Compare commits

..
Author SHA1 Message Date
Chris Eager 46aefc0cbe Add retry configuration to RemoveExpiredUsernameHoldsCommand 2025-03-25 11:46:05 -05:00
Chris Eager 9d4f9b4c12 Add retry configuration to RemoveExpiredBackupsCommand 2025-03-25 11:46:05 -05:00
Chris Eager 3591e6bebd Add retry configuration to RemoveExpiredAccountsCommand 2025-03-25 11:46:05 -05:00
Chris Eager e12ba6b15b Reduce page size in MessagesDynamoDb#mayHaveUrgentMessages 2025-03-25 11:45:47 -05:00
Chris Eager 744b05244d Add onErrorResume and retries to eligibility check in NotifyIdleDevicesCommand 2025-03-25 11:45:16 -05:00
Chris Eager c22b8fafa6 Update AWS SDK to 2.31.7 2025-03-25 11:44:54 -05:00
Ameya Lokare 2194cf46e1 Remove jaxb and jaxb-api version pins 2025-03-24 16:37:34 -07:00
Jonathan Klabunde Tomer 1a46ac122a add some tags to ProfileController.versionNotFound 2025-03-24 14:57:29 -07:00
Ameya Lokare 55f85a81c6 Update to the latest version of the spam filter 2025-03-24 13:26:53 -07:00
Chris Eager 5a8cb8a312 Revert "Skip shared multi-recipient message payloads for small messages"
This reverts commit db2cd20dcb.
2025-03-24 14:40:12 -05:00
Jon Chambers d641d1fc39 Update to the latest version of the spam filter 2025-03-24 11:17:49 -04:00
Jon Chambers df56c65b54 Validate device message sizes when distributing PNI keys 2025-03-24 10:58:38 -04:00
Jon Chambers 1346fcb59e Require that incoming messages have content 2025-03-24 10:58:38 -04:00
Jon Chambers 50f681ffe8 Centralize message length validation 2025-03-24 10:58:38 -04:00
Jon Chambers faef614d80 Parse message content as a byte array in request entities 2025-03-24 10:58:38 -04:00
Chris Eager db2cd20dcb Skip shared multi-recipient message payloads for small messages 2025-03-21 16:51:21 -05:00
Chris Eager 9ef6024291 Update to the latest version of the spam filter 2025-03-20 10:44:47 -05:00
Jon Chambers a643a6c0f0 Always record inbound message byte rate limit events 2025-03-20 10:44:10 -05:00
Chris Eager 82e21b0c21 Remove obsolete turn implementations 2025-03-20 10:38:14 -05:00
Chris Eager 50e298a4f4 Add counter for Redis events 2025-03-20 10:37:18 -05:00
Chris Eager a0b9c40f6c Add JettySslHandshakeMetrics 2025-03-20 10:36:52 -05:00
Ravi Khadiwala 359cf02161 Add new attachmentBackfill capability 2025-03-19 16:03:40 -05:00
Chris Eager 6a1f01f876 Remove unused executor service 2025-03-13 14:49:04 -04:00
Jon Chambers 0595acc48f Add a counter for messages removed from the message cache 2025-03-13 14:48:34 -04:00
Jon Chambers 46ff8d51dc Switch to remote aggregation for persister distribution summaries 2025-03-13 14:48:34 -04:00
Jon Chambers dcd80e11f4 Measure persisted message bytes 2025-03-13 14:48:34 -04:00
Jon Chambers e1b1c7db8d Normalize persister metric names; make metrics static final 2025-03-13 14:48:34 -04:00
Jon Chambers 99041bc593 Use a dedicated status code (and message) for "reauthentication required" 2025-03-13 14:48:17 -04:00
Ravi Khadiwala dbd14481ed Add a missing join to testTrimOnFullPrimaryQueue 2025-03-11 17:39:15 -05:00
ravi-signal e3160bc717 Add a dedicated size estimation method to MessagesCache 2025-03-10 16:09:05 -05:00
Chris Eager 6798958650 Update autoPagingIterable() usage to remove null params 2025-03-08 09:08:27 -08:00
Chris Eager 3a90c572b4 Ensure customer ID matches in StripeManager#cancelAllActiveSubscriptions 2025-03-08 08:35:43 -08:00
ravi-signal eab3c36d83 Dont discard ephemeral messages beyond what the persister consumes 2025-03-07 15:27:03 -06:00
Ravi Khadiwala b7fee7b426 Allow cancellation of an expired purchaseToken 2025-03-07 15:26:33 -06:00
ravi-signal 469955aec9 Treat a 410 for an IAP token as not found 2025-03-07 15:24:33 -06:00
Chris Eager d1c9dff2c5 Use WhisperServerService as base name for executor service metrics 2025-03-07 15:23:51 -06:00
Jonathan Klabunde Tomer 9491ebbe90 remove versionedExpirationTimer 2025-03-06 08:20:06 -08:00
Ravi Khadiwala 09b50383d7 Automatically trim primary queue when cache cannot be persisted 2025-03-05 15:56:00 -06:00
66 changed files with 848 additions and 2079 deletions

No files matched your search

@@ -8,7 +8,6 @@ package org.signal.integration;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Test;
@@ -27,11 +26,10 @@ public class MessagingTest {
try {
final byte[] expectedContent = "Hello, World!".getBytes(StandardCharsets.UTF_8);
final String contentBase64 = Base64.getEncoder().encodeToString(expectedContent);
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), contentBase64);
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), expectedContent);
final IncomingMessageList messages = new IncomingMessageList(List.of(message), false, true, System.currentTimeMillis());
final Pair<Integer, SendMessageResponse> sendMessage = Operations
Operations
.apiPut("/v1/messages/%s".formatted(userB.aciUuid().toString()), messages)
.authorized(userA)
.execute(SendMessageResponse.class);
@@ -40,7 +38,7 @@ public class MessagingTest {
.authorized(userB)
.execute(OutgoingMessageEntityList.class);
final byte[] actualContent = receiveMessages.getRight().messages().get(0).content();
final byte[] actualContent = receiveMessages.getRight().messages().getFirst().content();
assertArrayEquals(expectedContent, actualContent);
} finally {
Operations.deleteUser(userA);
+1 -13
View File
@@ -37,7 +37,7 @@
</modules>
<properties>
<aws.sdk2.version>2.29.48</aws.sdk2.version>
<aws.sdk2.version>2.31.7</aws.sdk2.version>
<braintree.version>3.37.0</braintree.version>
<commons-csv.version>1.12.0</commons-csv.version>
<commons-io.version>2.18.0</commons-io.version>
@@ -52,7 +52,6 @@
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.18.2</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>1.9.25</kotlin.version>
@@ -195,11 +194,6 @@
<artifactId>lettuce-core</artifactId>
<version>${lettuce.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
@@ -215,12 +209,6 @@
<artifactId>dropwizard-metrics-datadog</artifactId>
<version>${dropwizard-metrics-datadog.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>${jaxb.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
-1
View File
@@ -94,7 +94,6 @@ currentReportingKey.salt: AAAAAAAAAAA=
registrationService.collationKeySalt: AAAAAAAAAAA=
turn.secret: AAAAAAAAAAA=
turn.cloudflare.apiToken: ABCDEFGHIJKLM
linkDevice.secret: AAAAAAAAAAA=
-25
View File
@@ -473,7 +473,6 @@ keyTransparencyService:
clientPrivateKey: secret://keyTransparencyService.clientPrivateKey
turn:
secret: secret://turn.secret
cloudflare:
apiToken: secret://turn.cloudflare.apiToken
endpoint: https://rtc.live.cloudflare.com/v1/turn/keys/LMNOP/credentials/generate
@@ -490,30 +489,6 @@ turn:
linkDevice:
secret: secret://linkDevice.secret
maxmindCityDatabase:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
callingTurnDnsRecords:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
callingTurnPerformanceTable:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
callingTurnManualTable:
s3Region: a-region
s3Bucket: a-bucket
objectKey: an-object.tar.gz
maxSize: 32777216
noiseTunnel:
port: 8443
tlsKeyStoreFile: /path/to/file.p12
-10
View File
@@ -173,10 +173,6 @@
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
@@ -232,12 +228,6 @@
<version>1.27.1</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
@@ -301,27 +301,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration(Duration.ofMillis(1));
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory maxmindCityDatabase;
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory callingTurnDnsRecords;
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory callingTurnPerformanceTable;
@Valid
@NotNull
@JsonProperty
private S3ObjectMonitorFactory callingTurnManualTable;
@Valid
@NotNull
@JsonProperty
@@ -539,22 +518,6 @@ public class WhisperServerConfiguration extends Configuration {
return virtualThread;
}
public S3ObjectMonitorFactory getMaxmindCityDatabase() {
return maxmindCityDatabase;
}
public S3ObjectMonitorFactory getCallingTurnDnsRecords() {
return callingTurnDnsRecords;
}
public S3ObjectMonitorFactory getCallingTurnPerformanceTable() {
return callingTurnPerformanceTable;
}
public S3ObjectMonitorFactory getCallingTurnManualTable() {
return callingTurnManualTable;
}
public NoiseWebSocketTunnelConfiguration getNoiseWebSocketTunnelConfiguration() {
return noiseTunnel;
}
@@ -85,7 +85,6 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.auth.WebsocketRefreshApplicationEventListener;
import org.whispersystems.textsecuregcm.auth.grpc.ProhibitAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
@@ -509,8 +508,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// TODO: generally speaking this is a DynamoDB I/O executor for the accounts table; we should eventually have a general executor for speaking to the accounts table, but most of the server is still synchronous so this isn't widely useful yet
ExecutorService batchIdentityCheckExecutor = environment.lifecycle().executorService(name(getClass(), "batchIdentityCheck-%d")).minThreads(32).maxThreads(32).build();
ExecutorService multiRecipientMessageExecutor = environment.lifecycle()
.executorService(name(getClass(), "multiRecipientMessage-%d")).minThreads(64).maxThreads(64).build();
ExecutorService subscriptionProcessorExecutor = environment.lifecycle()
.executorService(name(getClass(), "subscriptionProcessor-%d"))
.maxThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
@@ -669,7 +666,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration().secret().value());
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
config.getTurnConfiguration().cloudflare().apiToken().value(),
config.getTurnConfiguration().cloudflare().endpoint(),
@@ -1094,7 +1090,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
@@ -15,8 +15,8 @@ import java.net.Inet6Address;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
@@ -127,11 +127,11 @@ public class CloudflareTurnCredentialsManager {
final CloudflareTurnResponse cloudflareTurnResponse = SystemMapper.jsonMapper()
.readValue(response.body(), CloudflareTurnResponse.class);
return TurnTokenGenerator.from(
return new TurnToken(
cloudflareTurnResponse.iceServers().username(),
cloudflareTurnResponse.iceServers().credential(),
Optional.ofNullable(cloudflareTurnUrls),
Optional.ofNullable(cloudflareTurnComposedUrls),
cloudflareTurnUrls == null ? Collections.emptyList() : cloudflareTurnUrls,
cloudflareTurnComposedUrls,
cloudflareTurnHostname
);
}
@@ -1,87 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
import org.whispersystems.textsecuregcm.util.Util;
public class TurnTokenGenerator {
private final byte[] turnSecret;
private static final String ALGORITHM = "HmacSHA1";
private static final String WithUrlsProtocol = "00";
private static final String WithIpsProtocol = "01";
public TurnTokenGenerator(final byte[] turnSecret) {
this.turnSecret = turnSecret;
}
public TurnToken generateWithTurnServerOptions(TurnServerOptions options) {
return generateToken(options.hostname(), options.urlsWithIps(), options.urlsWithHostname());
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private TurnToken generateToken(
String hostname,
Optional<List<String>> urlsWithIps,
Optional<List<String>> urlsWithHostname
) {
try {
final Mac mac = Mac.getInstance(ALGORITHM);
final long validUntilSeconds = Instant.now().plus(Duration.ofDays(1)).getEpochSecond();
final long user = Util.ensureNonNegativeInt(new SecureRandom().nextInt());
final String userTime = validUntilSeconds + ":" + user;
final String protocol = urlsWithIps.isEmpty() || urlsWithIps.get().isEmpty()
? WithUrlsProtocol
: WithIpsProtocol;
final String protocolUserTime = userTime + "#" + protocol;
mac.init(new SecretKeySpec(turnSecret, ALGORITHM));
final String password = Base64.getEncoder().encodeToString(mac.doFinal(protocolUserTime.getBytes()));
return from(
protocolUserTime,
password,
urlsWithHostname,
urlsWithIps,
hostname
);
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static TurnToken from(
String username,
String password,
Optional<List<String>> urls,
Optional<List<String>> urlsWithIps,
String hostname
) {
return new TurnToken(
username,
password,
urls.orElse(Collections.emptyList()),
urlsWithIps.orElse(Collections.emptyList()),
hostname
);
}
}
@@ -1,74 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
/** Uses DynamicConfig to help route a turn request */
public class DynamicConfigTurnRouter {
private static final Random rng = new Random();
public static final long RANDOMIZE_RATE_BASIS = 100_000;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public DynamicConfigTurnRouter(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public List<String> targetedUrls(final UUID aci) {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
.filter(config -> config.getEnrolledAcis().contains(aci))
.findFirst();
return enrolled
.map(turnUriConfiguration -> turnUriConfiguration.getUris().stream().toList())
.orElse(Collections.emptyList());
}
public List<String> randomUrls() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
// select from turn server sets by weighted choice
return WeightedRandomSelect.select(turnConfig
.getUriConfigs()
.stream()
.map(c -> new Pair<>(c.getUris(), c.getWeight())).toList());
}
public String getHostname() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
return turnConfig.getHostname();
}
public long getRandomizeRate() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
return turnConfig.getRandomizeRate();
}
public int getDefaultInstanceIpCount() {
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
return turnConfig.getDefaultInstanceIpCount();
}
public boolean shouldRandomize() {
long rate = getRandomizeRate();
return rate >= RANDOMIZE_RATE_BASIS || rng.nextLong(0, DynamicConfigTurnRouter.RANDOMIZE_RATE_BASIS) < rate;
}
}
@@ -1,190 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
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.InetAddress;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Returns routes based on performance tables, manually routing tables, and target routing. Falls back to a random Turn
* instance that the server knows about.
*/
public class TurnCallRouter {
private final Logger logger = LoggerFactory.getLogger(TurnCallRouter.class);
private final Supplier<CallDnsRecords> callDnsRecords;
private final Supplier<CallRoutingTable> performanceRouting;
private final Supplier<CallRoutingTable> manualRouting;
private final DynamicConfigTurnRouter configTurnRouter;
private final Supplier<DatabaseReader> geoIp;
// controls whether instance IPs are shuffled. using if & boolean is ~5x faster than a function pointer
private final boolean stableSelect;
public TurnCallRouter(
@Nonnull Supplier<CallDnsRecords> callDnsRecords,
@Nonnull Supplier<CallRoutingTable> performanceRouting,
@Nonnull Supplier<CallRoutingTable> manualRouting,
@Nonnull DynamicConfigTurnRouter configTurnRouter,
@Nonnull Supplier<DatabaseReader> geoIp,
boolean stableSelect
) {
this.performanceRouting = performanceRouting;
this.callDnsRecords = callDnsRecords;
this.manualRouting = manualRouting;
this.configTurnRouter = configTurnRouter;
this.geoIp = geoIp;
this.stableSelect = stableSelect;
}
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress
) {
return getRoutingFor(aci, clientAddress, this.configTurnRouter.getDefaultInstanceIpCount());
}
/**
* Gets Turn Instance addresses. Returns both the IPv4 and IPv6 addresses. Prefers to match the IP protocol of the
* client address in datacenter selection. Returns 2 instance options of the preferred protocol for every one instance
* of the other.
* @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,
@Nonnull final Optional<InetAddress> clientAddress,
final int instanceLimit
) {
try {
return getRoutingForInner(aci, clientAddress, instanceLimit);
} catch(Exception e) {
logger.error("Failed to perform routing", e);
return new TurnServerOptions(this.configTurnRouter.getHostname(), null, Optional.of(this.configTurnRouter.randomUrls()));
}
}
TurnServerOptions getRoutingForInner(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress,
final int instanceLimit
) {
String hostname = this.configTurnRouter.getHostname();
List<String> targetedUrls = this.configTurnRouter.targetedUrls(aci);
if(!targetedUrls.isEmpty()) {
return new TurnServerOptions(hostname, Optional.empty(), Optional.ofNullable(targetedUrls));
}
if(clientAddress.isEmpty() || this.configTurnRouter.shouldRandomize() || instanceLimit < 1) {
return new TurnServerOptions(hostname, Optional.empty(), Optional.ofNullable(this.configTurnRouter.randomUrls()));
}
CityResponse geoInfo;
try {
geoInfo = geoIp.get().city(clientAddress.get());
} catch (IOException | GeoIp2Exception e) {
throw new RuntimeException(e);
}
Optional<String> subdivision = !geoInfo.getSubdivisions().isEmpty()
? Optional.of(geoInfo.getSubdivisions().getFirst().getIsoCode())
: Optional.empty();
List<String> datacenters = this.manualRouting.get().getDatacentersFor(
clientAddress.get(),
geoInfo.getContinent().getCode(),
geoInfo.getCountry().getIsoCode(),
subdivision
);
if (datacenters.isEmpty()){
datacenters = this.performanceRouting.get().getDatacentersFor(
clientAddress.get(),
geoInfo.getContinent().getCode(),
geoInfo.getCountry().getIsoCode(),
subdivision
);
}
List<String> urlsWithIps = getUrlsForInstances(
selectInstances(
datacenters,
instanceLimit
));
return new TurnServerOptions(hostname, Optional.of(urlsWithIps), Optional.of(minimalRandomUrls()));
}
// Includes only the udp options in the randomUrls
private List<String> minimalRandomUrls(){
return this.configTurnRouter.randomUrls().stream()
.filter(s -> s.startsWith("turn:") && !s.endsWith("transport=tcp"))
.toList();
}
// 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();
}
CallDnsRecords dnsRecords = this.callDnsRecords.get();
List<List<InetAddress>> ipv4Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aByRegion().get(dc), instanceLimit, stableSelect))
.toList();
List<List<InetAddress>> ipv6Options = datacenters.stream()
.map(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), instanceLimit, stableSelect))
.toList();
List<InetAddress> ipv4Selection = selectFromOptions(ipv4Options, instanceLimit);
List<InetAddress> ipv6Selection = selectFromOptions(ipv6Options, instanceLimit);
return Stream.concat(
ipv4Selection.stream().map(InetAddress::getHostAddress),
// map ipv6 to RFC3986 format i.e. surrounded by brackets
ipv6Selection.stream().map(i -> String.format("[%s]", i.getHostAddress()))
).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);
}
private static List<String> getUrlsForInstances(List<String> instanceIps) {
return instanceIps.stream().flatMap(ip -> Stream.of(
String.format("turn:%s", ip),
String.format("turn:%s:80?transport=tcp", ip),
String.format("turns:%s:443?transport=tcp", ip)
)
).toList();
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import jakarta.validation.constraints.Positive;
@@ -15,8 +16,8 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
@NotBlank String endpoint,
@NotBlank long ttl,
@NotBlank List<String> urls,
@NotBlank List<String> urlsWithIps,
@NotNull @NotEmpty @Valid List<@NotBlank String> urls,
@NotNull @NotEmpty @Valid List<@NotBlank String> urlsWithIps,
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
@NotNull @Valid RetryConfiguration retry,
@NotBlank String hostname,
@@ -5,7 +5,5 @@
package org.whispersystems.textsecuregcm.configuration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
public record TurnConfiguration(SecretBytes secret, CloudflareTurnConfiguration cloudflare) {
public record TurnConfiguration(CloudflareTurnConfiguration cloudflare) {
}
@@ -42,10 +42,6 @@ public class DynamicConfiguration {
@Valid
private DynamicCaptchaConfiguration captcha = new DynamicCaptchaConfiguration();
@JsonProperty
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
@JsonProperty
@Valid
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
@@ -54,10 +50,6 @@ public class DynamicConfiguration {
@Valid
DynamicRateLimitPolicy rateLimitPolicy = new DynamicRateLimitPolicy(false);
@JsonProperty
@Valid
DynamicInboundMessageByteLimitConfiguration inboundMessageByteLimit = new DynamicInboundMessageByteLimitConfiguration(true);
@JsonProperty
@Valid
DynamicRegistrationConfiguration registrationConfiguration = new DynamicRegistrationConfiguration(false);
@@ -104,10 +96,6 @@ public class DynamicConfiguration {
return captcha;
}
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
return messagePersister;
}
@@ -116,10 +104,6 @@ public class DynamicConfiguration {
return rateLimitPolicy;
}
public DynamicInboundMessageByteLimitConfiguration getInboundMessageByteLimitConfiguration() {
return inboundMessageByteLimit;
}
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
return registrationConfiguration;
}
@@ -1,9 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
public record DynamicInboundMessageByteLimitConfiguration(boolean enforceInboundLimit) {
}
@@ -6,13 +6,33 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
public class DynamicMessagePersisterConfiguration {
@JsonProperty
private boolean persistenceEnabled = true;
/**
* If we have to trim a client's persisted queue to make room to persist from Redis to DynamoDB, how much extra room should we make
*/
@JsonProperty
private double trimOversizedQueueExtraRoomRatio = 1.5;
public DynamicMessagePersisterConfiguration() {}
@VisibleForTesting
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled, final double trimOversizedQueueExtraRoomRatio) {
this.persistenceEnabled = persistenceEnabled;
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
}
public boolean isPersistenceEnabled() {
return persistenceEnabled;
}
public double getTrimOversizedQueueExtraRoomRatio() {
return trimOversizedQueueExtraRoomRatio;
}
}
@@ -1,50 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import java.util.Collections;
import java.util.List;
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
public class DynamicTurnConfiguration {
@JsonProperty
private String hostname;
/**
* Rate at which to prioritize a random turn URL to exercise all endpoints.
* Based on a 100,000 basis, where 100,000 == 100%.
*/
@JsonProperty
private long randomizeRate = 5_000;
/**
* Number of instance ips to return in TURN routing request
*/
@JsonProperty
private int defaultInstanceIpCount = 0;
@JsonProperty
private List<@Valid TurnUriConfiguration> uriConfigs = Collections.emptyList();
public List<TurnUriConfiguration> getUriConfigs() {
return uriConfigs;
}
public long getRandomizeRate() {
return randomizeRate;
}
public int getDefaultInstanceIpCount() {
return defaultInstanceIpCount;
}
public String getHostname() {
return hostname;
}
}
@@ -51,6 +51,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.StaleDevices;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
@@ -94,6 +95,7 @@ public class AccountControllerV2 {
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
@ApiResponse(responseCode = "409", description = "Mismatched number of devices or device ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
@ApiResponse(responseCode = "410", description = "Mismatched registration ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = StaleDevices.class)))
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@ApiResponse(responseCode = "423", content = @Content(schema = @Schema(implementation = RegistrationLockFailure.class)))
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
@@ -143,7 +145,8 @@ public class AccountControllerV2 {
request.devicePniSignedPrekeys(),
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds());
request.pniRegistrationIds(),
userAgentString);
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (MismatchedDevicesException e) {
@@ -159,6 +162,8 @@ public class AccountControllerV2 {
.build());
} catch (IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
}
@@ -176,6 +181,7 @@ public class AccountControllerV2 {
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
@ApiResponse(responseCode = "410", description = "The registration IDs provided for some devices do not match those stored on the server.",
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
@Mutable @Auth final AuthenticatedDevice authenticatedDevice,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString,
@@ -196,7 +202,8 @@ public class AccountControllerV2 {
request.devicePniSignedPrekeys(),
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds());
request.pniRegistrationIds(),
userAgentString);
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (MismatchedDevicesException e) {
@@ -212,6 +219,8 @@ public class AccountControllerV2 {
.build());
} catch (IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
}
@@ -7,11 +7,8 @@ package org.whispersystems.textsecuregcm.controllers;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
@@ -59,11 +56,9 @@ import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.ServiceId;
@@ -80,7 +75,6 @@ import org.whispersystems.textsecuregcm.auth.CombinedUnidentifiedSenderAccessKey
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountMismatchedDevices;
import org.whispersystems.textsecuregcm.entities.AccountStaleDevices;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
@@ -105,6 +99,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
@@ -113,7 +108,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
@@ -149,7 +143,6 @@ public class MessageController {
private final ReportMessageManager reportMessageManager;
private final Scheduler messageDeliveryScheduler;
private final ClientReleaseManager clientReleaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ServerSecretParams serverSecretParams;
private final SpamChecker spamChecker;
private final MessageMetrics messageMetrics;
@@ -160,10 +153,7 @@ public class MessageController {
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
private static final String LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "largeMessage");
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
@@ -189,10 +179,6 @@ public class MessageController {
private static final String ENDPOINT_TYPE_SINGLE = "single";
private static final String ENDPOINT_TYPE_MULTI = "multi";
@VisibleForTesting
static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
private static final long LARGE_MESSAGE_SIZE = DataSize.kibibytes(8).toBytes();
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
// for additional details.
@@ -213,7 +199,6 @@ public class MessageController {
ReportMessageManager reportMessageManager,
Scheduler messageDeliveryScheduler,
final ClientReleaseManager clientReleaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ServerSecretParams serverSecretParams,
final SpamChecker spamChecker,
final MessageMetrics messageMetrics,
@@ -231,7 +216,6 @@ public class MessageController {
this.reportMessageManager = reportMessageManager;
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.clientReleaseManager = clientReleaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.serverSecretParams = serverSecretParams;
this.spamChecker = spamChecker;
this.messageMetrics = messageMetrics;
@@ -330,9 +314,13 @@ public class MessageController {
int totalContentLength = 0;
for (final IncomingMessage message : messages.messages()) {
final int contentLength = decodedSize(message.content());
final int contentLength = message.content().length;
validateContentLength(contentLength, false, isSyncMessage, isStory, userAgent);
try {
MessageSender.validateContentLength(contentLength, false, isSyncMessage, isStory, userAgent);
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
totalContentLength += contentLength;
}
@@ -340,10 +328,8 @@ public class MessageController {
try {
rateLimiters.getInboundMessageBytes().validate(destinationIdentifier.uuid(), totalContentLength);
} catch (final RateLimitExceededException e) {
if (dynamicConfigurationManager.getConfiguration().getInboundMessageByteLimitConfiguration().enforceInboundLimit()) {
messageByteLimitEstimator.add(destinationIdentifier.uuid().toString());
throw e;
}
messageByteLimitEstimator.add(destinationIdentifier.uuid().toString());
throw e;
}
try {
@@ -522,8 +508,13 @@ public class MessageController {
}
// Verify that the message isn't too large before performing more expensive validations
multiRecipientMessage.getRecipients().values().forEach(recipient ->
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient), true, false, isStory, userAgent));
multiRecipientMessage.getRecipients().values().forEach(recipient -> {
try {
MessageSender.validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient), true, false, isStory, userAgent);
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
});
// Check that the request is well-formed and doesn't contain repeated entries for the same device for the same
// recipient
@@ -929,53 +920,4 @@ public class MessageController {
throw e;
}
}
private void validateContentLength(final int contentLength,
final boolean isMultiRecipientMessage,
final boolean isSyncMessage,
final boolean isStory,
final String userAgent) {
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("oversize", String.valueOf(oversize)),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(contentLength);
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.increment();
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
}
if (contentLength > LARGE_MESSAGE_SIZE) {
Metrics.counter(
LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage))))
.increment();
}
}
@VisibleForTesting
static int decodedSize(final String base64) {
final int padding;
if (StringUtils.endsWith(base64, "==")) {
padding = 2;
} else if (StringUtils.endsWith(base64, "=")) {
padding = 1;
} else {
padding = 0;
}
return ((StringUtils.length(base64) - padding) * 3) / 4;
}
}
@@ -9,8 +9,8 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.base.Preconditions;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@@ -79,6 +79,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -121,7 +122,7 @@ public class ProfileController {
private static final String EXPIRING_PROFILE_KEY_CREDENTIAL_TYPE = "expiringProfileKey";
private static final Counter VERSION_NOT_FOUND_COUNTER = Metrics.counter(name(ProfileController.class, "versionNotFound"));
private static final String VERSION_NOT_FOUND_COUNTER_NAME = name(ProfileController.class, "versionNotFound");
public ProfileController(
Clock clock,
@@ -237,6 +238,7 @@ public class ProfileController {
return buildVersionedProfileResponse(targetAccount,
version,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false),
false,
containerRequestContext);
}
@@ -390,20 +392,27 @@ public class ProfileController {
.orElse(null);
return new ExpiringProfileKeyCredentialProfileResponse(
buildVersionedProfileResponse(account, version, isSelf, containerRequestContext),
buildVersionedProfileResponse(account, version, isSelf, true, containerRequestContext),
expiringProfileKeyCredentialResponse);
}
private VersionedProfileResponse buildVersionedProfileResponse(final Account account,
final String version,
final boolean isSelf,
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
if (maybeProfile.isEmpty()) {
// Hypothesis: this should basically never happen since clients can't delete versions
VERSION_NOT_FOUND_COUNTER.increment();
Metrics.counter(
VERSION_NOT_FOUND_COUNTER_NAME,
Tags.of(
"self", String.valueOf(isSelf),
"credential_request", String.valueOf(hasCredentialRequest),
"platform", UserAgentTagUtil.getPlatformTag(containerRequestContext.getHeaderString("User-Agent")).getValue()))
.increment();
}
final byte[] name = maybeProfile.map(VersionedProfile::name).orElse(null);
@@ -4,18 +4,31 @@
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.protobuf.ByteString;
import com.webauthn4j.converter.jackson.deserializer.json.ByteArrayBase64Deserializer;
import io.micrometer.core.instrument.Metrics;
import jakarta.validation.constraints.AssertTrue;
import java.util.Base64;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import java.util.Arrays;
import java.util.Objects;
public record IncomingMessage(int type, byte destinationDeviceId, int destinationRegistrationId, String content) {
public record IncomingMessage(int type,
byte destinationDeviceId,
int destinationRegistrationId,
@JsonDeserialize(using = ByteArrayBase64Deserializer.class)
@NotNull
// Note that max size is validated elsewhere in the interest of controlling responses and
// reporting additional metrics.
@Size(min = 1)
byte[] content) {
private static final String REJECT_INVALID_ENVELOPE_TYPE_COUNTER_NAME =
MetricsUtil.name(IncomingMessage.class, "rejectInvalidEnvelopeType");
@@ -50,9 +63,7 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken));
}
if (StringUtils.isNotEmpty(content())) {
envelopeBuilder.setContent(ByteString.copyFrom(Base64.getDecoder().decode(content())));
}
envelopeBuilder.setContent(ByteString.copyFrom(content()));
return envelopeBuilder.build();
}
@@ -69,4 +80,17 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
return true;
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof IncomingMessage(int otherType, byte otherDeviceId, int otherRegistrationId, byte[] otherContent)))
return false;
return type == otherType && destinationDeviceId == otherDeviceId
&& destinationRegistrationId == otherRegistrationId && Objects.deepEquals(content, otherContent);
}
@Override
public int hashCode() {
return Objects.hash(type, destinationDeviceId, destinationRegistrationId, Arrays.hashCode(content));
}
}
@@ -1,102 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.geo;
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.S3ObjectMonitorFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.s3.S3ObjectMonitor;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
public class MaxMindDatabaseManager implements Supplier<DatabaseReader>, Managed {
private final S3ObjectMonitor databaseMonitor;
private final AtomicReference<DatabaseReader> databaseReader = new AtomicReference<>();
private final String databaseTag;
private final Timer refreshTimer;
private static final Logger log = LoggerFactory.getLogger(MaxMindDatabaseManager.class);
public MaxMindDatabaseManager(final ScheduledExecutorService executorService,
final AwsCredentialsProvider awsCredentialsProvider, final S3ObjectMonitorFactory configuration,
final String databaseTag) {
this.databaseMonitor = configuration.build(awsCredentialsProvider, executorService);
this.databaseTag = databaseTag;
this.refreshTimer = Metrics.timer(MetricsUtil.name(MaxMindDatabaseManager.class, "refresh"), "db", databaseTag);
}
private void handleDatabaseChanged(final InputStream inputStream) {
refreshTimer.record(() -> {
boolean foundDatabaseEntry = false;
try (final InputStream bufferedInputStream = new BufferedInputStream(inputStream);
final GzipCompressorInputStream gzipInputStream = new GzipCompressorInputStream(bufferedInputStream);
final TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzipInputStream)) {
ArchiveEntry nextEntry;
while ((nextEntry = tarInputStream.getNextEntry()) != null) {
if (nextEntry.getName().toLowerCase().endsWith(".mmdb")) {
foundDatabaseEntry = true;
final DatabaseReader oldReader = databaseReader.getAndSet(
new DatabaseReader.Builder(tarInputStream).withCache(new CHMCache()).build()
);
if (oldReader != null) {
oldReader.close();
}
break;
}
}
} catch (final IOException e) {
log.error(String.format("Failed to load MaxMind database, tag %s", databaseTag));
}
if (!foundDatabaseEntry) {
log.warn(String.format("No .mmdb entry loaded from input stream, tag %s", databaseTag));
}
});
}
@Override
public void start() throws Exception {
databaseMonitor.start(this::handleDatabaseChanged);
}
@Override
public void stop() throws Exception {
databaseMonitor.stop();
final DatabaseReader reader = databaseReader.getAndSet(null);
if (reader != null) {
reader.close();
}
}
@Override
public DatabaseReader get() {
return this.databaseReader.get();
}
}
@@ -18,8 +18,8 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_STORAGE -> DeviceCapability.STORAGE;
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_DELETE_SYNC -> DeviceCapability.DELETE_SYNC;
case DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER -> DeviceCapability.VERSIONED_EXPIRATION_TIMER;
case DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION -> DeviceCapability.STORAGE_SERVICE_RECORD_KEY_ROTATION;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Unrecognized device capability").asRuntimeException();
};
}
@@ -29,8 +29,8 @@ public class DeviceCapabilityUtil {
case STORAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE;
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case DELETE_SYNC -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC;
case VERSIONED_EXPIRATION_TIMER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER;
case STORAGE_SERVICE_RECORD_KEY_ROTATION -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION;
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
};
}
}
@@ -12,6 +12,7 @@ import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.binder.jetty.JettySslHandshakeMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
@@ -72,6 +73,9 @@ public class MetricsUtil {
Metrics.addRegistry(dogstatsdMeterRegistry);
}
environment.lifecycle().addServerLifecycleListener(
server -> JettySslHandshakeMetrics.addToAllConnectors(server, Metrics.globalRegistry));
environment.lifecycle().addEventListener(new ApplicationShutdownMonitor(Metrics.globalRegistry));
environment.lifecycle().addEventListener(
new MicrometerRegistryManager(Metrics.globalRegistry,
@@ -8,11 +8,18 @@ import static com.codahale.metrics.MetricRegistry.name;
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
@@ -34,6 +41,11 @@ public class MessageSender {
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
// Note that these names deliberately reference `MessageController` for metric continuity
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageController.class, "rejectOversizeMessage");
private static final String LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageController.class, "largeMessage");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
private static final String SEND_COUNTER_NAME = name(MessageSender.class, "sendMessage");
private static final String CHANNEL_TAG_NAME = "channel";
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
@@ -42,6 +54,10 @@ public class MessageSender {
private static final String STORY_TAG_NAME = "story";
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
@VisibleForTesting
public static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
private static final long LARGE_MESSAGE_SIZE = DataSize.kibibytes(8).toBytes();
public MessageSender(final MessagesManager messagesManager, final PushNotificationManager pushNotificationManager) {
this.messagesManager = messagesManager;
this.pushNotificationManager = pushNotificationManager;
@@ -137,4 +153,40 @@ public class MessageSender {
return "none";
}
}
public static void validateContentLength(final int contentLength,
final boolean isMultiRecipientMessage,
final boolean isSyncMessage,
final boolean isStory,
final String userAgent) throws MessageTooLargeException {
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("oversize", String.valueOf(oversize)),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(contentLength);
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.increment();
throw new MessageTooLargeException();
}
if (contentLength > LARGE_MESSAGE_SIZE) {
Metrics.counter(
LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage))))
.increment();
}
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class MessageTooLargeException extends NoStackTraceException {
}
@@ -5,23 +5,31 @@
package org.whispersystems.textsecuregcm.redis;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
import io.lettuce.core.event.connection.ConnectionEvent;
import io.lettuce.core.resource.ClientResources;
import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConnectionEventLogger {
private static final Logger logger = LoggerFactory.getLogger(ConnectionEventLogger.class);
private static final String EVENT_COUNTER_NAME = name(ConnectionEventLogger.class, "events");
public static void logConnectionEvents(final ClientResources clientResources) {
clientResources.eventBus().get().subscribe(event -> {
if (event instanceof ConnectionEvent) {
logger.debug("Connection event: {}", event);
} else if (event instanceof ClusterTopologyChangedEvent) {
logger.info("Cluster topology changed: {}", event);
}
});
}
private static final Logger logger = LoggerFactory.getLogger(ConnectionEventLogger.class);
public static void logConnectionEvents(final ClientResources clientResources) {
clientResources.eventBus().get().subscribe(event -> {
if (event instanceof ConnectionEvent) {
logger.debug("Connection event: {}", event);
} else if (event instanceof ClusterTopologyChangedEvent) {
logger.info("Cluster topology changed: {}", event);
}
Metrics.counter(EVENT_COUNTER_NAME, "type", event.getClass().getSimpleName()).increment();
});
}
}
@@ -5,15 +5,12 @@
package org.whispersystems.textsecuregcm.storage;
import com.google.protobuf.ByteString;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -25,6 +22,7 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
public class ChangeNumberManager {
@@ -45,8 +43,9 @@ public class ChangeNumberManager {
@Nullable final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
@Nullable final List<IncomingMessage> deviceMessages,
@Nullable final Map<Byte, Integer> pniRegistrationIds)
throws InterruptedException, MismatchedDevicesException, StaleDevicesException {
@Nullable final Map<Byte, Integer> pniRegistrationIds,
@Nullable final String senderUserAgent)
throws InterruptedException, MismatchedDevicesException, StaleDevicesException, MessageTooLargeException {
if (ObjectUtils.allNotNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds)) {
// AccountsManager validates the device set on deviceSignedPreKeys and pniRegistrationIds
@@ -66,14 +65,14 @@ public class ChangeNumberManager {
if (pniIdentityKey == null) {
return account;
}
return updatePniKeys(account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, deviceMessages, pniRegistrationIds);
return updatePniKeys(account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, deviceMessages, pniRegistrationIds, senderUserAgent);
}
final Account updatedAccount = accountsManager.changeNumber(
account, number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
if (deviceMessages != null) {
sendDeviceMessages(updatedAccount, deviceMessages);
sendDeviceMessages(updatedAccount, deviceMessages, senderUserAgent);
}
return updatedAccount;
@@ -84,7 +83,9 @@ public class ChangeNumberManager {
final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
final List<IncomingMessage> deviceMessages,
final Map<Byte, Integer> pniRegistrationIds) throws MismatchedDevicesException, StaleDevicesException {
final Map<Byte, Integer> pniRegistrationIds,
final String senderUserAgent) throws MismatchedDevicesException, StaleDevicesException, MessageTooLargeException {
validateDeviceMessages(account, deviceMessages);
// Don't try to be smart about ignoring unnecessary retries. If we make literally no change we will skip the ddb
@@ -92,7 +93,7 @@ public class ChangeNumberManager {
final Account updatedAccount = accountsManager.updatePniKeys(
account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
sendDeviceMessages(updatedAccount, deviceMessages);
sendDeviceMessages(updatedAccount, deviceMessages, senderUserAgent);
return updatedAccount;
}
@@ -113,18 +114,28 @@ public class ChangeNumberManager {
false);
}
private void sendDeviceMessages(final Account account, final List<IncomingMessage> deviceMessages) {
private void sendDeviceMessages(final Account account,
final List<IncomingMessage> deviceMessages,
final String senderUserAgent) throws MessageTooLargeException {
for (final IncomingMessage message : deviceMessages) {
MessageSender.validateContentLength(message.content().length,
false,
true,
false,
senderUserAgent);
}
try {
final long serverTimestamp = System.currentTimeMillis();
messageSender.sendMessages(account, deviceMessages.stream()
.filter(message -> getMessageContent(message).isPresent())
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setClientTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(getMessageContent(message).orElseThrow()))
.setContent(ByteString.copyFrom(message.content()))
.setSourceServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
.setSourceDevice(Device.PRIMARY_ID)
.setUpdatedPni(account.getPhoneNumberIdentifier().toString())
@@ -136,18 +147,4 @@ public class ChangeNumberManager {
throw e;
}
}
private static Optional<byte[]> getMessageContent(final IncomingMessage message) {
if (StringUtils.isEmpty(message.content())) {
logger.warn("Message has no content");
return Optional.empty();
}
try {
return Optional.of(Base64.getDecoder().decode(message.content()));
} catch (final IllegalArgumentException e) {
logger.warn("Failed to parse message content", e);
return Optional.empty();
}
}
}
@@ -11,12 +11,21 @@ public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALL_DEVICES, true, true),
VERSIONED_EXPIRATION_TIMER("versionedExpirationTimer", AccountCapabilityMode.ALL_DEVICES, true, true),
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true);
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true);
public enum AccountCapabilityMode {
/**
* The account will have the capability iff the primary device has the capability
*/
PRIMARY_DEVICE,
/**
* The account will have the capability iff any device on the account has the capability
*/
ANY_DEVICE,
/**
* The account will have the capability iff all devices on the account have the capability
*/
ALL_DEVICES,
}
@@ -25,6 +34,18 @@ public enum DeviceCapability {
private final boolean preventDowngrade;
private final boolean includeInProfile;
/**
* Create a DeviceCapability
*
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server
*/
DeviceCapability(final String name,
final AccountCapabilityMode accountCapabilityMode,
final boolean preventDowngrade,
@@ -18,11 +18,17 @@ import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
public class MessagePersister implements Managed {
@@ -30,26 +36,30 @@ public class MessagePersister implements Managed {
private final MessagesCache messagesCache;
private final MessagesManager messagesManager;
private final AccountsManager accountsManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Duration persistDelay;
private final Thread[] workerThreads;
private volatile boolean running;
private final Timer getQueuesTimer = Metrics.timer(name(MessagePersister.class, "getQueues"));
private final Timer persistQueueTimer = Metrics.timer(name(MessagePersister.class, "persistQueue"));
private final Counter persistQueueExceptionMeter = Metrics.counter(
name(MessagePersister.class, "persistQueueException"));
private final Counter oversizedQueueCounter = Metrics.counter(name(MessagePersister.class, "persistQueueOversized"));
private final DistributionSummary queueCountDistributionSummery = DistributionSummary.builder(
private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized");
private static final Timer GET_QUEUES_TIMER = Metrics.timer(name(MessagePersister.class, "getQueues"));
private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue"));
private static final Counter PERSIST_QUEUE_EXCEPTION_METER =
Metrics.counter(name(MessagePersister.class, "persistQueueException"));
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private final DistributionSummary queueSizeDistributionSummery = DistributionSummary.builder(
private static final DistributionSummary QUEUE_SIZE_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueSize"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
static final int QUEUE_BATCH_LIMIT = 100;
@@ -66,12 +76,12 @@ public class MessagePersister implements Managed {
final AccountsManager accountsManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final Duration persistDelay,
final int dedicatedProcessWorkerThreadCount
) {
final int dedicatedProcessWorkerThreadCount) {
this.messagesCache = messagesCache;
this.messagesManager = messagesManager;
this.accountsManager = accountsManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.persistDelay = persistDelay;
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
@@ -82,7 +92,7 @@ public class MessagePersister implements Managed {
.isPersistenceEnabled()) {
try {
final int queuesPersisted = persistNextQueues(Instant.now());
queueCountDistributionSummery.record(queuesPersisted);
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
if (queuesPersisted == 0) {
Util.sleep(100);
@@ -134,7 +144,7 @@ public class MessagePersister implements Managed {
int queuesPersisted = 0;
do {
queuesToPersist = getQueuesTimer.record(
queuesToPersist = GET_QUEUES_TIMER.record(
() -> messagesCache.getQueuesToPersist(slot, currentTime.minus(persistDelay), QUEUE_BATCH_LIMIT));
for (final String queue : queuesToPersist) {
@@ -154,12 +164,15 @@ public class MessagePersister implements Managed {
try {
persistQueue(maybeAccount.get(), maybeDevice.get());
} catch (final Exception e) {
persistQueueExceptionMeter.increment();
PERSIST_QUEUE_EXCEPTION_METER.increment();
logger.warn("Failed to persist queue {}::{}; will schedule for retry", accountUuid, deviceId, e);
messagesCache.addQueueToPersist(accountUuid, deviceId);
Util.sleep(EXCEPTION_PAUSE_MILLIS);
if (!(e instanceof MessagePersistenceException)) {
// Pause after unexpected exceptions
Util.sleep(EXCEPTION_PAUSE_MILLIS);
}
}
}
@@ -202,24 +215,81 @@ public class MessagePersister implements Managed {
} while (!messages.isEmpty());
queueSizeDistributionSummery.record(messageCount);
QUEUE_SIZE_DISTRIBUTION_SUMMARY.record(messageCount);
} catch (ItemCollectionSizeLimitExceededException e) {
oversizedQueueCounter.increment();
maybeUnlink(account, deviceId); // may throw, in which case we'll retry later by the usual mechanism
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
// may throw, in which case we'll retry later by the usual mechanism
if (isPrimary) {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
account.getUuid(), deviceId);
trimQueue(account, deviceId);
throw new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed");
} else {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", account.getUuid(),
deviceId);
accountsManager.removeDevice(account, deviceId).join();
}
} finally {
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
sample.stop(persistQueueTimer);
sample.stop(PERSIST_QUEUE_TIMER);
}
}
@VisibleForTesting
void maybeUnlink(final Account account, byte destinationDeviceId) throws MessagePersistenceException {
if (destinationDeviceId == Device.PRIMARY_ID) {
throw new MessagePersistenceException("primary device has a full queue");
}
private void trimQueue(final Account account, byte deviceId) {
final UUID aci = account.getIdentifier(IdentityType.ACI);
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", account.getUuid(), destinationDeviceId);
accountsManager.removeDevice(account, destinationDeviceId).join();
final Optional<Device> maybeDevice = account.getDevice(deviceId);
if (maybeDevice.isEmpty()) {
logger.warn("Not deleting messages for overfull queue {}::{}, deviceId {} does not exist",
aci, deviceId, deviceId);
return;
}
final Device device = maybeDevice.get();
// Calculate how many bytes we should trim
final long cachedMessageBytes = messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId).join();
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
.getMessagePersisterConfiguration()
.getTrimOversizedQueueExtraRoomRatio();
final long targetDeleteBytes = Math.round(cachedMessageBytes * extraRoomRatio);
final AtomicLong oldestMessage = new AtomicLong(0L);
final AtomicLong newestMessage = new AtomicLong(0L);
final AtomicLong bytesDeleted = new AtomicLong(0L);
// Iterate from the oldest message until we've removed targetDeleteBytes
final Pair<Long, Long> outcomes = Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
.concatMap(envelope -> {
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes) {
return Mono.just(Optional.<MessageProtos.Envelope>empty());
}
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
newestMessage.set(envelope.getServerTimestamp());
return Mono.just(Optional.of(envelope));
})
.takeWhile(Optional::isPresent)
.flatMap(maybeEnvelope -> {
final MessageProtos.Envelope envelope = maybeEnvelope.get();
TRIMMED_MESSAGE_COUNTER.increment();
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
return Mono
.fromCompletionStage(() -> messagesManager
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
.retryWhen(Retry.backoff(5, Duration.ofSeconds(1)))
.map(Optional::isPresent);
})
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
? Pair.of(acc.getLeft() + 1, acc.getRight())
: Pair.of(acc.getLeft(), acc.getRight() + 1))
.block();
logger.warn(
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
aci, deviceId,
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
targetDeleteBytes, cachedMessageBytes,
outcomes.getLeft(), outcomes.getRight());
}
}
@@ -10,6 +10,9 @@ import static com.codahale.metrics.MetricRegistry.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import io.lettuce.core.Limit;
import io.lettuce.core.Range;
import io.lettuce.core.ScoredValue;
import io.lettuce.core.ZAddArgs;
import io.lettuce.core.cluster.SlotHash;
import io.micrometer.core.instrument.Counter;
@@ -31,6 +34,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
import java.util.function.Predicate;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
@@ -130,6 +134,7 @@ public class MessagesCache {
private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid"));
private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView"));
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
private final Counter removeMessageCounter = Metrics.counter(name(MessagesCache.class, "remove"));
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
name(MessagesCache.class, "staleEphemeralMessages"));
private final Counter staleMrmMessagesCounter = Metrics.counter(name(MessagesCache.class, "staleMrmMessages"));
@@ -145,7 +150,8 @@ public class MessagesCache {
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
private static final ByteString STALE_MRM_KEY = ByteString.copyFromUtf8("stale");
@VisibleForTesting
static final ByteString STALE_MRM_KEY = ByteString.copyFromUtf8("stale");
@VisibleForTesting
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
@@ -268,7 +274,13 @@ public class MessagesCache {
(serviceId, keysToUpdate) -> removeRecipientViewFromMrmData(keysToUpdate, serviceId, destinationDevice));
return removedMessages;
}, messageDeletionExecutorService).whenComplete((ignored, throwable) -> sample.stop(removeByGuidTimer));
}, messageDeletionExecutorService).whenComplete((removedMessages, throwable) -> {
if (removedMessages != null) {
removeMessageCounter.increment(removedMessages.size());
}
sample.stop(removeByGuidTimer);
});
}
@@ -528,6 +540,37 @@ public class MessagesCache {
});
}
/**
* Estimate the size of the cached queue if it were to be persisted
* @param accountUuid The account identifier
* @param destinationDevice The destination device id
* @return A future that completes with the approximate size of stored messages that need to be persisted
*/
CompletableFuture<Long> estimatePersistedQueueSizeBytes(final UUID accountUuid, final byte destinationDevice) {
final Function<Optional<Long>, Mono<List<ScoredValue<byte[]>>>> getNextPage = (Optional<Long> start) ->
Mono.fromCompletionStage(() -> redisCluster.withBinaryCluster(connection ->
connection.async().zrangebyscoreWithScores(
getMessageQueueKey(accountUuid, destinationDevice),
Range.from(
start.map(Range.Boundary::excluding).orElse(Range.Boundary.unbounded()),
Range.Boundary.unbounded()),
Limit.from(PAGE_SIZE))));
final Flux<byte[]> allSerializedMessages = getNextPage.apply(Optional.empty())
.expand(scoredValues -> {
if (scoredValues.isEmpty()) {
return Mono.empty();
}
long lastTimestamp = (long) scoredValues.getLast().getScore();
return getNextPage.apply(Optional.of(lastTimestamp));
})
.concatMap(scoredValues -> Flux.fromStream(scoredValues.stream().map(ScoredValue::getValue)));
return parseAndFetchMrms(allSerializedMessages, destinationDevice)
.filter(Predicate.not(envelope -> envelope.getEphemeral() || isStaleMrmMessage(envelope)))
.reduce(0L, (acc, envelope) -> acc + envelope.getSerializedSize())
.toFuture();
}
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
final int limit) {
@@ -536,25 +579,7 @@ public class MessagesCache {
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
final Flux<MessageProtos.Envelope> allMessages = Flux.fromIterable(messages)
.mapNotNull(message -> {
try {
return MessageProtos.Envelope.parseFrom(message);
} catch (InvalidProtocolBufferException e) {
logger.warn("Failed to parse envelope", e);
return null;
}
})
.concatMap(message -> {
final Mono<MessageProtos.Envelope> messageMono;
if (message.hasSharedMrmKey()) {
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
} else {
messageMono = Mono.just(message);
}
return messageMono;
});
final Flux<MessageProtos.Envelope> allMessages = parseAndFetchMrms(Flux.fromIterable(messages), destinationDevice);
final Flux<MessageProtos.Envelope> messagesToPersist = allMessages
.filter(Predicate.not(envelope ->
@@ -575,6 +600,28 @@ public class MessagesCache {
.block(Duration.ofSeconds(5));
}
private Flux<MessageProtos.Envelope> parseAndFetchMrms(final Flux<byte[]> serializedMessages, final byte destinationDevice) {
return serializedMessages
.mapNotNull(message -> {
try {
return MessageProtos.Envelope.parseFrom(message);
} catch (InvalidProtocolBufferException e) {
logger.warn("Failed to parse envelope", e);
return null;
}
})
.concatMap(message -> {
final Mono<MessageProtos.Envelope> messageMono;
if (message.hasSharedMrmKey()) {
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
} else {
messageMono = Mono.just(message);
}
return messageMono;
});
}
public CompletableFuture<Void> clear(final UUID destinationUuid) {
return CompletableFuture.allOf(
Device.ALL_POSSIBLE_DEVICE_IDS.stream()
@@ -11,7 +11,6 @@ import static io.micrometer.core.instrument.Metrics.timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.InvalidProtocolBufferException;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Duration;
@@ -24,7 +23,6 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Predicate;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,6 +56,9 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
@VisibleForTesting
static final String LOCAL_INDEX_MESSAGE_UUID_KEY_SORT = "U";
@VisibleForTesting
static final int MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT = 20;
private static final String KEY_TTL = "E";
private static final String KEY_ENVELOPE_BYTES = "EB";
@@ -69,8 +70,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private final ExecutorService messageDeletionExecutor;
private final Scheduler messageDeletionScheduler;
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
public MessagesDynamoDb(DynamoDbClient dynamoDb, DynamoDbAsyncClient dynamoDbAsyncClient, String tableName,
@@ -128,7 +127,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
public CompletableFuture<Boolean> mayHaveUrgentMessages(final UUID accountIdentifier, final Device device) {
return Flux.from(load(accountIdentifier, device, null))
return Flux.from(load(accountIdentifier, device, MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT))
.any(MessageProtos.Envelope::getUrgent)
.toFuture();
}
@@ -48,6 +48,9 @@ public class MessagesManager {
private static final Counter PERSIST_MESSAGE_COUNTER = Metrics.counter(
name(MessagesManager.class, "persistMessage"));
private static final Counter PERSIST_MESSAGE_BYTES_COUNTER = Metrics.counter(
name(MessagesManager.class, "persistMessageBytes"));
private static final String MAY_HAVE_MESSAGES_COUNTER_NAME =
MetricsUtil.name(MessagesManager.class, "mayHaveMessages");
@@ -276,6 +279,9 @@ public class MessagesManager {
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids)
.get(30, TimeUnit.SECONDS).size();
PERSIST_MESSAGE_COUNTER.increment(messages.size());
PERSIST_MESSAGE_BYTES_COUNTER.increment(messages.stream()
.mapToInt(Envelope::getSerializedSize)
.sum());
} catch (InterruptedException | ExecutionException | TimeoutException e) {
logger.warn("Failed to remove messages from cache", e);
@@ -142,7 +142,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
// We've already acknowledged this purchase on a previous attempt, nothing to do
return CompletableFuture.completedFuture(null);
}
return executeAsync(pub -> pub.purchases().subscriptions()
return executeTokenOperation(pub -> pub.purchases().subscriptions()
.acknowledge(packageName, productId, purchaseToken, new SubscriptionPurchasesAcknowledgeRequest()));
}
@@ -217,9 +217,11 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
}
final SubscriptionPurchaseLineItem purchase = getLineItem(subscription);
return executeAsync(pub ->
return executeTokenOperation(pub ->
pub.purchases().subscriptions().cancel(packageName, purchase.getProductId(), purchaseToken));
});
})
// If the subscription is not found, no need to do anything
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.NotFound.class, e -> null));
}
@Override
@@ -339,26 +341,37 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
return CompletableFuture.supplyAsync(() -> {
try {
return apiCall.req(androidPublisher).execute();
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
}
logger.warn("Unexpected HTTP status code {} from androidpublisher: {}", e.getStatusCode(), e.getDetails(), e);
throw ExceptionUtils.wrap(e);
} catch (HttpResponseException e) {
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
}
logger.warn("Unexpected HTTP status code {} from androidpublisher", e.getStatusCode(), e);
throw ExceptionUtils.wrap(e);
} catch (IOException e) {
throw ExceptionUtils.wrap(e);
}
}, executor);
}
/**
* Asynchronously execute a synchronous API call on a purchaseToken, mapping expected errors to the appropriate
* {@link SubscriptionException}
*
* @param apiCall An API call that operates on a purchaseToken
* @param <R> The result of the API call
* @return A stage that completes with the result of the API call
*/
private <R> CompletableFuture<R> executeTokenOperation(final ApiCall<R> apiCall) {
return executeAsync(apiCall)
.exceptionally(ExceptionUtils.exceptionallyHandler(HttpResponseException.class, e -> {
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()
|| e.getStatusCode() == Response.Status.GONE.getStatusCode()) {
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
}
final String details = e instanceof GoogleJsonResponseException
? ((GoogleJsonResponseException) e).getDetails().toString()
: "";
logger.warn("Unexpected HTTP status code {} from androidpublisher: {}", e.getStatusCode(), details, e);
throw ExceptionUtils.wrap(e);
}));
}
private CompletableFuture<SubscriptionPurchaseV2> lookupSubscription(final String purchaseToken) {
return executeAsync(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
}
private long productIdToLevel(final String productId) {
@@ -385,8 +385,17 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
if (customer == null) {
throw ExceptionUtils.wrap(new IOException("no customer record found for id " + customerId));
}
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId, customer.getSubscriptions());
throw ExceptionUtils.wrap(new IOException("unexpected customer ID returned by Stripe"));
}
return listNonCanceledSubscriptions(customer);
}).thenCompose(subscriptions -> {
if (subscriptions.stream()
.anyMatch(subscription -> !subscription.getCustomer().equals(customerId))) {
logger.error("Subscription did not match expected customer ID: {}", customerId);
throw ExceptionUtils.wrap( new IOException("mismatched customer ID"));
}
@SuppressWarnings("unchecked")
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
.map(this::endSubscription).toArray(CompletableFuture[]::new);
@@ -401,7 +410,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
.build();
try {
return Lists.newArrayList(
stripeClient.subscriptions().list(params, commonOptions()).autoPagingIterable(null, commonOptions()));
stripeClient.subscriptions().list(params, commonOptions()).autoPagingIterable());
} catch (StripeException e) {
throw new CompletionException(e);
}
@@ -450,7 +459,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
try {
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems().list(
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
return Lists.newArrayList(subscriptionItems.autoPagingIterable(null, commonOptions()));
return Lists.newArrayList(subscriptionItems.autoPagingIterable());
} catch (final StripeException e) {
throw new CompletionException(e);
@@ -519,7 +528,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
.build();
try {
ArrayList<Invoice> invoices = Lists.newArrayList(stripeClient.invoices().list(params, commonOptions())
.autoPagingIterable(null, commonOptions()));
.autoPagingIterable());
invoices.sort(Comparator.comparingLong(Invoice::getCreated).reversed());
return invoices;
} catch (StripeException e) {
@@ -677,7 +686,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
try {
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.invoices().lineItems()
.list(invoice.getId(), commonOptions());
return Lists.newArrayList(lineItems.autoPagingIterable(null, commonOptions()));
return Lists.newArrayList(lineItems.autoPagingIterable());
} catch (final StripeException e) {
throw new CompletionException(e);
}
@@ -0,0 +1,29 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
/**
* An abstract base class for exceptions that do not include a stack trace. Stackless exceptions are generally intended
* for internal error-handling cases where the error will never be logged or otherwise reported.
*/
public abstract class NoStackTraceException extends Exception {
public NoStackTraceException() {
super(null, null, true, false);
}
public NoStackTraceException(final String message) {
super(message, null, true, false);
}
public NoStackTraceException(final String message, final Throwable cause) {
super(message, cause, true, false);
}
public NoStackTraceException(final Throwable cause) {
super(null, cause, true, false);
}
}
@@ -508,8 +508,8 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
code = 4409;
message = "Connected elsewhere";
} else {
code = 1000;
message = "OK";
code = 4401;
message = "Reauthentication required";
}
client.close(code, message);
@@ -22,6 +22,7 @@ import java.util.concurrent.SynchronousQueue;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerService;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
@@ -105,7 +106,7 @@ record CommandDependencies(
final AwsCredentialsProvider awsCredentialsProvider = configuration.getAwsCredentialsConfiguration().build();
ScheduledExecutorService dynamicConfigurationExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "dynamicConfiguration-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "dynamicConfiguration-%d")).threads(1).build();
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
new DynamicConfigurationManager<>(
@@ -124,36 +125,36 @@ record CommandDependencies(
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
environment.lifecycle().executorService("messageDelivery").minThreads(4).maxThreads(4).build());
ExecutorService messageDeletionExecutor = environment.lifecycle()
.executorService(name(name, "messageDeletion-%d")).minThreads(4).maxThreads(4).build();
.executorService(name(WhisperServerService.class, "messageDeletion-%d")).minThreads(4).maxThreads(4).build();
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
.executorService(name(name, "secureValueRecoveryService-%d")).maxThreads(8).minThreads(8).build();
.executorService(name(WhisperServerService.class, "secureValueRecoveryService-%d")).maxThreads(8).minThreads(8).build();
ExecutorService storageServiceExecutor = environment.lifecycle()
.executorService(name(name, "storageService-%d")).maxThreads(8).minThreads(8).build();
.executorService(name(WhisperServerService.class, "storageService-%d")).maxThreads(8).minThreads(8).build();
ExecutorService accountLockExecutor = environment.lifecycle()
.executorService(name(name, "accountLock-%d")).minThreads(8).maxThreads(8).build();
.executorService(name(WhisperServerService.class, "accountLock-%d")).minThreads(8).maxThreads(8).build();
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
.executorService(name(name, "remoteStorage-%d"))
.executorService(name(WhisperServerService.class, "remoteStorage-%d"))
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
.keepAliveTime(io.dropwizard.util.Duration.seconds(60L)).build();
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(name, "apnSender-%d"))
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(WhisperServerService.class, "apnSender-%d"))
.maxThreads(1).minThreads(1).build();
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(name, "fcmSender-%d"))
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(WhisperServerService.class, "fcmSender-%d"))
.maxThreads(16).minThreads(16).build();
ExecutorService clientEventExecutor = environment.lifecycle()
.virtualExecutorService(name(name, "clientEvent-%d"));
.virtualExecutorService(name(WhisperServerService.class, "clientEvent-%d"));
ExecutorService asyncOperationQueueingExecutor = environment.lifecycle()
.executorService(name(name, "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
.executorService(name(WhisperServerService.class, "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
.virtualExecutorService(name(name, "disconnectionRequest-%d"));
.virtualExecutorService(name(WhisperServerService.class, "disconnectionRequest-%d"));
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
ScheduledExecutorService remoteStorageRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "remoteStorageRetry-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "remoteStorageRetry-%d")).threads(1).build();
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "storageServiceRetry-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "storageServiceRetry-%d")).threads(1).build();
ScheduledExecutorService messagePollExecutor = environment.lifecycle()
.scheduledExecutorService(name(name, "messagePollExecutor-%d")).threads(1).build();
.scheduledExecutorService(name(WhisperServerService.class, "messagePollExecutor-%d")).threads(1).build();
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
configuration.getSecureStorageServiceConfiguration());
@@ -161,7 +162,7 @@ record CommandDependencies(
configuration.getSvr2Configuration());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(MetricRegistry.name(CommandDependencies.class, "awsSdkMetrics-%d"));
.virtualExecutorService(MetricRegistry.name(WhisperServerService.class, "awsSdkMetrics-%d"));
DynamoDbAsyncClient dynamoDbAsyncClient = configuration.getDynamoDbClientConfiguration()
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsyncCommand"));
@@ -16,7 +16,9 @@ import org.whispersystems.textsecuregcm.storage.MessagesManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
import reactor.util.retry.Retry;
import java.time.Clock;
import java.time.Duration;
import java.time.LocalTime;
public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCommand {
@@ -79,7 +81,16 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
.doOnNext(ignored -> DEVICE_INSPECTED_COUNTER.increment())
.flatMap(accountAndDevice -> Mono.fromFuture(() ->
idleWakeupEligibilityChecker.isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2()))
.mapNotNull(eligible -> eligible ? accountAndDevice : null),
.mapNotNull(eligible -> eligible ? accountAndDevice : null)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.onErrorResume(throwable -> {
log.warn("Failed to check eligibility for {}:{}",
accountAndDevice.getT1().getIdentifier(IdentityType.ACI),
accountAndDevice.getT2().getId(),
throwable);
return Mono.empty();
}),
maxConcurrency)
.flatMap(accountAndDevice -> {
final Account account = accountAndDevice.getT1();
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;
public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccountsCommand {
@@ -70,6 +71,7 @@ public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccount
return deleteAccountMono
.doOnSuccess(ignored -> deletedAccountCounter.increment())
.retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.onErrorResume(throwable -> {
log.warn("Failed to delete account {}", expiredAccount.getUuid(), throwable);
return Mono.empty();
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.backup.ExpiredBackup;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.util.retry.Retry;
public class RemoveExpiredBackupsCommand extends AbstractCommandWithDependencies {
@@ -119,6 +120,7 @@ public class RemoveExpiredBackupsCommand extends AbstractCommandWithDependencies
}
return mono
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.doOnSuccess(ignored -> {
logger.trace("Successfully expired {} for {}",
expiredBackup.expirationType(),
@@ -5,9 +5,18 @@
package org.whispersystems.textsecuregcm.workers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -16,15 +25,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import reactor.util.retry.Retry;
public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAccountsCommand {
@@ -91,6 +92,7 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc
"expiredHolds", String.valueOf(holdsToRemove > 0))
.increment();
return purgeMono
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.doOnSuccess(ignored -> deletedHoldsCounter.increment(holdsToRemove))
.onErrorResume(throwable -> {
log.warn("Failed to purge {} expired holds on account {}", holdsToRemove, account.getUuid());
@@ -98,8 +98,9 @@ enum DeviceCapability {
DEVICE_CAPABILITY_STORAGE = 1;
DEVICE_CAPABILITY_TRANSFER = 2;
DEVICE_CAPABILITY_DELETE_SYNC = 3;
DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER = 4;
reserved 4;
DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION = 5;
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
}
message ZkCredential {
@@ -1,101 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Stream;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class CallDnsRecordsManagerTest {
@Test
public void testParseDnsRecords() throws IOException {
var input = """
{
"aByRegion": {
"datacenter-1": [
"127.0.0.1"
],
"datacenter-2": [
"127.0.0.2",
"127.0.0.3"
],
"datacenter-3": [
"127.0.0.4",
"127.0.0.5"
],
"datacenter-4": [
"127.0.0.6",
"127.0.0.7"
]
},
"aaaaByRegion": {
"datacenter-1": [
"2600:1111:2222:3333:0:20:0:0",
"2600:1111:2222:3333:0:21:0:0",
"2600:1111:2222:3333:0:22:0:0"
],
"datacenter-2": [
"2600:1111:2222:3333:0:23:0:0",
"2600:1111:2222:3333:0:24:0:0"
],
"datacenter-3": [
"2600:1111:2222:3333:0:25:0:0",
"2600:1111:2222:3333:0:26:0:0"
],
"datacenter-4": [
"2600:1111:2222:3333:0:27:0:0"
]
}
}
""";
var actual = CallDnsRecordsManager.parseRecords(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)));
var expected = new CallDnsRecords(
Map.of(
"datacenter-1", Stream.of("127.0.0.1").map(this::getAddressByName).toList(),
"datacenter-2", Stream.of("127.0.0.2", "127.0.0.3").map(this::getAddressByName).toList(),
"datacenter-3", Stream.of("127.0.0.4", "127.0.0.5").map(this::getAddressByName).toList(),
"datacenter-4", Stream.of("127.0.0.6", "127.0.0.7").map(this::getAddressByName).toList()
),
Map.of(
"datacenter-1", Stream.of(
"2600:1111:2222:3333:0:20:0:0",
"2600:1111:2222:3333:0:21:0:0",
"2600:1111:2222:3333:0:22:0:0"
).map(this::getAddressByName).toList(),
"datacenter-2", Stream.of(
"2600:1111:2222:3333:0:23:0:0",
"2600:1111:2222:3333:0:24:0:0")
.map(this::getAddressByName).toList(),
"datacenter-3", Stream.of(
"2600:1111:2222:3333:0:25:0:0",
"2600:1111:2222:3333:0:26:0:0")
.map(this::getAddressByName).toList(),
"datacenter-4", Stream.of(
"2600:1111:2222:3333:0:27:0:0"
).map(this::getAddressByName).toList()
)
);
assertThat(actual).isEqualTo(expected);
}
InetAddress getAddressByName(String ip) {
try {
return InetAddress.getByName(ip) ;
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
@@ -1,245 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class CallRoutingTableParserTest {
@Test
public void testParserSuccess() throws IOException {
var input =
"""
192.1.12.0/24 datacenter-1 datacenter-2 datacenter-3
193.123.123.0/24 datacenter-1 datacenter-2
1.123.123.0/24 datacenter-1
2001:db8:b0aa::/48 datacenter-1
2001:db8:b0ab::/48 datacenter-3 datacenter-1 datacenter-2
2001:db8:b0ac::/48 datacenter-2 datacenter-1
SA-SR-v4 datacenter-3
SA-UY-v4 datacenter-3 datacenter-1 datacenter-2
NA-US-VA-v6 datacenter-2 datacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParserVariousWhitespaceSuccess() throws IOException {
var input =
"""
192.1.12.0/24\t \tdatacenter-1\t\t datacenter-2 datacenter-3
\t193.123.123.0/24\tdatacenter-1\tdatacenter-2
1.123.123.0/24\t datacenter-1
2001:db8:b0aa::/48\t \tdatacenter-1
2001:db8:b0ab::/48 \tdatacenter-3\tdatacenter-1 datacenter-2
2001:db8:b0ac::/48\tdatacenter-2\tdatacenter-1
SA-SR-v4 datacenter-3
SA-UY-v4\tdatacenter-3\tdatacenter-1\tdatacenter-2
NA-US-VA-v6 datacenter-2 \tdatacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParserMissingSection() throws IOException {
var input =
"""
192.1.12.0/24\t \tdatacenter-1\t\t datacenter-2 datacenter-3
193.123.123.0/24\tdatacenter-1\tdatacenter-2
1.123.123.0/24\t datacenter-1
SA-SR-v4 datacenter-3
SA-UY-v4\tdatacenter-3\tdatacenter-1\tdatacenter-2
NA-US-VA-v6 datacenter-2 \tdatacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParserMixedSections() throws IOException {
var input =
"""
1.123.123.0/24\t datacenter-1
2001:db8:b0aa::/48\t \tdatacenter-1
2001:db8:b0ab::/48 \tdatacenter-3\tdatacenter-1 datacenter-2
2001:db8:b0ac::/48\tdatacenter-2\tdatacenter-1
192.1.12.0/24\t \tdatacenter-1\t\t datacenter-2 datacenter-3
193.123.123.0/24\tdatacenter-1\tdatacenter-2
SA-SR-v4 datacenter-3
SA-UY-v4\tdatacenter-3\tdatacenter-1\tdatacenter-2
NA-US-VA-v6 datacenter-2 \tdatacenter-1
""";
var actual = CallRoutingTableParser.fromTsv(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testJsonParserSuccess() throws IOException {
var input =
"""
{
"ipv4GeoToDataCenters": {
"SA-SR": ["datacenter-3"],
"SA-UY": ["datacenter-3", "datacenter-1", "datacenter-2"]
},
"ipv6GeoToDataCenters": {
"NA-US-VA": ["datacenter-2", "datacenter-1"]
},
"ipv4SubnetsToDatacenters": {
"192.1.12.0": ["datacenter-1", "datacenter-2", "datacenter-3"],
"193.123.123.0": ["datacenter-1", "datacenter-2"],
"1.123.123.0": ["datacenter-1"]
},
"ipv6SubnetsToDatacenters": {
"2001:db8:b0aa::": ["datacenter-1"],
"2001:db8:b0ab::": ["datacenter-3", "datacenter-1", "datacenter-2"],
"2001:db8:b0ac::": ["datacenter-2", "datacenter-1"]
}
}
""";
var actual = CallRoutingTableParser.fromJson(new StringReader(input));
var expected = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testParseVariousEdgeCases() throws IOException {
var input =
"""
{
"ipv4GeoToDataCenters": {},
"ipv6GeoToDataCenters": {},
"ipv4SubnetsToDatacenters": {},
"ipv6SubnetsToDatacenters": {}
}
""";
assertThat(CallRoutingTableParser.fromJson(new StringReader(input))).isEqualTo(CallRoutingTable.empty());
assertThat(CallRoutingTableParser.fromJson(new StringReader("{}"))).isEqualTo(CallRoutingTable.empty());
}
}
@@ -1,139 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
public class CallRoutingTableTest {
static final CallRoutingTable basicTable = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("193.123.123.0/24"), List.of("datacenter-1", "datacenter-2"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-4")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ab::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1"),
new CallRoutingTable.GeoKey("NA", "US", Optional.empty(), CallRoutingTable.Protocol.v6), List.of("datacenter-3", "datacenter-4")
)
);
// has overlapping subnets
static final CallRoutingTable overlappingTable = new CallRoutingTable(
Map.of(
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("192.1.12.0/24"), List.of("datacenter-1", "datacenter-2", "datacenter-3"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.123.0/24"), List.of("datacenter-4"),
(CidrBlock.IpV4CidrBlock) CidrBlock.parseCidrBlock("1.123.0.0/16"), List.of("datacenter-1")
),
Map.of(
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0aa::/48"), List.of("datacenter-1"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0ac::/48"), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
(CidrBlock.IpV6CidrBlock) CidrBlock.parseCidrBlock("2001:db8:b0a0::/44"), List.of("datacenter-2", "datacenter-1")
),
Map.of(
new CallRoutingTable.GeoKey("SA", "SR", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3"),
new CallRoutingTable.GeoKey("SA", "UY", Optional.empty(), CallRoutingTable.Protocol.v4), List.of("datacenter-3", "datacenter-1", "datacenter-2"),
new CallRoutingTable.GeoKey("NA", "US", Optional.of("VA"), CallRoutingTable.Protocol.v6), List.of("datacenter-2", "datacenter-1")
)
);
@Test
void testGetFastestDataCentersBySubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actualV4 = basicTable.getDatacentersBySubnet(v4address);
assertThat(actualV4).isEqualTo(List.of("datacenter-4"));
var v6address = Inet6Address.getByName("2001:db8:b0ac:aaaa:aaaa:aaaa:aaaa:0001");
var actualV6 = basicTable.getDatacentersBySubnet(v6address);
assertThat(actualV6).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDataCentersBySubnetOverlappingTable() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actualV4 = overlappingTable.getDatacentersBySubnet(v4address);
assertThat(actualV4).isEqualTo(List.of("datacenter-4"));
var v6address = Inet6Address.getByName("2001:db8:b0ac:aaaa:aaaa:aaaa:aaaa:0001");
var actualV6 = overlappingTable.getDatacentersBySubnet(v6address);
assertThat(actualV6).isEqualTo(List.of("datacenter-3", "datacenter-1", "datacenter-2"));
}
@Test
void testGetFastestDataCentersByGeo() {
var actual = basicTable.getDatacentersByGeo("SA", "SR", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-3"));
var actualWithSubdvision = basicTable.getDatacentersByGeo("NA", "US", Optional.of("VA"));
assertThat(actualWithSubdvision).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDataCentersByGeoFallback() {
var actualExactMatch = basicTable.getDatacentersByGeo("NA", "US", Optional.of("VA"));
assertThat(actualExactMatch).isEqualTo(List.of("datacenter-2", "datacenter-1"));
var actualApproximateMatch = basicTable.getDatacentersByGeo("NA", "US", Optional.of("MD"));
assertThat(actualApproximateMatch).isEqualTo(List.of("datacenter-3", "datacenter-4"));
}
@Test
void testGetFastestDatacentersPrioritizesSubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actual = basicTable.getDatacentersFor(v4address, "NA", "US", Optional.of("VA"));
assertThat(actual).isEqualTo(List.of("datacenter-4", "datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDatacentersEmptySubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("200.200.123.1");
var actual = basicTable.getDatacentersFor(v4address, "NA", "US", Optional.of("VA"));
assertThat(actual).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
@Test
void testGetFastestDatacentersEmptySubnetTakesExtraFromGeo() throws UnknownHostException {
var v4address = Inet4Address.getByName("200.200.123.1");
var actual = basicTable.getDatacentersFor(v4address, "SA", "UY", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-3", "datacenter-1", "datacenter-2"));
}
@Test
void testGetFastestDatacentersEmptyGeoResults() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actual = basicTable.getDatacentersFor(v4address, "ZZ", "AA", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-4"));
}
@Test
void testGetFastestDatacentersEmptyGeoTakesFromSubnet() throws UnknownHostException {
var v4address = Inet4Address.getByName("192.1.12.1");
var actual = basicTable.getDatacentersFor(v4address, "ZZ", "AA", Optional.empty());
assertThat(actual).isEqualTo(List.of("datacenter-1", "datacenter-2", "datacenter-3"));
}
@Test
void testGetFastestDatacentersDistinct() throws UnknownHostException {
var v6address = Inet6Address.getByName("2001:db8:b0ac:aaaa:aaaa:aaaa:aaaa:0001");
var actual = basicTable.getDatacentersFor(v6address, "NA", "US", Optional.of("VA"));
assertThat(actual).isEqualTo(List.of("datacenter-2", "datacenter-1"));
}
}
@@ -1,63 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HexFormat;
import static org.assertj.core.api.Assertions.assertThat;
public class CidrBlockTest {
private HexFormat hex = HexFormat.ofDelimiter(":").withLowerCase();
@Test
public void testIPv4CidrBlockParseSuccess() {
var actual = CidrBlock.parseCidrBlock("255.32.15.0/24");
var expected = new CidrBlock.IpV4CidrBlock(0xFF_20_0F_00, 0xFFFFFF00, 24);
assertThat(actual).isInstanceOf(CidrBlock.IpV4CidrBlock.class);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testIPv6CidrBlockParseSuccess() {
var actual = CidrBlock.parseCidrBlock("2001:db8:b0aa::/48");
var expected = new CidrBlock.IpV6CidrBlock(
new BigInteger(hex.parseHex("20:01:0d:b8:b0:aa:00:00:00:00:00:00:00:00:00:00")),
new BigInteger(hex.parseHex("FF:FF:FF:FF:FF:FF:00:00:00:00:00:00:00:00:00:00")),
48
);
assertThat(actual).isInstanceOf(CidrBlock.IpV6CidrBlock.class);
assertThat(actual).isEqualTo(expected);
}
@Test
public void testIPv4InBlock() throws UnknownHostException {
var block = CidrBlock.parseCidrBlock("255.32.15.0/24");
assertThat(block.ipInBlock(InetAddress.getByName("255.32.15.123"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("255.32.15.0"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("255.32.16.0"))).isFalse();
assertThat(block.ipInBlock(InetAddress.getByName("255.33.15.0"))).isFalse();
assertThat(block.ipInBlock(InetAddress.getByName("254.33.15.0"))).isFalse();
}
@Test
public void testIPv6InBlock() throws UnknownHostException {
var block = CidrBlock.parseCidrBlock("2001:db8:b0aa::/48");
assertThat(block.ipInBlock(InetAddress.getByName("2001:db8:b0aa:1:1::"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("2001:db8:b0aa:0:0::"))).isTrue();
assertThat(block.ipInBlock(InetAddress.getByName("2001:db8:b0ab:1:1::"))).isFalse();
assertThat(block.ipInBlock(InetAddress.getByName("2001:da8:b0aa:1:1::"))).isFalse();
}
}
@@ -1,137 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DynamicConfigTurnRouterTest {
@Test
public void testAlwaysSelectFirst() throws JsonProcessingException {
final String configString = """
captcha:
scoreFloor: 1.0
turn:
uriConfigs:
- uris:
- always1.org
- always2.org
- uris:
- never.org
weight: 0
""";
DynamicConfiguration config = DynamicConfigurationManager
.parseConfiguration(configString, DynamicConfiguration.class)
.orElseThrow();
@SuppressWarnings("unchecked")
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
DynamicConfigurationManager.class);
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(mockDynamicConfigManager);
final long COUNT = 1000;
final Map<String, Long> urlCounts = Stream
.generate(configTurnRouter::randomUrls)
.limit(COUNT)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
assertThat(urlCounts.get("always1.org")).isEqualTo(COUNT);
assertThat(urlCounts.get("always2.org")).isEqualTo(COUNT);
assertThat(urlCounts).doesNotContainKey("never.org");
}
@Test
public void testProbabilisticUrls() throws JsonProcessingException {
final String configString = """
captcha:
scoreFloor: 1.0
turn:
uriConfigs:
- uris:
- always.org
- sometimes1.org
weight: 5
- uris:
- always.org
- sometimes2.org
weight: 5
""";
DynamicConfiguration config = DynamicConfigurationManager
.parseConfiguration(configString, DynamicConfiguration.class)
.orElseThrow();
@SuppressWarnings("unchecked")
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
DynamicConfigurationManager.class);
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(mockDynamicConfigManager);
final long COUNT = 1000;
final Map<String, Long> urlCounts = Stream
.generate(configTurnRouter::randomUrls)
.limit(COUNT)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
assertThat(urlCounts.get("always.org")).isEqualTo(COUNT);
assertThat(urlCounts.get("sometimes1.org")).isGreaterThan(0);
assertThat(urlCounts.get("sometimes2.org")).isGreaterThan(0);
}
@Test
public void testExplicitEnrollment() throws JsonProcessingException {
final String configString = """
captcha:
scoreFloor: 1.0
turn:
secret: bloop
uriConfigs:
- uris:
- enrolled.org
weight: 0
enrolledAcis:
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
- uris:
- unenrolled.org
weight: 1
""";
DynamicConfiguration config = DynamicConfigurationManager
.parseConfiguration(configString, DynamicConfiguration.class)
.orElseThrow();
@SuppressWarnings("unchecked")
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
DynamicConfigurationManager.class);
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(mockDynamicConfigManager);
List<String> urls = configTurnRouter.targetedUrls(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
assertThat(urls.getFirst()).isEqualTo("enrolled.org");
urls = configTurnRouter.targetedUrls(UUID.randomUUID());
assertTrue(urls.isEmpty());
}
}
@@ -1,335 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.calls.routing;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.Continent;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Subdivision;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TurnCallRouterTest {
private final static String TEST_HOSTNAME = "subdomain.example.org";
private final static List<String> TEST_URLS_WITH_HOSTS = List.of(
"stun:one.example.com",
"turn:two.example.com",
"turn:three.example.com?transport=tcp"
);
private final static List<String> EXPECTED_TEST_URLS_WITH_HOSTS = List.of(
"turn:two.example.com"
);
private CallRoutingTable performanceTable;
private CallRoutingTable manualTable;
private DynamicConfigTurnRouter configTurnRouter;
private DatabaseReader geoIp;
private Country country;
private Continent continent;
private CallDnsRecords callDnsRecords;
private Subdivision subdivision;
private UUID aci = UUID.randomUUID();
@BeforeEach
void setup() throws IOException, GeoIp2Exception {
performanceTable = mock(CallRoutingTable.class);
manualTable = mock(CallRoutingTable.class);
configTurnRouter = mock(DynamicConfigTurnRouter.class);
geoIp = mock(DatabaseReader.class);
continent = mock(Continent.class);
country = mock(Country.class);
subdivision = mock(Subdivision.class);
ArrayList<Subdivision> subdivisions = new ArrayList<>();
subdivisions.add(subdivision);
when(geoIp.city(any())).thenReturn(new CityResponse(null, continent, country, null, null, null, null, null, subdivisions, null));
setupDefault();
}
void setupDefault() {
when(configTurnRouter.targetedUrls(any())).thenReturn(Collections.emptyList());
when(configTurnRouter.randomUrls()).thenReturn(TEST_URLS_WITH_HOSTS);
when(configTurnRouter.getHostname()).thenReturn(TEST_HOSTNAME);
when(configTurnRouter.shouldRandomize()).thenReturn(false);
when(manualTable.getDatacentersFor(any(), any(), any(), any())).thenReturn(Collections.emptyList());
when(continent.getCode()).thenReturn("NA");
when(country.getIsoCode()).thenReturn("US");
when(subdivision.getIsoCode()).thenReturn("VA");
try {
callDnsRecords = new CallDnsRecords(
Map.of(
"dc-manual", List.of(InetAddress.getByName("1.1.1.1")),
"dc-performance1", List.of(
InetAddress.getByName("9.9.9.1"),
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-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::")),
"dc-performance1", List.of(
InetAddress.getByName("2222:1111:0:abc0::"),
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-performance4", List.of(
InetAddress.getByName("2222:1111:0:abc4::"),
InetAddress.getByName("2222:1111:0:abc5::"),
InetAddress.getByName("2222:1111:0:abc6::")
)
)
);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
private TurnCallRouter router() {
return new TurnCallRouter(
() -> callDnsRecords,
() -> performanceTable,
() -> manualTable,
configTurnRouter,
() -> geoIp,
// set to true so the return values are predictable
true
);
}
TurnServerOptions optionsWithUrls(List<String> urls) {
return new TurnServerOptions(
TEST_HOSTNAME,
Optional.of(urls),
Optional.of(EXPECTED_TEST_URLS_WITH_HOSTS)
);
}
@Test
public void testPrioritizesTargetedUrls() throws UnknownHostException {
List<String> targetedUrls = List.of(
"targeted1.example.com",
"targeted.example.com"
);
when(configTurnRouter.targetedUrls(any()))
.thenReturn(targetedUrls);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
Optional.empty(),
Optional.of(targetedUrls)
));
}
@Test
public void testRandomizes() throws UnknownHostException {
when(configTurnRouter.shouldRandomize())
.thenReturn(true);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
Optional.empty(),
Optional.of(TEST_URLS_WITH_HOSTS)
));
}
@Test
public void testUrlsOnlyNoInstanceIps() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance2", "dc-performance1"));
when(configTurnRouter.shouldRandomize())
.thenReturn(false);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 0))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
Optional.empty(),
Optional.of(TEST_URLS_WITH_HOSTS)
));
}
@Test
public void testOrderedByPerformance() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance2", "dc-performance1"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of(
"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.1",
"turn:9.9.9.1:80?transport=tcp",
"turns:9.9.9.1:443?transport=tcp",
"turn:9.9.9.2",
"turn:9.9.9.2:80?transport=tcp",
"turns:9.9.9.2: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",
"turn:[2222:1111:0:abc0:0:0:0:0]",
"turn:[2222:1111:0:abc0:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc0:0:0:0:0]:443?transport=tcp",
"turn:[2222:1111:0:abc1:0:0:0:0]",
"turn:[2222:1111:0:abc1:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:abc1:0:0:0:0]:443?transport=tcp"
)));
}
@Test
public void testPrioritizesManualRecords() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance1"));
when(manualTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-manual"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of(
"turn:1.1.1.1",
"turn:1.1.1.1:80?transport=tcp",
"turns:1.1.1.1:443?transport=tcp",
"turn:[2222:1111:0:dead:0:0:0:0]",
"turn:[2222:1111:0:dead:0:0:0:0]:80?transport=tcp",
"turns:[2222:1111:0:dead:0:0:0:0]:443?transport=tcp"
)));
}
@Test
public void testLimitPrioritizesBestDataCenters() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("dc-performance3", "dc-performance2", "dc-performance3"));
// 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",
"turns:9.9.9.4: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:[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",
"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")), 1))
.isEqualTo(optionsWithUrls(List.of(
"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: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"
)));
}
@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",
"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"
)));
}
@Test
public void testNoDatacentersMatched() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of());
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of()));
}
@Test
public void testHandlesDatacenterNotInDnsRecords() throws UnknownHostException {
when(performanceTable.getDatacentersFor(any(), any(), any(), any()))
.thenReturn(List.of("unsynced-datacenter"));
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(optionsWithUrls(List.of()));
}
}
@@ -335,67 +335,6 @@ class DynamicConfigurationTest {
assertThat(resetRateLimiterConfig.permitRegenerationDuration()).isEqualTo(Duration.ofNanos(4_000));
}
@Test
void testParseTurnConfig() throws JsonProcessingException {
{
final String config = REQUIRED_CONFIG.concat("""
turn:
secret: bloop
uriConfigs:
- uris:
- turn:test.org
weight: -1
""");
assertThat(DynamicConfigurationManager.parseConfiguration(config, DynamicConfiguration.class)).isEmpty();
}
{
final String config = REQUIRED_CONFIG.concat("""
turn:
uriConfigs:
- uris:
- turn:test0.org
- turn:test1.org
- uris:
- turn:test2.org
weight: 2
enrolledAcis:
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
randomizeRate: 100_000
hostname: test.domain.org
""");
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
.parseConfiguration(config, DynamicConfiguration.class)
.orElseThrow()
.getTurnConfiguration();
assertThat(turnConfiguration.getUriConfigs().get(0).getUris()).hasSize(2);
assertThat(turnConfiguration.getUriConfigs().get(1).getUris()).hasSize(1);
assertThat(turnConfiguration.getUriConfigs().get(0).getWeight()).isEqualTo(1);
assertThat(turnConfiguration.getUriConfigs().get(1).getWeight()).isEqualTo(2);
assertThat(turnConfiguration.getUriConfigs().get(1).getEnrolledAcis())
.containsExactly(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
assertThat(turnConfiguration.getHostname()).isEqualTo("test.domain.org");
assertThat(turnConfiguration.getRandomizeRate()).isEqualTo(100_000L);
assertThat(turnConfiguration.getDefaultInstanceIpCount()).isEqualTo(0);
}
{
final String config = REQUIRED_CONFIG.concat("""
turn:
uriConfigs:
- uris:
- turn:test0.org
- turn:test1.org
defaultInstanceIpCount: 5
""");
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
.parseConfiguration(config, DynamicConfiguration.class)
.orElseThrow()
.getTurnConfiguration();
assertThat(turnConfiguration.getDefaultInstanceIpCount()).isEqualTo(5);
}
}
@Test
void testMessagePersister() throws JsonProcessingException {
{
@@ -59,7 +59,6 @@ import org.signal.libsignal.usernames.BaseUsernameException;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
@@ -130,7 +129,6 @@ class AccountControllerTest {
private static final RateLimiter usernameReserveLimiter = mock(RateLimiter.class);
private static final RateLimiter usernameLookupLimiter = mock(RateLimiter.class);
private static final RateLimiter checkAccountExistence = mock(RateLimiter.class);
private static final TurnTokenGenerator turnTokenGenerator = mock(TurnTokenGenerator.class);
private static final Account senderPinAccount = mock(Account.class);
private static final Account senderRegLockAccount = mock(Account.class);
private static final Account senderHasStorage = mock(Account.class);
@@ -234,7 +232,6 @@ class AccountControllerTest {
usernameSetLimiter,
usernameReserveLimiter,
usernameLookupLimiter,
turnTokenGenerator,
senderPinAccount,
senderRegLockAccount,
senderHasStorage,
@@ -16,6 +16,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -79,6 +80,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -139,7 +141,7 @@ class AccountControllerV2Test {
void setUp() throws Exception {
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any())).thenAnswer(
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
(Answer<Account>) invocation -> {
final Account account = invocation.getArgument(0);
final String number = invocation.getArgument(1);
@@ -189,7 +191,7 @@ class AccountControllerV2Test {
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
any(), any());
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
@@ -212,7 +214,7 @@ class AccountControllerV2Test {
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(AuthHelper.VALID_NUMBER), any(), any(), any(),
any(), any());
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(AuthHelper.VALID_NUMBER, accountIdentityResponse.number());
@@ -220,7 +222,7 @@ class AccountControllerV2Test {
}
@Test
void changeNumberNonNormalizedNumber() throws Exception {
void changeNumberNonNormalizedNumber() {
try (Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
@@ -293,13 +295,15 @@ class AccountControllerV2Test {
null, NEW_NUMBER, "123", new IdentityKey(Curve.generateKeyPair().getPublicKey()),
Collections.emptyList(), Collections.emptyMap(), null, Map.of((byte) 1, pniRegistrationId));
final Response response = resources.getJerseyTest()
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(changeNumberRequest, MediaType.APPLICATION_JSON_TYPE));
assertEquals(expectedStatusCode, response.getStatus());
.put(Entity.entity(changeNumberRequest, MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(expectedStatusCode, response.getStatus());
}
}
private static Stream<Arguments> invalidRegistrationId() {
@@ -422,7 +426,7 @@ class AccountControllerV2Test {
final AccountIdentityResponse accountIdentityResponse = response.readEntity(AccountIdentityResponse.class);
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
any(), any());
any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
@@ -481,6 +485,33 @@ class AccountControllerV2Test {
}
}
@Test
void deviceMessageTooLarge() throws Exception {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
SESSION_EXPIRATION_SECONDS))));
reset(changeNumberManager);
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(MessageTooLargeException.class);
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(
new ChangeNumberRequest(encodeSessionId("session"), null, NEW_NUMBER, "123", new IdentityKey(Curve.generateKeyPair().getPublicKey()),
Collections.emptyList(),
Collections.emptyMap(), null, Collections.emptyMap()),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(413, response.getStatus());
}
}
/**
* Valid request JSON with the given Recovery Password
*/
@@ -558,7 +589,7 @@ class AccountControllerV2Test {
@BeforeEach
void setUp() throws Exception {
when(changeNumberManager.updatePniKeys(any(), any(), any(), any(), any(), any())).thenAnswer(
when(changeNumberManager.updatePniKeys(any(), any(), any(), any(), any(), any(), any())).thenAnswer(
(Answer<Account>) invocation -> {
final Account account = invocation.getArgument(0);
final IdentityKey pniIdentityKey = invocation.getArgument(1);
@@ -594,7 +625,7 @@ class AccountControllerV2Test {
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(requestJson()), AccountIdentityResponse.class);
verify(changeNumberManager).updatePniKeys(eq(AuthHelper.VALID_ACCOUNT), eq(IDENTITY_KEY), any(), any(), any(), any());
verify(changeNumberManager).updatePniKeys(eq(AuthHelper.VALID_ACCOUNT), eq(IDENTITY_KEY), any(), any(), any(), any(), any());
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(AuthHelper.VALID_NUMBER, accountIdentityResponse.number());
@@ -646,6 +677,23 @@ class AccountControllerV2Test {
}
}
@Test
void deviceMessageTooLarge() throws Exception {
reset(changeNumberManager);
when(changeNumberManager.updatePniKeys(any(), any(), any(), any(), any(), any(), any()))
.thenThrow(MessageTooLargeException.class);
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/phone_number_identity_key_distribution")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(requestJson()))) {
assertEquals(413, response.getStatus());
}
}
/**
* Valid request JSON for a {@link org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest}
*/
@@ -29,7 +29,6 @@ import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.asJson;
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.jsonFixture;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.protobuf.ByteString;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
@@ -73,8 +72,6 @@ import org.mockito.ArgumentCaptor;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicInboundMessageByteLimitConfiguration;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -105,7 +102,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RemovedMessage;
@@ -177,10 +173,6 @@ class MessageControllerTest {
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
private static final Scheduler messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
@SuppressWarnings("unchecked")
private static final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
private static final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
private static final TestClock clock = TestClock.now();
@@ -198,7 +190,7 @@ class MessageControllerTest {
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager,
messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, messageDeliveryScheduler, mock(ClientReleaseManager.class),
dynamicConfigurationManager, serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
clock))
.build();
@@ -239,16 +231,6 @@ class MessageControllerTest {
when(accountsManager.getByServiceIdentifierAsync(MULTI_DEVICE_PNI_ID)).thenReturn(CompletableFuture.completedFuture(Optional.of(multiDeviceAccount)));
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(INTERNATIONAL_UUID))).thenReturn(CompletableFuture.completedFuture(Optional.of(internationalAccount)));
final DynamicInboundMessageByteLimitConfiguration inboundMessageByteLimitConfiguration =
mock(DynamicInboundMessageByteLimitConfiguration.class);
when(inboundMessageByteLimitConfiguration.enforceInboundLimit()).thenReturn(false);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getInboundMessageByteLimitConfiguration()).thenReturn(inboundMessageByteLimitConfiguration);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(rateLimiters.getMessagesLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getStoriesLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getInboundMessageBytes()).thenReturn(rateLimiter);
@@ -507,7 +489,7 @@ class MessageControllerTest {
// `long`) instead of the validation layer, we get a 400 instead of a 422
"99999999999999999999999999999999999, 400"
})
void testSingleDeviceExtremeTimestamp(final String timestamp, final int expectedStatus) throws JsonProcessingException {
void testSingleDeviceExtremeTimestamp(final String timestamp, final int expectedStatus) {
final String jsonTemplate = """
{
"timestamp" : %s,
@@ -624,9 +606,7 @@ class MessageControllerTest {
assertEquals(3, envelopeCaptor.getValue().size());
envelopeCaptor.getValue().values().forEach(envelope -> {
assertTrue(envelope.getUrgent());
});
envelopeCaptor.getValue().values().forEach(envelope -> assertTrue(envelope.getUrgent()));
}
}
@@ -650,9 +630,7 @@ class MessageControllerTest {
assertEquals(3, envelopeCaptor.getValue().size());
envelopeCaptor.getValue().values().forEach(envelope -> {
assertFalse(envelope.getUrgent());
});
envelopeCaptor.getValue().values().forEach(envelope -> assertFalse(envelope.getUrgent()));
}
}
@@ -965,7 +943,7 @@ class MessageControllerTest {
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
final String userAgent = "user-agent";
UUID messageGuid = UUID.randomUUID();
final UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
@@ -976,8 +954,6 @@ class MessageControllerTest {
when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni));
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
messageGuid = UUID.randomUUID();
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
@@ -1103,7 +1079,7 @@ class MessageControllerTest {
@Test
void testValidateContentLength() {
final int contentLength = Math.toIntExact(MessageController.MAX_MESSAGE_SIZE + 1);
final int contentLength = Math.toIntExact(MessageSender.MAX_MESSAGE_SIZE + 1);
final byte[] contentBytes = new byte[contentLength];
Arrays.fill(contentBytes, (byte) 1);
@@ -1113,7 +1089,7 @@ class MessageControllerTest {
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
.put(Entity.entity(new IncomingMessageList(
List.of(new IncomingMessage(1, (byte) 1, 1, Base64.getEncoder().encodeToString(contentBytes))), false, true,
List.of(new IncomingMessage(1, (byte) 1, 1, contentBytes)), false, true,
System.currentTimeMillis()),
MediaType.APPLICATION_JSON_TYPE))) {
@@ -1659,14 +1635,4 @@ class MessageControllerTest {
return builder.build();
}
@Test
void decodedSize() {
for (int size = MessageController.MAX_MESSAGE_SIZE - 3; size <= MessageController.MAX_MESSAGE_SIZE + 3; size++) {
final byte[] bytes = TestRandomUtil.nextBytes(size);
final String base64Encoded = Base64.getEncoder().encodeToString(bytes);
assertEquals(bytes.length, MessageController.decodedSize(base64Encoded));
}
}
}
@@ -443,9 +443,9 @@ class ProfileControllerTest {
@CartesianTest
void testProfileCapabilities(
@CartesianTest.Values(booleans = {true, false}) final boolean isDeleteSyncSupported,
@CartesianTest.Values(booleans = {true, false}) final boolean isVersionedExpirationTimerSupported) {
@CartesianTest.Values(booleans = {true, false}) final boolean isAttachmentBackfillSupported) {
when(capabilitiesAccount.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(isDeleteSyncSupported);
when(capabilitiesAccount.hasCapability(DeviceCapability.VERSIONED_EXPIRATION_TIMER)).thenReturn(isVersionedExpirationTimerSupported);
when(capabilitiesAccount.hasCapability(DeviceCapability.ATTACHMENT_BACKFILL)).thenReturn(isAttachmentBackfillSupported);
final BaseProfileResponse profile = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID)
.request()
@@ -453,7 +453,7 @@ class ProfileControllerTest {
.get(BaseProfileResponse.class);
assertEquals(isDeleteSyncSupported, profile.getCapabilities().get("deleteSync"));
assertEquals(isVersionedExpirationTimerSupported, profile.getCapabilities().get("versionedExpirationTimer"));
assertEquals(isAttachmentBackfillSupported, profile.getCapabilities().get("attachmentBackfill"));
}
@Test
@@ -69,7 +69,7 @@ class OutgoingMessageEntityTest {
final Account account = new Account();
account.setUuid(UUID.randomUUID());
IncomingMessage message = new IncomingMessage(1, (byte) 44, 55, "AAAAAA");
IncomingMessage message = new IncomingMessage(1, (byte) 44, 55, TestRandomUtil.nextBytes(4));
MessageProtos.Envelope baseEnvelope = message.toEnvelope(
new AciServiceIdentifier(UUID.randomUUID()),
@@ -435,7 +435,7 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@CartesianTest.Values(booleans = {true, false}) final boolean storage,
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
@CartesianTest.Values(booleans = {true, false}) final boolean deleteSync,
@CartesianTest.Values(booleans = {true, false}) final boolean versionedExpirationTimer) {
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill) {
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
@@ -456,8 +456,8 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC);
}
if (versionedExpirationTimer) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER);
if (attachmentBackfill) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL);
}
final SetCapabilitiesResponse ignored = authenticatedServiceStub().setCapabilities(requestBuilder.build());
@@ -476,8 +476,8 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
expectedCapabilities.add(DeviceCapability.DELETE_SYNC);
}
if (versionedExpirationTimer) {
expectedCapabilities.add(DeviceCapability.VERSIONED_EXPIRATION_TIMER);
if (attachmentBackfill) {
expectedCapabilities.add(DeviceCapability.ATTACHMENT_BACKFILL);
}
verify(device).setCapabilities(expectedCapabilities);
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.push;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyByte;
@@ -24,6 +25,7 @@ import java.util.Map;
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;
@@ -172,4 +174,13 @@ class MessageSenderTest {
return arguments;
}
@Test
void validateContentLength() {
assertThrows(MessageTooLargeException.class, () ->
MessageSender.validateContentLength(MessageSender.MAX_MESSAGE_SIZE + 1, false, false, false, null));
assertDoesNotThrow(() ->
MessageSender.validateContentLength(MessageSender.MAX_MESSAGE_SIZE, false, false, false, null));
}
}
@@ -41,8 +41,6 @@ class AccountTest {
private final Device oldSecondaryDevice = mock(Device.class);
private final Device deleteSyncCapableDevice = mock(Device.class);
private final Device deleteSyncIncapableDevice = mock(Device.class);
private final Device versionedExpirationTimerCapableDevice = mock(Device.class);
private final Device versionedExpirationTimerIncapableDevice = mock(Device.class);
@BeforeEach
void setup() {
@@ -67,12 +65,6 @@ class AccountTest {
when(deleteSyncIncapableDevice.getId()).thenReturn((byte) 2);
when(deleteSyncIncapableDevice.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(false);
when(versionedExpirationTimerCapableDevice.getId()).thenReturn((byte) 1);
when(versionedExpirationTimerCapableDevice.hasCapability(DeviceCapability.VERSIONED_EXPIRATION_TIMER)).thenReturn(true);
when(versionedExpirationTimerIncapableDevice.getId()).thenReturn((byte) 2);
when(versionedExpirationTimerIncapableDevice.hasCapability(DeviceCapability.VERSIONED_EXPIRATION_TIMER)).thenReturn(false);
}
@Test
@@ -139,17 +131,6 @@ class AccountTest {
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.DELETE_SYNC));
}
@Test
void isVersionedExpirationTimerSupported() {
assertTrue(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
List.of(versionedExpirationTimerCapableDevice),
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.VERSIONED_EXPIRATION_TIMER));
assertFalse(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
List.of(versionedExpirationTimerIncapableDevice, versionedExpirationTimerCapableDevice),
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.VERSIONED_EXPIRATION_TIMER));
}
@Test
void stale() {
final Account account = AccountsHelper.generateTestAccount("+14151234567", UUID.randomUUID(), UUID.randomUUID(), Collections.emptyList(),
new byte[0]);
@@ -15,8 +15,8 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -102,7 +102,7 @@ public class ChangeNumberManagerTest {
void changeNumberNoMessages() throws Exception {
Account account = mock(Account.class);
when(account.getNumber()).thenReturn("+18005551234");
changeNumberManager.changeNumber(account, "+18025551234", null, null, null, null, null);
changeNumberManager.changeNumber(account, "+18025551234", null, null, null, null, null, null);
verify(accountsManager).changeNumber(account, "+18025551234", null, null, null, null);
verify(accountsManager, never()).updateDevice(any(), anyByte(), any());
verify(messageSender, never()).sendMessages(eq(account), any());
@@ -117,7 +117,7 @@ public class ChangeNumberManagerTest {
final Map<Byte, ECSignedPreKey> prekeys = Map.of(Device.PRIMARY_ID,
KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
changeNumberManager.changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyList(), Collections.emptyMap());
changeNumberManager.changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyList(), Collections.emptyMap(), null);
verify(accountsManager).changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyMap());
verify(messageSender, never()).sendMessages(eq(account), any());
}
@@ -150,9 +150,9 @@ public class ChangeNumberManagerTest {
final IncomingMessage msg = mock(IncomingMessage.class);
when(msg.destinationDeviceId()).thenReturn(deviceId2);
when(msg.content()).thenReturn(Base64.getEncoder().encodeToString(new byte[]{1}));
when(msg.content()).thenReturn(new byte[]{1});
changeNumberManager.changeNumber(account, changedE164, pniIdentityKey, prekeys, null, List.of(msg), registrationIds);
changeNumberManager.changeNumber(account, changedE164, pniIdentityKey, prekeys, null, List.of(msg), registrationIds, null);
verify(accountsManager).changeNumber(account, changedE164, pniIdentityKey, prekeys, null, registrationIds);
@@ -203,9 +203,9 @@ public class ChangeNumberManagerTest {
final IncomingMessage msg = mock(IncomingMessage.class);
when(msg.destinationDeviceId()).thenReturn(deviceId2);
when(msg.content()).thenReturn(Base64.getEncoder().encodeToString(new byte[]{1}));
when(msg.content()).thenReturn(new byte[]{1});
changeNumberManager.changeNumber(account, changedE164, pniIdentityKey, prekeys, pqPrekeys, List.of(msg), registrationIds);
changeNumberManager.changeNumber(account, changedE164, pniIdentityKey, prekeys, pqPrekeys, List.of(msg), registrationIds, null);
verify(accountsManager).changeNumber(account, changedE164, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
@@ -254,9 +254,9 @@ public class ChangeNumberManagerTest {
final IncomingMessage msg = mock(IncomingMessage.class);
when(msg.destinationDeviceId()).thenReturn(deviceId2);
when(msg.content()).thenReturn(Base64.getEncoder().encodeToString(new byte[]{1}));
when(msg.content()).thenReturn(new byte[]{1});
changeNumberManager.changeNumber(account, originalE164, pniIdentityKey, prekeys, pqPrekeys, List.of(msg), registrationIds);
changeNumberManager.changeNumber(account, originalE164, pniIdentityKey, prekeys, pqPrekeys, List.of(msg), registrationIds, null);
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
@@ -301,9 +301,9 @@ public class ChangeNumberManagerTest {
final IncomingMessage msg = mock(IncomingMessage.class);
when(msg.destinationDeviceId()).thenReturn(deviceId2);
when(msg.content()).thenReturn(Base64.getEncoder().encodeToString(new byte[]{1}));
when(msg.content()).thenReturn(new byte[]{1});
changeNumberManager.updatePniKeys(account, pniIdentityKey, prekeys, null, List.of(msg), registrationIds);
changeNumberManager.updatePniKeys(account, pniIdentityKey, prekeys, null, List.of(msg), registrationIds, null);
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, null, registrationIds);
@@ -350,9 +350,9 @@ public class ChangeNumberManagerTest {
final IncomingMessage msg = mock(IncomingMessage.class);
when(msg.destinationDeviceId()).thenReturn(deviceId2);
when(msg.content()).thenReturn(Base64.getEncoder().encodeToString(new byte[]{1}));
when(msg.content()).thenReturn(new byte[]{1});
changeNumberManager.updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, List.of(msg), registrationIds);
changeNumberManager.updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, List.of(msg), registrationIds, null);
verify(accountsManager).updatePniKeys(account, pniIdentityKey, prekeys, pqPrekeys, registrationIds);
@@ -393,8 +393,8 @@ public class ChangeNumberManagerTest {
final byte destinationDeviceId2 = 2;
final byte destinationDeviceId3 = 3;
final List<IncomingMessage> messages = List.of(
new IncomingMessage(1, destinationDeviceId2, 1, "foo"),
new IncomingMessage(1, destinationDeviceId3, 1, "foo"));
new IncomingMessage(1, destinationDeviceId2, 1, "foo".getBytes(StandardCharsets.UTF_8)),
new IncomingMessage(1, destinationDeviceId3, 1, "foo".getBytes(StandardCharsets.UTF_8)));
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECPublicKey pniIdentityKey = pniIdentityKeyPair.getPublicKey();
@@ -407,7 +407,7 @@ public class ChangeNumberManagerTest {
destinationDeviceId3, 89);
assertThrows(StaleDevicesException.class,
() -> changeNumberManager.changeNumber(account, "+18005559876", new IdentityKey(Curve.generateKeyPair().getPublicKey()), preKeys, null, messages, registrationIds));
() -> changeNumberManager.changeNumber(account, "+18005559876", new IdentityKey(Curve.generateKeyPair().getPublicKey()), preKeys, null, messages, registrationIds, null));
}
@Test
@@ -431,8 +431,8 @@ public class ChangeNumberManagerTest {
final byte destinationDeviceId2 = 2;
final byte destinationDeviceId3 = 3;
final List<IncomingMessage> messages = List.of(
new IncomingMessage(1, destinationDeviceId2, 1, "foo"),
new IncomingMessage(1, destinationDeviceId3, 1, "foo"));
new IncomingMessage(1, destinationDeviceId2, 1, "foo".getBytes(StandardCharsets.UTF_8)),
new IncomingMessage(1, destinationDeviceId3, 1, "foo".getBytes(StandardCharsets.UTF_8)));
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECPublicKey pniIdentityKey = pniIdentityKeyPair.getPublicKey();
@@ -445,7 +445,7 @@ public class ChangeNumberManagerTest {
destinationDeviceId3, 89);
assertThrows(StaleDevicesException.class,
() -> changeNumberManager.updatePniKeys(account, new IdentityKey(Curve.generateKeyPair().getPublicKey()), preKeys, null, messages, registrationIds));
() -> changeNumberManager.updatePniKeys(account, new IdentityKey(Curve.generateKeyPair().getPublicKey()), preKeys, null, messages, registrationIds, null));
}
@Test
@@ -469,12 +469,12 @@ public class ChangeNumberManagerTest {
final byte destinationDeviceId2 = 2;
final byte destinationDeviceId3 = 3;
final List<IncomingMessage> messages = List.of(
new IncomingMessage(1, destinationDeviceId2, 2, "foo"),
new IncomingMessage(1, destinationDeviceId3, 3, "foo"));
new IncomingMessage(1, destinationDeviceId2, 2, "foo".getBytes(StandardCharsets.UTF_8)),
new IncomingMessage(1, destinationDeviceId3, 3, "foo".getBytes(StandardCharsets.UTF_8)));
final Map<Byte, Integer> registrationIds = Map.of((byte) 1, 17, destinationDeviceId2, 47, destinationDeviceId3, 89);
assertThrows(IllegalArgumentException.class,
() -> changeNumberManager.changeNumber(account, "+18005559876", new IdentityKey(Curve.generateKeyPair().getPublicKey()), null, null, messages, registrationIds));
() -> changeNumberManager.changeNumber(account, "+18005559876", new IdentityKey(Curve.generateKeyPair().getPublicKey()), null, null, messages, registrationIds, null));
}
}
@@ -10,12 +10,16 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNotNull;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.util.MockUtils.exactly;
@@ -26,6 +30,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -34,8 +39,10 @@ import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -45,9 +52,12 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagePersisterConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
@@ -75,6 +85,8 @@ class MessagePersisterTest {
private static final Duration PERSIST_DELAY = Duration.ofMinutes(5);
private static final double EXTRA_ROOM_RATIO = 2.0;
@BeforeEach
void setUp() throws Exception {
@@ -84,16 +96,21 @@ class MessagePersisterTest {
messagesDynamoDb = mock(MessagesDynamoDb.class);
accountsManager = mock(AccountsManager.class);
destinationAccount = mock(Account.class);;
destinationAccount = mock(Account.class);
when(accountsManager.getByAccountIdentifier(DESTINATION_ACCOUNT_UUID)).thenReturn(Optional.of(destinationAccount));
when(accountsManager.removeDevice(any(), anyByte()))
.thenAnswer(invocation -> CompletableFuture.completedFuture(invocation.getArgument(0)));
when(destinationAccount.getUuid()).thenReturn(DESTINATION_ACCOUNT_UUID);
when(destinationAccount.getIdentifier(IdentityType.ACI)).thenReturn(DESTINATION_ACCOUNT_UUID);
when(destinationAccount.getNumber()).thenReturn(DESTINATION_ACCOUNT_NUMBER);
when(destinationAccount.getDevice(DESTINATION_DEVICE_ID)).thenReturn(Optional.of(DESTINATION_DEVICE));
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getMessagePersisterConfiguration())
.thenReturn(new DynamicMessagePersisterConfiguration(true, EXTRA_ROOM_RATIO));
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
sharedExecutorService = Executors.newSingleThreadExecutor();
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
@@ -285,6 +302,66 @@ class MessagePersisterTest {
verify(accountsManager, exactly()).removeDevice(destinationAccount, DESTINATION_DEVICE_ID);
}
@Test
void testTrimOnFullPrimaryQueue() {
final byte[] queueName = MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, Device.PRIMARY_ID);
final Instant now = Instant.now();
final List<MessageProtos.Envelope> cachedMessages = Stream.generate(() -> generateMessage(
DESTINATION_ACCOUNT_UUID, UUID.randomUUID(), now.getEpochSecond(), ThreadLocalRandom.current().nextInt(100)))
.limit(10)
.toList();
final long cacheSize = cachedMessages.stream().mapToLong(MessageProtos.Envelope::getSerializedSize).sum();
for (MessageProtos.Envelope envelope : cachedMessages) {
messagesCache.insert(UUID.fromString(envelope.getServerGuid()), DESTINATION_ACCOUNT_UUID, Device.PRIMARY_ID, envelope).join();
}
final long expectedClearedBytes = (long) (cacheSize * EXTRA_ROOM_RATIO);
final int persistedMessageCount = 100;
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(persistedMessageCount);
final List<UUID> expectedClearedGuids = new ArrayList<>();
long total = 0L;
for (int i = 0; i < 100; i++) {
final UUID guid = UUID.randomUUID();
final MessageProtos.Envelope envelope = generateMessage(DESTINATION_ACCOUNT_UUID, guid, now.getEpochSecond(), 13);
persistedMessages.add(envelope);
if (total < expectedClearedBytes) {
total += envelope.getSerializedSize();
expectedClearedGuids.add(guid);
}
}
setNextSlotToPersist(SlotHash.getSlot(queueName));
final Device primary = mock(Device.class);
when(primary.getId()).thenReturn((byte) 1);
when(primary.isPrimary()).thenReturn(true);
when(primary.getFetchesMessages()).thenReturn(true);
when(destinationAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(primary));
when(messagesManager.persistMessages(any(UUID.class), any(), anyList()))
.thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
when(messagesManager.getMessagesForDeviceReactive(DESTINATION_ACCOUNT_UUID, primary, false))
.thenReturn(Flux.concat(
Flux.fromIterable(persistedMessages),
Flux.fromIterable(cachedMessages)));
when(messagesManager.delete(any(), any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
assertTimeoutPreemptively(Duration.ofSeconds(10), () ->
messagePersister.persistNextQueues(Clock.systemUTC().instant()));
verify(messagesManager, times(expectedClearedGuids.size()))
.delete(eq(DESTINATION_ACCOUNT_UUID), eq(primary), argThat(expectedClearedGuids::contains), isNotNull());
verify(messagesManager, never()).delete(any(), any(), argThat(guid -> !expectedClearedGuids.contains(guid)), any());
final List<String> queuesToPersist = messagesCache.getQueuesToPersist(SlotHash.getSlot(queueName),
Clock.systemUTC().instant(), 1);
assertEquals(queuesToPersist.size(), 1);
assertEquals(queuesToPersist.getFirst(), new String(queueName, StandardCharsets.UTF_8));
}
@Test
void testFailedUnlinkOnFullQueueThrowsForRetry() {
final String queueName = new String(
@@ -348,20 +425,23 @@ class MessagePersisterTest {
final Instant firstMessageTimestamp) {
for (int i = 0; i < messageCount; i++) {
final UUID messageGuid = UUID.randomUUID();
final MessageProtos.Envelope envelope = MessageProtos.Envelope.newBuilder()
.setDestinationServiceId(accountUuid.toString())
.setClientTimestamp(firstMessageTimestamp.toEpochMilli() + i)
.setServerTimestamp(firstMessageTimestamp.toEpochMilli() + i)
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(messageGuid.toString())
.build();
final MessageProtos.Envelope envelope = generateMessage(
accountUuid, messageGuid, firstMessageTimestamp.toEpochMilli() + i, 256);
messagesCache.insert(messageGuid, accountUuid, deviceId, envelope).join();
}
}
private MessageProtos.Envelope generateMessage(UUID accountUuid, UUID messageGuid, long messageTimestamp, int contentSize) {
return MessageProtos.Envelope.newBuilder()
.setDestinationServiceId(accountUuid.toString())
.setClientTimestamp(messageTimestamp)
.setServerTimestamp(messageTimestamp)
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(contentSize)))
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
.setServerGuid(messageGuid.toString())
.build();
}
private void setNextSlotToPersist(final int nextSlot) {
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
connection -> connection.sync().set(MessagesCache.NEXT_SLOT_TO_PERSIST_KEY, String.valueOf(nextSlot - 1)));
@@ -9,6 +9,8 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -54,6 +56,7 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
@@ -488,6 +491,67 @@ class MessagesCacheTest {
}, "Shared MRM data should be deleted asynchronously");
}
@Test
void testEstimatePersistedQueueSize() {
final UUID destinationUuid = UUID.randomUUID();
final ServiceIdentifier serviceId = new AciServiceIdentifier(destinationUuid);
final byte deviceId = 1;
// Should count all non-ephemeral, non-stale message bytes
long expectedQueueSize = 0L;
for (int i = 0; i < 400; i++) {
final MessageProtos.Envelope messageToInsert = switch (i % 4) {
// An MRM message
case 0 -> {
// First generate a random MRM message
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(serviceId, deviceId);
final SealedSenderMultiRecipientMessage.Recipient recepient = mrm.getRecipients()
.get(serviceId.toLibsignal());
// Calculate the size of a message that has the shared content in it
final MessageProtos.Envelope message = generateRandomMessage(UUID.randomUUID(), serviceId, true)
.toBuilder()
.setContent(ByteString.copyFrom(mrm.messageForRecipient(recepient)))
.build();
expectedQueueSize += message.getSerializedSize();
byte[] sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm).join();
// Insert the MRM message without the content
yield message
.toBuilder()
.clearContent()
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.build();
}
// A stale MRM message
case 1 ->
generateRandomMessage(UUID.randomUUID(), serviceId, true)
.toBuilder()
// clear some things added by the helper
.clearContent()
.setSharedMrmKey(MessagesCache.STALE_MRM_KEY)
.build();
// An ephemeral message
case 2 -> generateRandomMessage(UUID.randomUUID(), serviceId, true).toBuilder().setEphemeral(true).build();
// A standardard message
case 3 -> {
final MessageProtos.Envelope message = generateRandomMessage(UUID.randomUUID(), serviceId, true);
expectedQueueSize += message.getSerializedSize();
yield message;
}
default -> throw new IllegalStateException();
};
messagesCache.insert(UUID.fromString(messageToInsert.getServerGuid()), destinationUuid, deviceId, messageToInsert).join();
}
long actualQueueSize = messagesCache.estimatePersistedQueueSizeBytes(destinationUuid, deviceId).join();
assertEquals(expectedQueueSize, actualQueueSize);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testGetMessagesToPersist(final boolean sharedMrmKeyPresent) {
@@ -313,11 +313,14 @@ class MessagesDynamoDbTest {
assertThat(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice).join()).isFalse();
// used as the stable sort key, and the urgent message should be sorted last
int serverTimestamp = 1;
{
final MessageProtos.Envelope nonUrgentMessage = MessageProtos.Envelope.newBuilder()
.setUrgent(false)
.setServerGuid(UUID.randomUUID().toString())
.setDestinationServiceId(UUID.randomUUID().toString())
.setDestinationServiceId(destinationUuid.toString())
.setServerTimestamp(serverTimestamp++)
.build();
messagesDynamoDb.store(List.of(nonUrgentMessage), destinationUuid, destinationDevice);
@@ -326,13 +329,26 @@ class MessagesDynamoDbTest {
assertThat(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice).join()).isFalse();
{
final MessageProtos.Envelope urgentMessage = MessageProtos.Envelope.newBuilder()
final List<MessageProtos.Envelope> messages = new ArrayList<>();
// store more non-urgent messages
for (int i = 0; i < MessagesDynamoDb.MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT * 5; i++) {
messages.add(MessageProtos.Envelope.newBuilder()
.setUrgent(false)
.setServerGuid(UUID.randomUUID().toString())
.setDestinationServiceId(destinationUuid.toString())
.setServerTimestamp(serverTimestamp++)
.build());
}
// and one urgent message
messages.add(MessageProtos.Envelope.newBuilder()
.setUrgent(true)
.setServerGuid(UUID.randomUUID().toString())
.setDestinationServiceId(UUID.randomUUID().toString())
.build();
.setDestinationServiceId(destinationUuid.toString())
.setServerTimestamp(serverTimestamp++)
.build());
messagesDynamoDb.store(List.of(urgentMessage), destinationUuid, destinationDevice);
messagesDynamoDb.store(messages, destinationUuid, destinationDevice);
}
assertThat(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice).join()).isTrue();
@@ -15,6 +15,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.api.client.http.HttpResponseException;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
import com.google.api.services.androidpublisher.model.BasePlan;
@@ -33,11 +34,14 @@ import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
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.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.MockUtils;
@@ -177,6 +181,16 @@ class GooglePlayBillingManagerTest {
verify(cancel, times(wanted)).execute();
}
@Test
public void cancelMissingSubscription() throws IOException {
final HttpResponseException mockException = mock(HttpResponseException.class);
when(mockException.getStatusCode()).thenReturn(404);
when(subscriptionsv2Get.execute()).thenThrow(mockException);
assertThatNoException().isThrownBy(() ->
googlePlayBillingManager.cancelAllActiveSubscriptions(PURCHASE_TOKEN).join());
verifyNoInteractions(cancel);
}
@Test
public void getReceiptUnacknowledged() throws IOException {
when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2()
@@ -257,4 +271,22 @@ class GooglePlayBillingManagerTest {
}
public static Stream<Arguments> tokenErrors() {
return Stream.of(
Arguments.of(404, SubscriptionException.NotFound.class),
Arguments.of(410, SubscriptionException.NotFound.class),
Arguments.of(400, HttpResponseException.class)
);
}
@ParameterizedTest
@MethodSource
public void tokenErrors(final int httpStatus, Class<? extends Exception> expected) throws IOException {
final HttpResponseException mockException = mock(HttpResponseException.class);
when(mockException.getStatusCode()).thenReturn(httpStatus);
when(subscriptionsv2Get.execute()).thenThrow(mockException);
CompletableFutureTestUtil.assertFailsWithCause(expected,
googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN));
}
}
@@ -164,7 +164,6 @@ currentReportingKey.salt: AAAAAAAAAAA=
registrationService.collationKeySalt: AAAAAAAAAAA=
turn.secret: AAAAAAAAAAA=
turn.cloudflare.apiToken: ABCDEFGHIJKLM
linkDevice.secret: AAAAAAAAAAA=
@@ -467,7 +467,6 @@ keyTransparencyService:
clientPrivateKey: secret://keyTransparencyService.clientPrivateKey
turn:
secret: secret://turn.secret
cloudflare:
apiToken: secret://turn.cloudflare.apiToken
endpoint: https://rtc.live.cloudflare.com/v1/turn/keys/LMNOP/credentials/generate
@@ -484,18 +483,6 @@ turn:
linkDevice:
secret: secret://linkDevice.secret
maxmindCityDatabase:
type: static
callingTurnDnsRecords:
type: static
callingTurnPerformanceTable:
type: static
callingTurnManualTable:
type: static
noiseTunnel:
port: 8443
noiseStaticPrivateKey: secret://noiseTunnel.noiseStaticPrivateKey