Compare commits

...
Author SHA1 Message Date
Jon Chambers 4d81124dfa Remove redundant disconnection requests 2025-07-24 10:33:10 -04:00
Jonathan Klabunde Tomer ccf8840fa3 fix accidental reversal of metrics 2025-07-24 10:32:34 -04:00
Katherine 267aafe861 Encrypt device creation timestamp crawler 2025-07-24 10:29:52 -04:00
Chris Eager 1bdcfb1d83 Don’t unnecessarily reinitialize test DynamoDB client 2025-07-23 13:32:58 -05:00
Chris Eager 0c69ef9381 Update to the latest version of the spam filter 2025-07-23 13:18:39 -05:00
Chris Eager c99b1cada1 Add overrides configuration to LocalDynamoDbFactory 2025-07-23 13:13:23 -05:00
Chris Eager 83d19ac8ed Update localstack test container to 4.x 2025-07-23 13:13:23 -05:00
Chris Eager 5f77d7f582 Migrate from embedded DynamoDBLocal to Testcontainers 2025-07-23 13:13:23 -05:00
Katherine 96f6e75702 Introduce encrypted device creation timestamps 2025-07-23 10:36:11 -04:00
Katherine 74c7e49cea Replace device creation timestamps with registration IDs in experiment logic 2025-07-23 10:24:28 -04:00
Jon Chambers 876bf15a11 Extend timeouts for Redis client tests 2025-07-23 10:24:07 -04:00
Chris Eager de60752219 Convert Profiles gRPC to SimpleGrpc 2025-07-23 10:23:48 -04:00
Katherine 5d80ac73da Update libsignal to 0.76.5 2025-07-23 10:22:48 -04:00
Ravi Khadiwala 0ff32d5cae Update to the latest version of the spam filter 2025-07-21 12:01:45 -05:00
Chris Eager 4618b47141 Convert classes using @JsonUnwrapped to records 2025-07-21 11:52:25 -05:00
Ravi Khadiwala 94361b2d5d Remove allow list from pin event monitor 2025-07-21 11:50:30 -05:00
Ravi Khadiwala d4429ebce1 Update to Java 24 and add .java-version 2025-07-21 11:50:30 -05:00
Jonathan Klabunde TomerandChris Eager b5711ead25 /v2/config: don't return configs namespaced to different platforms
Co-authored-by: Chris Eager <79161849+eager-signal@users.noreply.github.com>
2025-07-18 14:59:41 -07:00
ravi-signal 522ddd4e61 Add documentation for 413 response from /v1/archives/upload/form 2025-07-18 14:59:26 -07:00
Jon Chambers 73365369df Fix a silly typo when generating Redis URIs for tests 2025-07-17 13:16:14 -04:00
Jon Chambers 631b9a5290 Measure the rate of new WebSocket connections by authentication type 2025-07-17 11:35:15 -04:00
Jon Chambers 4ccd39fd55 Validate intra-account messages before applying number changes 2025-07-17 11:34:50 -04:00
Jon Chambers 50bc6b2c62 Update to the latest version of the spam filter 2025-07-17 11:33:46 -04:00
Jon Chambers 609b86acb9 Inline the cluster compose file 2025-07-17 11:17:40 -04:00
Jon Chambers 1ea84483da Copy Redis cluster compose file to a temporary file 2025-07-17 11:17:40 -04:00
Jon Chambers ed5086823c Extend timeout for MessagePersisterTest 2025-07-17 10:00:48 -04:00
Jon Chambers 73748a6341 Create new Redis client resources for each test 2025-07-17 10:00:48 -04:00
Jon Chambers 1f60300555 Remove embedded-redis as a dependency 2025-07-17 10:00:48 -04:00
Jon Chambers 85a13a9dc0 Extend lifecycle of Redis cluster clients 2025-07-17 10:00:48 -04:00
Jon Chambers 803e73bd1e Use a Redis testcontainer instead of embedded-redis in RedisClusterExtension 2025-07-17 10:00:48 -04:00
Jon Chambers a3356d0188 Use a Redis testcontainer instead of embedded-redis in RedisServerExtension 2025-07-17 10:00:48 -04:00
Jonathan Klabunde Tomer 5c21aa2ad4 implement /v2/config API (#2764) 2025-07-16 15:29:31 -07:00
Jon Chambers 6116830da9 Remove spurious null checks 2025-07-16 12:34:20 -04:00
Jon Chambers 650bc2598b Retire AccountsManager#updatePniKeys and associated plumbing 2025-07-16 12:34:20 -04:00
Jon Chambers a36fba061a Remove "no action on change to same number" optimization for "change number" operations 2025-07-16 12:34:20 -04:00
Jon Chambers e62b3d390f Accquire pessimistic account locks by sets of identifiers instead of lists 2025-07-16 12:34:20 -04:00
Jon Chambers 1a8ebf80b5 Add an integration test for changing to the same phone number 2025-07-16 12:34:20 -04:00
Jon Chambers 2564f706d8 Retire the "distribute PNI key material" endpoint 2025-07-16 12:34:20 -04:00
Ravi Khadiwala c97c00bf5f Fix the play mapping to stripe statuses
CANCELLED in play terminiology is the same as an active subscription
with cancelAtPeriodEnd set. So it should map to the ACTIVE stripe
status. EXPIRED is the equivalent of a stripe CANCELLED subscription.
2025-07-16 11:19:15 -05:00
Ravi Khadiwala 702b125a48 Accept all entitled play tokens 2025-07-16 11:19:15 -05:00
Chris Eager ca9f29f984 Only delete profile avatars during explicit delete actions
This preserves the avatar during re-registration, when PIN recovery might occur.
2025-07-15 16:19:52 -05:00
ravi-signal 58b9fa100d Remove from svrb on account deletion 2025-07-15 16:17:14 -05:00
ravi-signal 656b08f3b6 Avoid potential concurrent modification in KeysController 2025-07-15 16:15:08 -05:00
Ravi Khadiwala 3f62677176 Allow optional size parameter when requesting message backup upload forms 2025-07-15 16:14:33 -05:00
140 changed files with 3162 additions and 2572 deletions

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
- uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
with:
distribution: 'temurin'
java-version: '21'
java-version-file: .java-version
cache: 'maven'
- name: Compile and Build OpenAPI file
run: ./mvnw compile
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
- uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with:
distribution: 'temurin'
java-version: '21'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v4.2.1
name: Configure AWS credentials from Test account
+3 -3
View File
@@ -9,7 +9,7 @@ on:
jobs:
build:
runs-on: ubuntu-latest
container: ubuntu:22.04
container: ubuntu:24.04
timeout-minutes: 20
services:
@@ -21,11 +21,11 @@ jobs:
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up JDK 21
- name: Set up JDK
uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
with:
distribution: 'temurin'
java-version: 21
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
+1 -2
View File
@@ -16,7 +16,6 @@ config/deploy.properties
/service/config/testing.yml
/service/config/deploy.properties
/service/dependency-reduced-pom.xml
.java-version
.opsmanage
put.sh
deployer-staging.properties
@@ -29,4 +28,4 @@ deployer.log
.project
.classpath
.settings
.DS_Store
.DS_Store
+1
View File
@@ -0,0 +1 @@
temurin-24
@@ -14,7 +14,6 @@ import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Base64;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
public final class Codecs {
@@ -84,7 +83,7 @@ public final class Codecs {
public static class ECPublicKeyDeserializer extends Base64BasedDeserializer<ECPublicKey> {
public ECPublicKeyDeserializer() {
super(bytes -> Curve.decodePoint(bytes, 0));
super(ECPublicKey::new);
}
}
@@ -34,7 +34,6 @@ import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
import org.signal.integration.config.Config;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.kem.KEMKeyPair;
@@ -45,6 +44,7 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
@@ -78,8 +78,8 @@ public final class Operations {
final TestUser user = TestUser.create(number, accountPassword, registrationPassword);
final AccountAttributes accountAttributes = user.accountAttributes();
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
// register account
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
@@ -88,12 +88,12 @@ public final class Operations {
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
generateSignedECPreKey(1, aciIdentityKeyPair),
generateSignedECPreKey(2, pniIdentityKeyPair),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
generateSignedKEMPreKey(4, pniIdentityKeyPair),
Optional.empty(),
Optional.empty());
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
generateSignedECPreKey(2, pniIdentityKeyPair),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
generateSignedKEMPreKey(4, pniIdentityKeyPair),
Optional.empty(),
Optional.empty()));
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
.authorized(number, accountPassword)
@@ -336,7 +336,7 @@ public final class Operations {
}
public static ECSignedPreKey generateSignedECPreKey(final long id, final ECKeyPair identityKeyPair) {
final ECPublicKey pubKey = Curve.generateKeyPair().getPublicKey();
final ECPublicKey pubKey = ECKeyPair.generate().getPublicKey();
final byte[] signature = identityKeyPair.getPrivateKey().calculateSignature(pubKey.serialize());
return new ECSignedPreKey(id, pubKey, signature);
}
@@ -9,8 +9,6 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.tuple.Pair;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
@@ -50,15 +48,11 @@ public class TestDevice {
}
public SignedPreKeyRecord addSignedPreKey(final IdentityKeyPair identity) {
try {
final int nextId = signedPreKeys.keySet().stream().mapToInt(k -> k + 1).max().orElse(0);
final ECKeyPair keyPair = Curve.generateKeyPair();
final byte[] signature = Curve.calculateSignature(identity.getPrivateKey(), keyPair.getPublicKey().serialize());
final SignedPreKeyRecord signedPreKeyRecord = new SignedPreKeyRecord(nextId, System.currentTimeMillis(), keyPair, signature);
signedPreKeys.put(nextId, Pair.of(identity, signedPreKeyRecord));
return signedPreKeyRecord;
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
final int nextId = signedPreKeys.keySet().stream().mapToInt(k -> k + 1).max().orElse(0);
final ECKeyPair keyPair = ECKeyPair.generate();
final byte[] signature = keyPair.getPrivateKey().calculateSignature(keyPair.getPublicKey().serialize());
final SignedPreKeyRecord signedPreKeyRecord = new SignedPreKeyRecord(nextId, System.currentTimeMillis(), keyPair, signature);
signedPreKeys.put(nextId, Pair.of(identity, signedPreKeyRecord));
return signedPreKeyRecord;
}
}
@@ -17,7 +17,6 @@ import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Test;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.usernames.Username;
@@ -64,7 +63,7 @@ public class AccountTest {
final TestUser user = Operations.newRegisteredUser("+19995550301");
final String targetNumber = "+19995550302";
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final ChangeNumberRequest changeNumberRequest = new ChangeNumberRequest(null,
Operations.populateRandomRecoveryPassword(targetNumber),
+12 -17
View File
@@ -43,8 +43,6 @@
<commons-io.version>2.19.0</commons-io.version>
<dropwizard.version>4.0.12</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.14</dropwizard-metrics-datadog.version>
<!-- can be updated to latest version with Dropwizard 5 (Jetty 12); will then need to disable telemetry -->
<dynamodblocal.version>2.2.1</dynamodblocal.version>
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
with even-numbered patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDB
@@ -86,11 +84,14 @@
<swagger.version>2.2.31</swagger.version>
<testcontainers.version>1.21.2</testcontainers.version>
<!-- image to use in tests that run localstack via docker. -->
<localstack.image>localstack/localstack:3.5.0</localstack.image>
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
<localstack.image>localstack/localstack:4@sha256:5a97e0f9917a3f0d9630bb13b9d8ccf10cbe52f33252807d3b4e21418cc21348</localstack.image>
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
<redis-cluster.image>docker.io/bitnami/redis-cluster:7.4@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
<!-- eclipse-temurin:21.0.6_7-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>02fc89fa8766a9ba221e69225f8d1c10bb91885ddbd3c112448e23488ba40ab6</docker.image.sha256>
<!-- eclipse-temurin:24.0.1_9-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>a42f2330212db8bc1459a2550def18f6ec04a8c31494ffc20dea13dfa82a211e</docker.image.sha256>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -269,15 +270,15 @@
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.9.1</version>
<groupId>com.redis</groupId>
<artifactId>testcontainers-redis</artifactId>
<version>2.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.67.6</version>
<version>0.76.5</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
@@ -306,12 +307,6 @@
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<version>${dynamodblocal.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
@@ -506,7 +501,7 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<release>21</release>
<release>24</release>
</configuration>
</plugin>
+8 -11
View File
@@ -479,8 +479,8 @@
</dependency>
<dependency>
<groupId>org.signal</groupId>
<artifactId>embedded-redis</artifactId>
<groupId>com.redis</groupId>
<artifactId>testcontainers-redis</artifactId>
<scope>test</scope>
</dependency>
@@ -491,12 +491,6 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>localstack</artifactId>
@@ -758,6 +752,12 @@
<goal>filter-sources</goal>
</goals>
</execution>
<execution>
<id>filter-test-src</id>
<goals>
<goal>filter-test-sources</goal>
</goals>
</execution>
</executions>
</plugin>
@@ -767,9 +767,6 @@
<configuration>
<!-- add-opens: work around PATCH not being a supported method on HttpUrlConnection -->
<argLine>-javaagent:${org.mockito:mockito-core:jar} --add-opens=java.base/java.net=ALL-UNNAMED</argLine>
<systemPropertyVariables>
<localstackImage>${localstack.image}</localstackImage>
</systemPropertyVariables>
</configuration>
</plugin>
@@ -122,6 +122,7 @@ import org.whispersystems.textsecuregcm.controllers.ProfileController;
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
import org.whispersystems.textsecuregcm.controllers.RegistrationController;
import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
import org.whispersystems.textsecuregcm.controllers.RemoteConfigControllerV1;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecoveryBController;
@@ -205,7 +206,7 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
@@ -271,6 +272,7 @@ import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.EncryptDeviceCreationTimestampCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
@@ -345,6 +347,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new IdleDeviceNotificationSchedulerFactory()));
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
bootstrap.addCommand(new EncryptDeviceCreationTimestampCommand());
}
@Override
@@ -508,8 +511,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.maxThreads(1).minThreads(1).build();
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "fcmSender-%d"))
.maxThreads(32).minThreads(32).workQueue(fcmSenderQueue).build();
ExecutorService secureValueRecovery2ServiceExecutor = environment.lifecycle()
.executorService(name(getClass(), "secureValueRecoveryService2-%d")).maxThreads(1).minThreads(1).build();
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
.executorService(name(getClass(), "secureValueRecoveryService-%d")).maxThreads(1).minThreads(1).build();
ExecutorService storageServiceExecutor = environment.lifecycle()
.executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
ExecutorService virtualThreadEventLoggerExecutor = environment.lifecycle()
@@ -624,8 +627,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getKeyTransparencyServiceConfiguration().tlsCertificate(),
config.getKeyTransparencyServiceConfiguration().clientCertificate(),
config.getKeyTransparencyServiceConfiguration().clientPrivateKey().value());
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
secureValueRecovery2ServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
SecureValueRecoveryClient secureValueRecovery2Client = new SecureValueRecoveryClient(
svr2CredentialsGenerator,
secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
config.getSvr2Configuration(),
() -> dynamicConfigurationManager.getConfiguration().getSvr2StatusCodesToIgnoreForAccountDeletion());
SecureValueRecoveryClient secureValueRecoveryBClient = new SecureValueRecoveryClient(
svrbCredentialsGenerator,
secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
config.getSvrbConfiguration(),
() -> dynamicConfigurationManager.getConfiguration().getSvrbStatusCodesToIgnoreForAccountDeletion());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
@@ -646,7 +659,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
@@ -689,7 +702,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager, experimentEnrollmentManager);
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
config.getTurnConfiguration().cloudflare().apiToken().value(),
@@ -726,7 +739,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
cacheCluster, config.getPaymentsServiceConfiguration().paymentCurrencies(), recurringJobExecutor, Clock.systemUTC());
VirtualThreadPinEventMonitor virtualThreadPinEventMonitor = new VirtualThreadPinEventMonitor(
virtualThreadEventLoggerExecutor,
() -> dynamicConfigurationManager.getConfiguration().getVirtualThreads().allowedPinEvents(),
config.getVirtualThreadConfiguration().pinEventThreshold());
StripeManager stripeManager = new StripeManager(config.getStripe().apiKey().value(), subscriptionProcessorExecutor,
@@ -1121,6 +1133,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters),
new RemoteConfigControllerV1(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
@@ -9,7 +9,6 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.security.InvalidKeyException;
import java.util.concurrent.TimeUnit;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
@@ -45,11 +44,7 @@ public class CertificateGenerator {
byte[] certificate = builder.build().toByteArray();
byte[] signature;
try {
signature = Curve.calculateSignature(privateKey, certificate);
} catch (org.signal.libsignal.protocol.InvalidKeyException e) {
throw new InvalidKeyException(e);
}
signature = privateKey.calculateSignature(certificate);
return SenderCertificate.newBuilder()
.setCertificate(ByteString.copyFrom(certificate))
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -25,7 +26,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -54,6 +55,7 @@ public class BackupManager {
static final String MESSAGE_BACKUP_NAME = "messageBackup";
public static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = DataSize.gibibytes(100).toBytes();
public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
// If the last media usage recalculation is over MAX_QUOTA_STALENESS, force a recalculation before quota enforcement.
@@ -525,7 +527,7 @@ public class BackupManager {
}
}
private static final ECPublicKey INVALID_PUBLIC_KEY = Curve.generateKeyPair().getPublicKey();
private static final ECPublicKey INVALID_PUBLIC_KEY = ECKeyPair.generate().getPublicKey();
/**
* Authenticate the ZK anonymous backup credential's presentation
@@ -4,7 +4,6 @@ import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import javax.annotation.Nullable;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
@@ -19,7 +18,7 @@ public record NoiseTunnelConfiguration(@Positive int webSocketPort,
@NotNull SecretString recognizedProxySecret) {
public ECKeyPair noiseStaticKeyPair() throws InvalidKeyException {
final ECPrivateKey privateKey = Curve.decodePrivatePoint(noiseStaticPrivateKey().value());
final ECPrivateKey privateKey = new ECPrivateKey(noiseStaticPrivateKey().value());
return new ECKeyPair(privateKey.publicKey(), privateKey);
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.ExactlySize;
@@ -17,6 +16,6 @@ public record UnidentifiedDeliveryConfiguration(@NotNull @NotEmpty byte[] certi
@ExactlySize(32) SecretBytes privateKey,
int expiresDays) {
public ECPrivateKey ecPrivateKey() throws InvalidKeyException {
return Curve.decodePrivatePoint(privateKey.value());
return new ECPrivateKey(privateKey.value());
}
}
@@ -6,7 +6,6 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.vdurmont.semver4j.Semver;
import jakarta.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
@@ -14,7 +13,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public class DynamicConfiguration {
@@ -50,17 +48,17 @@ public class DynamicConfiguration {
@Valid
DynamicRegistrationConfiguration registrationConfiguration = new DynamicRegistrationConfiguration(false);
@JsonProperty
@Valid
DynamicVirtualThreadConfiguration virtualThreads = new DynamicVirtualThreadConfiguration(Collections.emptySet());
@JsonProperty
@Valid
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false);
@JsonProperty
@Valid
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
List<Integer> svr2StatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
@JsonProperty
@Valid
List<Integer> svrbStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
@JsonProperty
@Valid
@@ -100,16 +98,16 @@ public class DynamicConfiguration {
return registrationConfiguration;
}
public DynamicVirtualThreadConfiguration getVirtualThreads() {
return virtualThreads;
}
public DynamicMetricsConfiguration getMetricsConfiguration() {
return metricsConfiguration;
}
public List<String> getSvrStatusCodesToIgnoreForAccountDeletion() {
return svrStatusCodesToIgnoreForAccountDeletion;
public List<Integer> getSvr2StatusCodesToIgnoreForAccountDeletion() {
return svr2StatusCodesToIgnoreForAccountDeletion;
}
public List<Integer> getSvrbStatusCodesToIgnoreForAccountDeletion() {
return svrbStatusCodesToIgnoreForAccountDeletion;
}
public DynamicRestDeprecationConfiguration restDeprecation() {
@@ -1,10 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import java.util.Set;
public record DynamicVirtualThreadConfiguration(Set<String> allowedPinEvents) {}
@@ -171,6 +171,8 @@ public class AccountControllerV2 {
}
}
// TODO Remove entirely on or after 2025-10-08
@Deprecated(forRemoval = true)
@PUT
@Path("/phone_number_identity_key_distribution")
@Consumes(MediaType.APPLICATION_JSON)
@@ -181,11 +183,6 @@ public class AccountControllerV2 {
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "This endpoint can only be invoked from the account's primary device.")
@ApiResponse(responseCode = "422", description = "The request body failed validation.")
@ApiResponse(responseCode = "409", description = "The set of devices specified in the request does not match the set of devices active on the account.",
content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.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 = StaleDevicesResponse.class)))
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
@Auth final AuthenticatedDevice authenticatedDevice,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString,
@@ -199,38 +196,8 @@ public class AccountControllerV2 {
throw new WebApplicationException("Invalid signature", 422);
}
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
try {
final Account updatedAccount = changeNumberManager.updatePniKeys(
account,
request.pniIdentityKey(),
request.devicePniSignedPrekeys(),
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds(),
userAgentString);
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (MismatchedDevicesException e) {
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
.build());
} else {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
e.getMismatchedDevices().extraDeviceIds()))
.build());
}
} catch (IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
return AccountIdentityResponseBuilder.fromAccount(accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED)));
}
@PUT
@@ -505,6 +505,7 @@ public class ArchiveController {
description = "Retrieve an upload form that can be used to perform a resumable upload of a message backup.")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change.")
@ApiResponseZkAuth
public CompletionStage<UploadDescriptorResponse> backup(
@Auth final Optional<AuthenticatedDevice> account,
@@ -516,12 +517,24 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@Parameter(description = "The size of the message backup to upload in bytes")
@QueryParam("uploadLength") final Optional<Long> uploadLength) {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
.thenCompose(backupManager::createMessageBackupUploadDescriptor)
.thenCompose(backupUser -> {
final boolean oversize = uploadLength
.map(length -> length > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE)
.orElse(false);
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
if (oversize) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
return backupManager.createMessageBackupUploadDescriptor(backupUser);
})
.thenApply(result -> new UploadDescriptorResponse(
result.cdn(),
result.key(),
@@ -74,6 +74,8 @@ import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v2/keys")
@@ -388,43 +390,36 @@ public class KeysController {
}
final List<Device> devices = parseDeviceId(deviceId, target);
final List<PreKeyResponseItem> responseItems = new ArrayList<>(devices.size());
final List<CompletableFuture<Void>> tasks = devices.stream().map(device -> {
final CompletableFuture<Optional<ECPreKey>> unsignedEcPreKeyFuture =
keysManager.takeEC(targetIdentifier.uuid(), device.getId());
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(devices)
.flatMap(device -> Mono.zip(
Mono.just(device),
Mono.fromFuture(keysManager.takeEC(targetIdentifier.uuid(), device.getId())),
Mono.fromFuture(keysManager.getEcSignedPreKey(targetIdentifier.uuid(), device.getId())),
Mono.fromFuture(keysManager.takePQ(targetIdentifier.uuid(), device.getId()))))
.flatMap(deviceAndPreKeys -> {
final Device device = deviceAndPreKeys.getT1();
final KEMSignedPreKey pqPreKey = deviceAndPreKeys.getT4().orElse(null);
final ECPreKey unsignedEcPreKey = deviceAndPreKeys.getT2().orElse(null);
final ECSignedPreKey signedEcPreKey = deviceAndPreKeys.getT3().orElse(null);
final CompletableFuture<Optional<ECSignedPreKey>> signedEcPreKeyFuture =
keysManager.getEcSignedPreKey(targetIdentifier.uuid(), device.getId());
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(IDENTITY_TYPE_TAG_NAME, targetIdentifier.identityType().name()),
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
.increment();
final CompletableFuture<Optional<KEMSignedPreKey>> pqPreKeyFuture =
keysManager.takePQ(targetIdentifier.uuid(), device.getId());
return CompletableFuture.allOf(unsignedEcPreKeyFuture, signedEcPreKeyFuture, pqPreKeyFuture)
.thenAccept(ignored -> {
final KEMSignedPreKey pqPreKey = pqPreKeyFuture.join().orElse(null);
final ECPreKey unsignedEcPreKey = unsignedEcPreKeyFuture.join().orElse(null);
final ECSignedPreKey signedEcPreKey = signedEcPreKeyFuture.join().orElse(null);
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(IDENTITY_TYPE_TAG_NAME, targetIdentifier.identityType().name()),
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
.increment();
if (signedEcPreKey != null || unsignedEcPreKey != null || pqPreKey != null) {
final int registrationId = device.getRegistrationId(targetIdentifier.identityType());
responseItems.add(
new PreKeyResponseItem(device.getId(), registrationId, signedEcPreKey, unsignedEcPreKey,
pqPreKey));
}
});
if (signedEcPreKey != null || unsignedEcPreKey != null || pqPreKey != null) {
final int registrationId = device.getRegistrationId(targetIdentifier.identityType());
return Mono.just(new PreKeyResponseItem(
device.getId(), registrationId, signedEcPreKey, unsignedEcPreKey, pqPreKey));
} else {
return Mono.empty();
}
})
.toList();
CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
.collectList()
.block();
final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType());
@@ -429,7 +429,8 @@ public class MessageController {
isStory,
messages.online(),
messages.urgent(),
spamCheckResult.token().orElse(null));
spamCheckResult.token().orElse(null),
clock);
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", message.type(), userAgent);
throw new BadRequestException(e);
@@ -193,7 +193,7 @@ public class ProfileController {
request.commitment().serialize()));
if (request.getAvatarChange() != CreateProfileRequest.AvatarChange.UNCHANGED) {
currentAvatar.ifPresent(s -> profilesManager.deleteAvatar(s).join());
currentAvatar.ifPresent(profilesManager::deleteAvatar);
}
accountsManager.update(account, a -> {
@@ -64,7 +64,6 @@ public class RegistrationController {
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
private static final String REGION_CODE_TAG_NAME = "regionCode";
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
private static final String INVALID_ACCOUNT_ATTRS_COUNTER_NAME = name(RegistrationController.class, "invalidAccountAttrs");
private final AccountsManager accounts;
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
@@ -1,5 +1,5 @@
/*
* Copyright 2013 Signal Messenger, LLC
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
@@ -8,80 +8,137 @@ package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.Arrays;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfig;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@Path("/v1/config")
@Path("/v2/config")
@Tag(name = "Remote Config")
public class RemoteConfigController {
private final RemoteConfigsManager remoteConfigsManager;
private final Map<String, String> globalConfig;
private final Clock clock;
private static final String GLOBAL_CONFIG_PREFIX = "global.";
private static final Set<String> PLATFORM_PREFIXES = Arrays.stream(ClientPlatform.values())
.map(p -> p.name().toLowerCase())
.collect(Collectors.toSet());
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager,
Map<String, String> globalConfig,
final Clock clock) {
this.remoteConfigsManager = remoteConfigsManager;
this.globalConfig = globalConfig;
this.clock = clock;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Fetch remote configuration",
description = """
Remote configuration is a list of namespaced keys that clients may use for consistent configuration or behavior.
Configuration values change over time, and the list should be refreshed periodically, typically at client
launch and every few hours thereafter.
"""
description = "Remote configuration is a list of namespaced keys that clients may use for consistent configuration or behavior. Configuration values change over time, and the list should be refreshed periodically, typically at client launch and every few hours thereafter. Some values depend on the authenticated user, so the list should be refreshed immediately if the user changes."
)
@ApiResponse(responseCode = "200", description = "Remote configuration values for the authenticated user", useReturnTypeSchema = true)
public UserRemoteConfigList getAll(@Auth AuthenticatedDevice auth) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA1");
@ApiResponse(
responseCode = "200",
description = "Remote configuration values for the authenticated user",
content = @Content(schema = @Schema(implementation = RemoteConfigurationResponse.class)),
headers = @Header(name = "ETag", description = "A hash of the configuration content which can be supplied in an If-None-Match header on future requests"))
@ApiResponse(responseCode = "304", description = "There is no change since the last fetch", content = {})
@ApiResponse(responseCode = "401", description = "This request requires authentication", content = {})
final Stream<UserRemoteConfig> globalConfigStream = globalConfig.entrySet().stream()
.map(entry -> new UserRemoteConfig(GLOBAL_CONFIG_PREFIX + entry.getKey(), true, entry.getValue()));
return new UserRemoteConfigList(Stream.concat(remoteConfigsManager.getAll().stream().map(config -> {
final byte[] hashKey = config.getHashKey() != null ? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(),
config.getUuids());
return new UserRemoteConfig(config.getName(), inBucket,
inBucket ? config.getValue() : config.getDefaultValue());
}), globalConfigStream).collect(Collectors.toList()), clock.instant());
public Response getAll(
@Auth AuthenticatedDevice auth,
@Parameter(description = "The ETag header supplied with a previous response from this endpoint. Optional.")
@HeaderParam(HttpHeaders.IF_NONE_MATCH)
@Nullable EntityTag eTag,
@Parameter(description = "The user agent in standard form.")
@HeaderParam(HttpHeaders.USER_AGENT)
String userAgent
) {
final String platformPrefix = platformPrefix(userAgent);
final List<RemoteConfig> remoteConfigs = remoteConfigsManager.getAll();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Map<String, String> configs = Stream.concat(
remoteConfigs.stream()
.filter(config -> {
final String firstNameComponent = config.getName().split("\\.", 2)[0];
return firstNameComponent.equals(platformPrefix) || !PLATFORM_PREFIXES.contains(firstNameComponent);
})
.map(
config -> {
final byte[] hashKey = config.getHashKey() != null
? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(), config.getUuids());
final String value = inBucket ? config.getValue() : config.getDefaultValue();
return Pair.of(config.getName(), value == null ? String.valueOf(inBucket) : value);
}),
globalConfig.entrySet().stream()
.map(e -> Pair.of(GLOBAL_CONFIG_PREFIX + e.getKey(), e.getValue())))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
final EntityTag newETag = new EntityTag(HexFormat.of().toHexDigits(configs.hashCode()));
if (newETag.equals(eTag)) {
return Response.notModified(eTag).build();
}
return Response.ok(new RemoteConfigurationResponse(configs))
.tag(newETag)
.build();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String platformPrefix(final String userAgent) {
try {
return UserAgentUtil.parseUserAgentString(userAgent).platform().name().toLowerCase();
} catch (UnrecognizedUserAgentException e) {
return null;
}
}
@VisibleForTesting
public static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
Set<UUID> uuidsInBucket) {
@@ -89,7 +146,7 @@ public class RemoteConfigController {
return true;
}
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
ByteBuffer bb = ByteBuffer.allocate(16);
bb.putLong(uid.getMostSignificantBits());
bb.putLong(uid.getLeastSignificantBits());
@@ -0,0 +1,107 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfig;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
@Path("/v1/config")
@Tag(name = "Remote Config")
public class RemoteConfigControllerV1 {
private final RemoteConfigsManager remoteConfigsManager;
private final Map<String, String> globalConfig;
private final Clock clock;
private static final String GLOBAL_CONFIG_PREFIX = "global.";
public RemoteConfigControllerV1(RemoteConfigsManager remoteConfigsManager,
Map<String, String> globalConfig,
final Clock clock) {
this.remoteConfigsManager = remoteConfigsManager;
this.globalConfig = globalConfig;
this.clock = clock;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Deprecated
@Operation(
summary = "Fetch remote configuration (deprecated)",
description = """
Remote configuration is a list of namespaced keys that clients may use for consistent configuration or behavior.
Configuration values change over time, and the list should be refreshed periodically, typically at client
launch and every few hours thereafter.
This endpoint is deprecated; use GET /v2/config instead
"""
)
@ApiResponse(responseCode = "200", description = "Remote configuration values for the authenticated user", useReturnTypeSchema = true)
public UserRemoteConfigList getAll(@Auth AuthenticatedDevice auth) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Stream<UserRemoteConfig> globalConfigStream = globalConfig.entrySet().stream()
.map(entry -> new UserRemoteConfig(GLOBAL_CONFIG_PREFIX + entry.getKey(), true, entry.getValue()));
return new UserRemoteConfigList(Stream.concat(remoteConfigsManager.getAll().stream().map(config -> {
final byte[] hashKey = config.getHashKey() != null ? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(),
config.getUuids());
return new UserRemoteConfig(config.getName(), inBucket,
inBucket ? config.getValue() : config.getDefaultValue());
}), globalConfigStream).collect(Collectors.toList()), clock.instant());
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
@VisibleForTesting
public static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
Set<UUID> uuidsInBucket) {
if (uuidsInBucket.contains(uid)) {
return true;
}
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uid.getMostSignificantBits());
bb.putLong(uid.getLeastSignificantBits());
digest.update(bb.array());
byte[] hash = digest.digest(hashKey);
int bucket = (int) (Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
return bucket < configPercentage;
}
}
@@ -178,11 +178,11 @@ public class VerificationController {
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
request.getUpdateVerificationSessionRequest());
request.updateVerificationSessionRequest());
final Phonenumber.PhoneNumber phoneNumber;
try {
phoneNumber = Util.canonicalizePhoneNumber(PhoneNumberUtil.getInstance().parse(request.getNumber(), null));
phoneNumber = Util.canonicalizePhoneNumber(PhoneNumberUtil.getInstance().parse(request.number(), null));
} catch (final NumberParseException e) {
throw new ServerErrorException("could not parse already validated number", Response.Status.INTERNAL_SERVER_ERROR);
}
@@ -192,7 +192,7 @@ public class VerificationController {
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber, sourceHost,
accountsManager.getByE164(request.getNumber()).isPresent(),
accountsManager.getByE164(request.number()).isPresent(),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CancellationException e) {
@@ -8,25 +8,11 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import io.swagger.v3.oas.annotations.media.Schema;
// Note, this class cannot be converted into a record because @JsonUnwrapped does not work with records until 2.19. We are on 2.18 until Dropwizard’s BOM updates.
// https://github.com/FasterXML/jackson-databind/issues/1467
public class AccountCreationResponse {
public record AccountCreationResponse(
@JsonUnwrapped
private AccountIdentityResponse identityResponse;
@JsonUnwrapped
AccountIdentityResponse identityResponse,
@Schema(description = "If true, there was an existing account registered for this number")
private boolean reregistration;
public AccountCreationResponse() {
}
public AccountCreationResponse(AccountIdentityResponse identityResponse, boolean reregistration) {
this.identityResponse = identityResponse;
this.reregistration = reregistration;
}
public boolean isReregistration() {
return reregistration;
}
@Schema(description = "If true, there was an existing account registered for this number")
boolean reregistration) {
}
@@ -7,41 +7,23 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.google.common.annotations.VisibleForTesting;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.whispersystems.textsecuregcm.util.E164;
// Not a record, because Jackson does not support @JsonUnwrapped with records
// https://github.com/FasterXML/jackson-databind/issues/1497
public final class CreateVerificationSessionRequest {
public record CreateVerificationSessionRequest(
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "The e164-formatted phone number to be verified")
@E164
@NotBlank
@JsonProperty
private String number;
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "The e164-formatted phone number to be verified")
@E164
@NotBlank
@JsonProperty
String number,
@Valid
@JsonUnwrapped
private UpdateVerificationSessionRequest updateVerificationSessionRequest;
public CreateVerificationSessionRequest() {
}
@Valid
@JsonUnwrapped
UpdateVerificationSessionRequest updateVerificationSessionRequest) {
@VisibleForTesting
public CreateVerificationSessionRequest(final String number, final UpdateVerificationSessionRequest updateVerificationSessionRequest) {
this.number = number;
this.updateVerificationSessionRequest = updateVerificationSessionRequest;
}
public String getNumber() {
return number;
}
public UpdateVerificationSessionRequest getUpdateVerificationSessionRequest() {
return updateVerificationSessionRequest;
}
}
@@ -7,7 +7,10 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
public record DeviceInfo(long id,
@@ -17,9 +20,27 @@ public record DeviceInfo(long id,
byte[] name,
long lastSeen,
long created) {
@Deprecated
@Schema(description = """
The time in milliseconds since epoch when the device was linked.
Deprecated in favor of `createdAtCiphertext`.
""", deprecated = true)
long created,
@Schema(description = "The registration ID of the given device.")
int registrationId,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Schema(description = """
The ciphertext of the time in milliseconds since epoch when the device was attached
to the parent account, encoded in standard base64 without padding.
""")
byte[] createdAtCiphertext) {
public static DeviceInfo forDevice(final Device device) {
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getCreated());
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getCreated(), device.getRegistrationId(
IdentityType.ACI), device.getCreatedAtCiphertext());
}
}
@@ -12,6 +12,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.Clock;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nullable;
@@ -40,14 +41,15 @@ public record IncomingMessage(int type,
final boolean story,
final boolean ephemeral,
final boolean urgent,
@Nullable byte[] reportSpamToken) {
@Nullable byte[] reportSpamToken,
final Clock clock) {
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder();
envelopeBuilder
.setType(MessageProtos.Envelope.Type.forNumber(type))
.setClientTimestamp(timestamp)
.setServerTimestamp(System.currentTimeMillis())
.setServerTimestamp(clock.millis())
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
.setStory(story)
.setEphemeral(ephemeral)
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@@ -16,7 +15,6 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
@@ -72,31 +70,9 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@NotNull
@Valid
@JsonUnwrapped
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@JsonProperty
DeviceActivationRequest deviceActivationRequest) implements PhoneVerificationRequest {
@JsonCreator
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public RegistrationRequest(@JsonProperty("sessionId") String sessionId,
@JsonProperty("recoveryPassword") byte[] recoveryPassword,
@JsonProperty("accountAttributes") AccountAttributes accountAttributes,
@JsonProperty("skipDeviceTransfer") boolean skipDeviceTransfer,
@JsonProperty("aciIdentityKey") @NotNull @Valid IdentityKey aciIdentityKey,
@JsonProperty("pniIdentityKey") @NotNull @Valid IdentityKey pniIdentityKey,
@JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey,
@JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
@JsonProperty("pniPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey pniPqLastResortPreKey,
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
// This may seem a little verbose, but at the time of writing, Jackson struggles with `@JsonUnwrapped` members in
// records, and this is a workaround. Please see
// https://github.com/FasterXML/jackson-databind/issues/3726#issuecomment-1525396869 for additional context.
this(sessionId, recoveryPassword, accountAttributes, skipDeviceTransfer, aciIdentityKey, pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnToken, gcmToken));
}
public boolean isEverySignedKeyValid(@Nullable final String userAgent) {
if (deviceActivationRequest().aciSignedPreKey() == null ||
deviceActivationRequest().pniSignedPreKey() == null ||
@@ -0,0 +1,16 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Map;
public record RemoteConfigurationResponse(
@JsonProperty
@Schema(description = "Remote configurations applicable to the user and client")
Map<String, String> config) {
}
@@ -11,86 +11,37 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
// Note, this class cannot be converted into a record because @JsonUnwrapped does not work with records.
// https://github.com/FasterXML/jackson-databind/issues/1467
public class VersionedProfileResponse {
public record VersionedProfileResponse(
@JsonUnwrapped
private BaseProfileResponse baseProfileResponse;
@JsonUnwrapped
BaseProfileResponse baseProfileResponse,
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
private byte[] name;
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
private byte[] about;
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
private byte[] aboutEmoji;
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonProperty
private String avatar;
@JsonProperty
String avatar,
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
private byte[] paymentAddress;
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
private byte[] phoneNumberSharing;
@JsonProperty
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] phoneNumberSharing) {
public VersionedProfileResponse() {
}
public VersionedProfileResponse(final BaseProfileResponse baseProfileResponse,
final byte[] name,
final byte[] about,
final byte[] aboutEmoji,
final String avatar,
final byte[] paymentAddress,
final byte[] phoneNumberSharing) {
this.baseProfileResponse = baseProfileResponse;
this.name = name;
this.about = about;
this.aboutEmoji = aboutEmoji;
this.avatar = avatar;
this.paymentAddress = paymentAddress;
this.phoneNumberSharing = phoneNumberSharing;
}
public BaseProfileResponse getBaseProfileResponse() {
return baseProfileResponse;
}
public byte[] getName() {
return name;
}
public byte[] getAbout() {
return about;
}
public byte[] getAboutEmoji() {
return aboutEmoji;
}
public String getAvatar() {
return avatar;
}
public byte[] getPaymentAddress() {
return paymentAddress;
}
public byte[] getPhoneNumberSharing() {
return phoneNumberSharing;
}
}
@@ -3,7 +3,11 @@ package org.whispersystems.textsecuregcm.experiment;
import javax.annotation.Nullable;
public record DeviceLastSeenState(boolean deviceExists,
long createdAtMillis,
// Registration IDs are not guaranteed to be unique across devices and re-registrations.
// However, for this use case, we accept the possibility of collisions in order to
// avoid storing plaintext device creation timestamps on the server.
// This tradeoff is intentional and aligned with our privacy goals.
int registrationId,
boolean hasPushToken,
long lastSeenMillis,
@Nullable PushTokenType pushTokenType) {
@@ -4,6 +4,7 @@ import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.workers.IdleWakeupEligibilityChecker;
@@ -64,7 +65,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
} else {
pushTokenType = null;
}
return new DeviceLastSeenState(true, device.getCreated(), hasPushToken(device), device.getLastSeen(), pushTokenType);
return new DeviceLastSeenState(true, device.getRegistrationId(IdentityType.ACI), hasPushToken(device), device.getLastSeen(), pushTokenType);
} else {
return DeviceLastSeenState.MISSING_DEVICE_STATE;
}
@@ -116,7 +117,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
assert sample.finalState() != null;
if (!sample.finalState().deviceExists() || sample.initialState().createdAtMillis() != sample.finalState().createdAtMillis()) {
if (!sample.finalState().deviceExists() || sample.initialState().registrationId() != sample.finalState().registrationId()) {
outcome = Outcome.DELETED;
} else if (!sample.finalState().hasPushToken()) {
outcome = Outcome.UNINSTALLED;
@@ -101,7 +101,18 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
public Mono<GetUploadFormResponse> getUploadForm(final GetUploadFormRequest request) {
return authenticateBackupUserMono(request.getSignedPresentation())
.flatMap(backupUser -> switch (request.getUploadTypeCase()) {
case MESSAGES -> Mono.fromFuture(backupManager.createMessageBackupUploadDescriptor(backupUser));
case MESSAGES -> {
final long uploadLength = request.getMessages().getUploadLength();
final boolean oversize = uploadLength > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE;
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
if (oversize) {
yield Mono.error(Status.FAILED_PRECONDITION
.withDescription("Exceeds max upload length")
.asRuntimeException());
}
yield Mono.fromFuture(backupManager.createMessageBackupUploadDescriptor(backupUser));
}
case MEDIA -> Mono.fromCompletionStage(backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
case UPLOADTYPE_NOT_SET -> Mono.error(Status.INVALID_ARGUMENT
.withDescription("Must set upload_type")
@@ -27,6 +27,7 @@ import org.signal.chat.device.SetPushTokenRequest;
import org.signal.chat.device.SetPushTokenResponse;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
@@ -61,6 +62,8 @@ public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
.setId(device.getId())
.setCreated(device.getCreated())
.setLastSeen(device.getLastSeen())
.setRegistrationId(device.getRegistrationId(IdentityType.ACI))
.setCreatedAtCiphertext(ByteString.copyFrom(device.getCreatedAtCiphertext()))
.build());
})
.map(GetDevicesResponse.Builder::build);
@@ -15,7 +15,7 @@ import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.ReactorProfileAnonymousGrpc;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
@@ -25,9 +25,8 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import reactor.core.publisher.Mono;
public class ProfileAnonymousGrpcService extends ReactorProfileAnonymousGrpc.ProfileAnonymousImplBase {
public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.ProfileAnonymousImplBase {
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final ProfileBadgeConverter profileBadgeConverter;
@@ -47,72 +46,68 @@ public class ProfileAnonymousGrpcService extends ReactorProfileAnonymousGrpc.Pro
}
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) throws StatusException {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
throw Status.UNAUTHENTICATED.asRuntimeException();
throw Status.UNAUTHENTICATED.asException();
}
final Mono<Account> account = switch (request.getAuthenticationCase()) {
final Account account = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> {
try {
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
yield Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(targetIdentifier))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()));
} catch (final StatusException e) {
yield Mono.error(e);
}
yield accountsManager.getByServiceIdentifier(targetIdentifier)
.orElseThrow(Status.NOT_FOUND::asException);
}
case UNIDENTIFIED_ACCESS_KEY ->
getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
default -> Mono.error(Status.INVALID_ARGUMENT.asException());
default -> throw Status.INVALID_ARGUMENT.asException();
};
return account.map(targetAccount -> ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
null,
targetAccount,
profileBadgeConverter));
account,
profileBadgeConverter);
}
@Override
public Mono<GetVersionedProfileResponse> getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) throws StatusException {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
return getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray())
.flatMap(targetAccount -> ProfileGrpcHelper.getVersionedProfile(targetAccount, profilesManager, request.getRequest().getVersion()));
final Account targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getVersionedProfile(targetAccount, profilesManager, request.getRequest().getVersion());
}
@Override
public Mono<GetExpiringProfileKeyCredentialResponse> getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) throws StatusException {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
}
return getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray())
.flatMap(account -> ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(account.getUuid(),
request.getRequest().getVersion(), request.getRequest().getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations));
final Account account = getTargetAccountAndValidateUnidentifiedAccess(
targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(account.getUuid(),
request.getRequest().getVersion(), request.getRequest().getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
}
private Mono<Account> getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) {
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(targetIdentifier))
.flatMap(Mono::justOrEmpty)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey))
.switchIfEmpty(Mono.error(Status.UNAUTHENTICATED.asException()));
private Account getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) throws StatusException {
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey))
.orElseThrow(Status.UNAUTHENTICATED::asException);
}
}
@@ -12,6 +12,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import io.grpc.StatusException;
import org.signal.chat.profile.Badge;
import org.signal.chat.profile.BadgeSvg;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
@@ -30,36 +31,31 @@ import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
import reactor.core.publisher.Mono;
public class ProfileGrpcHelper {
static Mono<GetVersionedProfileResponse> getVersionedProfile(final Account account,
static GetVersionedProfileResponse getVersionedProfile(final Account account,
final ProfilesManager profilesManager,
final String requestVersion) {
return Mono.fromFuture(() -> profilesManager.getAsync(account.getUuid(), requestVersion))
.map(maybeProfile -> {
if (maybeProfile.isEmpty()) {
throw Status.NOT_FOUND.withDescription("Profile version not found").asRuntimeException();
}
final String requestVersion) throws StatusException {
final GetVersionedProfileResponse.Builder responseBuilder = GetVersionedProfileResponse.newBuilder();
final VersionedProfile profile = profilesManager.get(account.getUuid(), requestVersion)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
maybeProfile.map(VersionedProfile::name).map(ByteString::copyFrom).ifPresent(responseBuilder::setName);
maybeProfile.map(VersionedProfile::about).map(ByteString::copyFrom).ifPresent(responseBuilder::setAbout);
maybeProfile.map(VersionedProfile::aboutEmoji).map(ByteString::copyFrom).ifPresent(responseBuilder::setAboutEmoji);
maybeProfile.map(VersionedProfile::avatar).ifPresent(responseBuilder::setAvatar);
maybeProfile.map(VersionedProfile::phoneNumberSharing).map(ByteString::copyFrom).ifPresent(responseBuilder::setPhoneNumberSharing);
final GetVersionedProfileResponse.Builder responseBuilder = GetVersionedProfileResponse.newBuilder();
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
maybeProfile
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(requestVersion)).orElse(true))
.map(VersionedProfile::paymentAddress)
.map(ByteString::copyFrom)
.ifPresent(responseBuilder::setPaymentAddress);
responseBuilder
.setName(ByteString.copyFrom(profile.name()))
.setAbout(ByteString.copyFrom(profile.about()))
.setAboutEmoji(ByteString.copyFrom(profile.aboutEmoji()))
.setAvatar(profile.avatar())
.setPhoneNumberSharing(ByteString.copyFrom(profile.phoneNumberSharing()));
return responseBuilder.build();
});
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
if (account.getCurrentProfileVersion().map(v -> v.equals(requestVersion)).orElse(true)) {
responseBuilder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
}
return responseBuilder.build();
}
@VisibleForTesting
@@ -127,27 +123,26 @@ public class ProfileGrpcHelper {
return responseBuilder.build();
}
static Mono<GetExpiringProfileKeyCredentialResponse> getExpiringProfileKeyCredentialResponse(
static GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredentialResponse(
final UUID targetUuid,
final String version,
final byte[] encodedCredentialRequest,
final ProfilesManager profilesManager,
final ServerZkProfileOperations zkProfileOperations) {
return Mono.fromFuture(profilesManager.getAsync(targetUuid, version))
.flatMap(Mono::justOrEmpty)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(encodedCredentialRequest,
profile, new ServiceId.Aci(targetUuid), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw Status.INVALID_ARGUMENT.withCause(e).asRuntimeException();
}
final ServerZkProfileOperations zkProfileOperations) throws StatusException {
return GetExpiringProfileKeyCredentialResponse.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
})
.switchIfEmpty(Mono.error(Status.NOT_FOUND.withDescription("Profile version not found").asException()));
final VersionedProfile profile = profilesManager.get(targetUuid, version)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(encodedCredentialRequest,
profile, new ServiceId.Aci(targetUuid), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw Status.INVALID_ARGUMENT.withCause(e).asException();
}
return GetExpiringProfileKeyCredentialResponse.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
}
}
@@ -9,13 +9,13 @@ import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.grpc.StatusException;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
@@ -24,10 +24,10 @@ import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
import org.signal.chat.profile.ReactorProfileGrpc;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SimpleProfileGrpc;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
@@ -35,6 +35,7 @@ import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -48,10 +49,8 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private final Clock clock;
private final AccountsManager accountsManager;
@@ -93,133 +92,132 @@ public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
}
@Override
public Mono<SetProfileResponse> setProfile(final SetProfileRequest request) {
public SetProfileResponse setProfile(final SetProfileRequest request) throws StatusException {
validateRequest(request);
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> Mono.zip(
Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)),
Mono.fromFuture(() -> profilesManager.getAsync(authenticatedDevice.accountIdentifier(), request.getVersion()))
))
.doOnNext(accountAndMaybeProfile -> {
if (!request.getPaymentAddress().isEmpty()) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> accountAndMaybeProfile.getT1().getNumber().startsWith(prefix));
if (hasDisallowedPrefix && accountAndMaybeProfile.getT2().map(VersionedProfile::paymentAddress).isEmpty()) {
throw Status.PERMISSION_DENIED.asRuntimeException();
}
}
})
.flatMap(accountAndMaybeProfile -> {
final Account account = accountAndMaybeProfile.getT1();
final Optional<String> currentAvatar = accountAndMaybeProfile.getT2().map(VersionedProfile::avatar)
.filter(avatar -> avatar.startsWith("profiles/"));
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
case AVATAR_CHANGE_UPDATE -> {
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
}
};
final Mono<Void> profileSetMono = Mono.fromFuture(() -> profilesManager.setAsync(account.getUuid(),
new VersionedProfile(
request.getVersion(),
request.getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getAboutEmoji().toByteArray(),
request.getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getPhoneNumberSharing().toByteArray(),
request.getCommitment().toByteArray())));
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final List<Mono<?>> updates = new ArrayList<>(2);
final Account account = accountsManager.getByAccountIdentifier(
authenticatedDevice.accountIdentifier()).orElseThrow(Status.UNAUTHENTICATED::asException);
final Optional<VersionedProfile> maybeProfile = profilesManager.get(
authenticatedDevice.accountIdentifier(), request.getVersion());
updates.add(Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> {
if (!request.getPaymentAddress().isEmpty()) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && maybeProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
throw Status.PERMISSION_DENIED.asException();
}
}
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, a.getBadges()))
.orElseGet(a::getBadges);
final Optional<String> currentAvatar = maybeProfile.map(VersionedProfile::avatar)
.filter(avatar -> avatar.startsWith("profiles/"));
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.getVersion());
})));
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
case AVATAR_CHANGE_UPDATE -> {
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
}
};
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
updates.add(Mono.fromFuture(() -> profilesManager.deleteAvatar(avatarData.currentAvatar.get())));
}
return profileSetMono.thenMany(Flux.merge(updates)).then(Mono.just(avatarData));
})
.map(avatarData -> avatarData.uploadAttributes()
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
.orElse(SetProfileResponse.newBuilder().build())
);
profilesManager.set(account.getUuid(),
new VersionedProfile(
request.getVersion(),
request.getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getAboutEmoji().toByteArray(),
request.getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getPhoneNumberSharing().toByteArray(),
request.getCommitment().toByteArray()));
accountsManager.update(account, a -> {
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
a.getBadges()))
.orElseGet(a::getBadges);
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.getVersion());
});
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
profilesManager.deleteAvatar(avatarData.currentAvatar().get());
}
return avatarData.uploadAttributes()
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
.orElse(SetProfileResponse.newBuilder().build());
}
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileRequest request) {
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws StatusException, RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
return validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier)
.map(targetAccount -> ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
authenticatedDevice.accountIdentifier(),
targetAccount,
profileBadgeConverter));
profileBadgeConverter);
}
@Override
public Mono<GetVersionedProfileResponse> getVersionedProfile(final GetVersionedProfileRequest request) {
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws StatusException, RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
return validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier)
.flatMap(account -> ProfileGrpcHelper.getVersionedProfile(account, profilesManager, request.getVersion()));
final Account account = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getVersionedProfile(account, profilesManager, request.getVersion());
}
@Override
public Mono<GetExpiringProfileKeyCredentialResponse> getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialRequest request) {
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialRequest request) throws StatusException, RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
}
return validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier)
.flatMap(targetAccount -> ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(targetAccount.getUuid(),
request.getVersion(), request.getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations));
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(targetAccount.getUuid(),
request.getVersion(), request.getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
}
private Mono<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) {
return rateLimiters.getProfileLimiter().validateReactive(requesterUuid)
.then(Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(targetIdentifier))
.flatMap(Mono::justOrEmpty))
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()));
private Account validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException, StatusException {
rateLimiters.getProfileLimiter().validate(requesterUuid);
return accountsManager.getByServiceIdentifier(targetIdentifier).orElseThrow(Status.NOT_FOUND::asException);
}
private void validateRequest(final SetProfileRequest request) {
private void validateRequest(final SetProfileRequest request) throws StatusException {
if (request.getVersion().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asException();
}
if (request.getCommitment().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asException();
}
checkByteStringLength(request.getName(), "Invalid name length", List.of(81, 285));
@@ -228,7 +226,9 @@ public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
checkByteStringLength(request.getPaymentAddress(), "Invalid mobile coin address length", List.of(0, 582));
}
private static void checkByteStringLength(final ByteString byteString, final String errorMessage, final List<Integer> allowedLengths) {
private static void checkByteStringLength(final ByteString byteString, final String errorMessage,
final List<Integer> allowedLengths) throws StatusException {
final int byteStringLength = byteString.toByteArray().length;
for (int allowedLength : allowedLengths) {
@@ -237,7 +237,7 @@ public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
}
}
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asRuntimeException();
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asException();
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
@@ -8,17 +8,21 @@ package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import java.util.Optional;
public class BackupMetrics {
private final static String COPY_MEDIA_COUNTER_NAME = name(BackupMetrics.class, "copyMedia");
private final static String GET_BACKUP_CREDENTIALS_NAME = name(BackupMetrics.class, "getBackupCredentials");
private final static String MESSAGE_BACKUP_SIZE_NAME = name(BackupMetrics.class, "messageBackupSize");
private MeterRegistry registry;
@@ -48,4 +52,19 @@ public class BackupMetrics {
.increment();
}
public void updateMessageBackupSizeDistribution(
AuthenticatedBackupUser authenticatedBackupUser,
final boolean oversize,
final Optional<Long> backupLength) {
DistributionSummary.builder(MESSAGE_BACKUP_SIZE_NAME)
.publishPercentileHistogram(true)
.tags(Tags.of(
UserAgentTagUtil.getPlatformTag(authenticatedBackupUser.userAgent()),
Tag.of("tier", authenticatedBackupUser.backupLevel().name().toLowerCase()),
Tag.of("oversize", Boolean.toString(oversize)),
Tag.of("hasBackupLength", Boolean.toString(backupLength.isPresent()))))
.register(Metrics.globalRegistry)
.record(backupLength.orElse(0L));
}
}
@@ -18,26 +18,35 @@ public class OpenWebSocketCounter {
private static final String WEBSOCKET_CLOSED_COUNTER_NAME = name(OpenWebSocketCounter.class, "websocketClosed");
private final String newConnectionCounterName;
private final String durationTimerName;
private final Tags tags;
private final Map<ClientPlatform, AtomicInteger> openWebsocketsByClientPlatform;
private final AtomicInteger openWebsocketsFromUnknownPlatforms;
private final Map<ClientPlatform, Timer> durationTimersByClientPlatform;
private final Timer durationTimerForUnknownPlatforms;
public OpenWebSocketCounter(final String openWebSocketGaugeName,
final String newConnectionCounterName,
final String durationTimerName) {
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName) {
this(openWebSocketGaugeName, durationTimerName, Tags.empty());
this(openWebSocketGaugeName, newConnectionCounterName, durationTimerName, Tags.empty());
}
public OpenWebSocketCounter(final String openWebSocketGaugeName, final String durationTimerName, final Tags tags) {
public OpenWebSocketCounter(final String openWebSocketGaugeName,
final String newConnectionCounterName,
final String durationTimerName,
final Tags tags) {
this.newConnectionCounterName = newConnectionCounterName;
this.durationTimerName = durationTimerName;
this.tags = tags;
openWebsocketsByClientPlatform = EnumMapUtil.toEnumMap(ClientPlatform.class,
clientPlatform -> buildGauge(openWebSocketGaugeName, clientPlatform.name().toLowerCase(), tags));
openWebsocketsFromUnknownPlatforms = buildGauge(openWebSocketGaugeName, "unknown", tags);
durationTimersByClientPlatform = EnumMapUtil.toEnumMap(ClientPlatform.class,
clientPlatform -> buildTimer(durationTimerName, clientPlatform.name().toLowerCase(), tags));
durationTimerForUnknownPlatforms = buildTimer(durationTimerName, "unknown", tags);
}
private static AtomicInteger buildGauge(final String gaugeName, final String clientPlatformName, final Tags tags) {
@@ -46,47 +55,43 @@ public class OpenWebSocketCounter {
new AtomicInteger(0));
}
private static Timer buildTimer(final String timerName, final String clientPlatformName, final Tags tags) {
return Timer.builder(timerName)
.publishPercentileHistogram(true)
.tags(tags.and(Tag.of(UserAgentTagUtil.PLATFORM_TAG, clientPlatformName)))
.register(Metrics.globalRegistry);
}
public void countOpenWebSocket(final WebSocketSessionContext context) {
final Timer.Sample sample = Timer.start();
// We have to jump through some hoops here to have something "effectively final" for the close listener, but
// assignable from a `catch` block.
final AtomicInteger openWebSocketCounter;
final Timer durationTimer;
{
AtomicInteger calculatedOpenWebSocketCounter;
Timer calculatedDurationTimer;
try {
final ClientPlatform clientPlatform =
UserAgentUtil.parseUserAgentString(context.getClient().getUserAgent()).platform();
calculatedOpenWebSocketCounter = openWebsocketsByClientPlatform.get(clientPlatform);
calculatedDurationTimer = durationTimersByClientPlatform.get(clientPlatform);
} catch (final UnrecognizedUserAgentException e) {
calculatedOpenWebSocketCounter = openWebsocketsFromUnknownPlatforms;
calculatedDurationTimer = durationTimerForUnknownPlatforms;
}
openWebSocketCounter = calculatedOpenWebSocketCounter;
durationTimer = calculatedDurationTimer;
}
openWebSocketCounter.incrementAndGet();
final Tags tagsWithClientPlatform = tags.and(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent()));
Metrics.counter(newConnectionCounterName, tagsWithClientPlatform).increment();
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
sample.stop(durationTimer);
sample.stop(Timer.builder(durationTimerName)
.publishPercentileHistogram(true)
.tags(tagsWithClientPlatform)
.register(Metrics.globalRegistry));
openWebSocketCounter.decrementAndGet();
Metrics.counter(WEBSOCKET_CLOSED_COUNTER_NAME, "status", String.valueOf(statusCode))
Metrics.counter(WEBSOCKET_CLOSED_COUNTER_NAME, tagsWithClientPlatform.and("status", String.valueOf(statusCode)))
.increment();
});
}
@@ -28,7 +28,6 @@ import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
@@ -53,7 +52,6 @@ public class MessageSender {
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
// Note that these names deliberately reference `MessageController` for metric continuity
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageController.class, "rejectOversizeMessage");
@@ -75,13 +73,9 @@ public class MessageSender {
@VisibleForTesting
static final byte NO_EXCLUDED_DEVICE_ID = -1;
public MessageSender(
final MessagesManager messagesManager,
final PushNotificationManager pushNotificationManager,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
public MessageSender(final MessagesManager messagesManager, final PushNotificationManager pushNotificationManager) {
this.messagesManager = messagesManager;
this.pushNotificationManager = pushNotificationManager;
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
/**
@@ -109,44 +103,14 @@ public class MessageSender {
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Byte> syncMessageSenderDeviceId,
@Nullable final String userAgent) throws MismatchedDevicesException, MessageTooLargeException {
if (!destination.isIdentifiedBy(destinationIdentifier)) {
throw new IllegalArgumentException("Destination account not identified by destination service identifier");
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
if (messagesByDeviceId.isEmpty()) {
Metrics.counter(EMPTY_MESSAGE_LIST_COUNTER_NAME,
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(syncMessageSenderDeviceId.isPresent())).and(platformTag)).increment();
}
final byte excludedDeviceId;
if (syncMessageSenderDeviceId.isPresent()) {
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isBlank(message.getSourceServiceId()) ||
!destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
throw new IllegalArgumentException("Sync message sender device ID specified, but one or more messages are not addressed to sender");
}
excludedDeviceId = syncMessageSenderDeviceId.get();
} else {
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isNotBlank(message.getSourceServiceId()) &&
destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
throw new IllegalArgumentException("Sync message sender device ID not specified, but one or more messages are addressed to sender");
}
excludedDeviceId = NO_EXCLUDED_DEVICE_ID;
}
final Optional<MismatchedDevices> maybeMismatchedDevices = getMismatchedDevices(destination,
validateIndividualMessageBundle(destination,
destinationIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
excludedDeviceId);
if (maybeMismatchedDevices.isPresent()) {
throw new MismatchedDevicesException(maybeMismatchedDevices.get());
}
validateIndividualMessageContentLength(messagesByDeviceId.values(), syncMessageSenderDeviceId.isPresent(), userAgent);
syncMessageSenderDeviceId,
platformTag);
messagesManager.insert(destination.getIdentifier(IdentityType.ACI), messagesByDeviceId)
.forEach((deviceId, destinationPresent) -> {
@@ -206,7 +170,9 @@ public class MessageSender {
final boolean isUrgent,
@Nullable final String userAgent) throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
validateMultiRecipientMessageContentLength(multiRecipientMessage, isStory, userAgent);
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
validateMultiRecipientMessageContentLength(multiRecipientMessage, isStory, platformTag);
final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier = new HashMap<>();
@@ -252,24 +218,105 @@ public class MessageSender {
SEALED_SENDER_TAG_NAME, "true",
SYNC_MESSAGE_TAG_NAME, "false",
MULTI_RECIPIENT_TAG_NAME, "true")
.and(UserAgentTagUtil.getPlatformTag(userAgent));
.and(platformTag);
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
})))
.thenRun(Util.NOOP);
}
/**
* Validates that a bundle of messages destined for an individual account is well-formed and may be delivered. Note
* that all checks performed by this method are also performed by
* {@link #sendMessages(Account, ServiceIdentifier, Map, Map, Optional, String)}; callers should only invoke this
* method if they need to verify that a bundle of individual messages is valid <em>before</em> trying to send the
* messages (i.e. if the caller must take some other action in conjunction with sending the messages and cannot
* reverse that action if message sending fails).
*
* @param destination the account to which to send messages
* @param destinationIdentifier the service identifier to which the messages are addressed
* @param messagesByDeviceId a map of device IDs to message payloads
* @param registrationIdsByDeviceId a map of device IDs to device registration IDs
* @param syncMessageSenderDeviceId if the message is a sync message (i.e. a message to other devices linked to the
* caller's own account), contains the ID of the device that sent the message
* @param userAgent the User-Agent string for the sender; may be {@code null} if not known
*
* @throws MismatchedDevicesException if the given bundle of messages did not include a message for all required
* devices, contained messages for devices not linked to the destination account, or devices with outdated
* registration IDs
* @throws MessageTooLargeException if the given message payload is too large
*/
public static void validateIndividualMessageBundle(final Account destination,
final ServiceIdentifier destinationIdentifier,
final Map<Byte, Envelope> messagesByDeviceId,
final Map<Byte, Integer> registrationIdsByDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Byte> syncMessageSenderDeviceId,
@Nullable final String userAgent) throws MessageTooLargeException, MismatchedDevicesException {
validateIndividualMessageBundle(destination,
destinationIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
syncMessageSenderDeviceId,
UserAgentTagUtil.getPlatformTag(userAgent));
}
private static void validateIndividualMessageBundle(final Account destination,
final ServiceIdentifier destinationIdentifier,
final Map<Byte, Envelope> messagesByDeviceId,
final Map<Byte, Integer> registrationIdsByDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Byte> syncMessageSenderDeviceId,
final Tag platformTag) throws MismatchedDevicesException, MessageTooLargeException {
if (!destination.isIdentifiedBy(destinationIdentifier)) {
throw new IllegalArgumentException("Destination account not identified by destination service identifier");
}
if (messagesByDeviceId.isEmpty()) {
Metrics.counter(EMPTY_MESSAGE_LIST_COUNTER_NAME,
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(syncMessageSenderDeviceId.isPresent())).and(platformTag)).increment();
}
final byte excludedDeviceId;
if (syncMessageSenderDeviceId.isPresent()) {
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isBlank(message.getSourceServiceId()) ||
!destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
throw new IllegalArgumentException("Sync message sender device ID specified, but one or more messages are not addressed to sender");
}
excludedDeviceId = syncMessageSenderDeviceId.get();
} else {
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isNotBlank(message.getSourceServiceId()) &&
destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
throw new IllegalArgumentException("Sync message sender device ID not specified, but one or more messages are addressed to sender");
}
excludedDeviceId = NO_EXCLUDED_DEVICE_ID;
}
final Optional<MismatchedDevices> maybeMismatchedDevices = getMismatchedDevices(destination,
destinationIdentifier,
registrationIdsByDeviceId,
excludedDeviceId);
if (maybeMismatchedDevices.isPresent()) {
throw new MismatchedDevicesException(maybeMismatchedDevices.get());
}
validateIndividualMessageContentLength(messagesByDeviceId.values(), syncMessageSenderDeviceId.isPresent(), platformTag);
}
@VisibleForTesting
static void validateContentLength(final int contentLength,
final boolean isMultiRecipientMessage,
final boolean isSyncMessage,
final boolean isStory,
final String userAgent) throws MessageTooLargeException {
final Tag platformTag) throws MessageTooLargeException {
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
.tags(Tags.of(platformTag,
Tag.of("oversize", String.valueOf(oversize)),
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
@@ -279,7 +326,7 @@ public class MessageSender {
.record(contentLength);
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(platformTag,
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
@@ -330,27 +377,27 @@ public class MessageSender {
private static void validateIndividualMessageContentLength(final Iterable<Envelope> messages,
final boolean isSyncMessage,
@Nullable final String userAgent) throws MessageTooLargeException {
final Tag platformTag) throws MessageTooLargeException {
for (final Envelope message : messages) {
MessageSender.validateContentLength(message.getContent().size(),
false,
isSyncMessage,
message.getStory(),
userAgent);
platformTag);
}
}
private static void validateMultiRecipientMessageContentLength(final SealedSenderMultiRecipientMessage multiRecipientMessage,
final boolean isStory,
@Nullable final String userAgent) throws MessageTooLargeException {
final Tag platformTag) throws MessageTooLargeException {
for (final SealedSenderMultiRecipientMessage.Recipient recipient : multiRecipientMessage.getRecipients().values()) {
MessageSender.validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient),
true,
false,
isStory,
userAgent);
platformTag);
}
}
}
@@ -15,10 +15,14 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
@@ -28,21 +32,26 @@ import org.whispersystems.textsecuregcm.util.HttpUtils;
/**
* A client for sending requests to Signal's secure value recovery v2 service on behalf of authenticated users.
*/
public class SecureValueRecovery2Client {
public class SecureValueRecoveryClient {
private static final Logger logger = LoggerFactory.getLogger(SecureValueRecoveryClient.class);
private final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator;
private final URI deleteUri;
private final Supplier<List<Integer>> allowedDeletionErrorStatusCodes;
private final FaultTolerantHttpClient httpClient;
@VisibleForTesting
static final String DELETE_PATH = "/v1/delete";
public SecureValueRecovery2Client(final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator,
public SecureValueRecoveryClient(
final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator,
final Executor executor, final ScheduledExecutorService retryExecutor,
final SecureValueRecoveryConfiguration configuration)
final SecureValueRecoveryConfiguration configuration,
Supplier<List<Integer>> allowedDeletionErrorStatusCodes)
throws CertificateException {
this.secureValueRecoveryCredentialsGenerator = secureValueRecoveryCredentialsGenerator;
this.deleteUri = URI.create(configuration.uri()).resolve(DELETE_PATH);
this.allowedDeletionErrorStatusCodes = allowedDeletionErrorStatusCodes;
this.httpClient = FaultTolerantHttpClient.newBuilder()
.withCircuitBreaker(configuration.circuitBreaker())
.withRetry(configuration.retry())
@@ -57,7 +66,7 @@ public class SecureValueRecovery2Client {
.build();
}
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) {
public CompletableFuture<Void> removeData(final UUID accountUuid) {
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid);
@@ -72,6 +81,13 @@ public class SecureValueRecovery2Client {
return null;
}
final List<Integer> allowedErrors = allowedDeletionErrorStatusCodes.get();
if (allowedErrors.contains(response.statusCode())) {
logger.warn("Ignoring failure to delete svr entry for account {} with status {}",
accountUuid, response.statusCode());
return null;
}
logger.warn("Failed to delete svr entry for account {} with status {}", accountUuid, response.statusCode());
throw new SecureValueRecoveryException("Failed to delete backup", String.valueOf(response.statusCode()));
});
}
@@ -8,6 +8,7 @@ import com.amazonaws.services.dynamodbv2.ReleaseLockOptions;
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
@@ -55,7 +56,7 @@ public class AccountLockManager {
*
* @throws Exception if an exception is thrown by the given {@code task}
*/
public <V> V withLock(final List<UUID> phoneNumberIdentifiers,
public <V> V withLock(final Set<UUID> phoneNumberIdentifiers,
final Callable<V> task,
final Executor lockAcquisitionExecutor) throws Exception {
@@ -106,7 +107,7 @@ public class AccountLockManager {
* @return a future that completes normally when the given task has executed successfully and all locks have been
* released; the returned future may fail with an {@link InterruptedException} if interrupted while acquiring a lock
*/
public <T> CompletableFuture<T> withLockAsync(final List<UUID> phoneNumberIdentifiers,
public <T> CompletableFuture<T> withLockAsync(final Set<UUID> phoneNumberIdentifiers,
final Supplier<CompletableFuture<T>> taskSupplier, final Executor executor) {
if (phoneNumberIdentifiers.isEmpty()) {
@@ -11,7 +11,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.io.IOException;
@@ -424,11 +423,14 @@ public class Accounts {
final AttributeValue numberAttr = AttributeValues.fromString(number);
final AttributeValue pniAttr = AttributeValues.fromUUID(phoneNumberIdentifier);
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, originalNumber));
writeItems.add(buildConstraintTablePut(phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr));
writeItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, originalPni));
writeItems.add(buildConstraintTablePut(phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniAttr));
writeItems.add(buildRemoveDeletedAccount(phoneNumberIdentifier));
if (!originalNumber.equals(number)) {
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, originalNumber));
writeItems.add(buildConstraintTablePut(phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr));
writeItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, originalPni));
writeItems.add(buildConstraintTablePut(phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniAttr));
writeItems.add(buildRemoveDeletedAccount(phoneNumberIdentifier));
}
maybeDisplacedAccountIdentifier.ifPresent(displacedAccountIdentifier ->
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalPni)));
@@ -45,7 +45,6 @@ import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
@@ -53,7 +52,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -84,8 +82,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -126,8 +123,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final MessagesManager messagesManager;
private final ProfilesManager profilesManager;
private final SecureStorageClient secureStorageClient;
private final SecureValueRecovery2Client secureValueRecovery2Client;
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final SecureValueRecoveryClient secureValueRecoveryBClient;
private final DisconnectionRequestManager disconnectionRequestManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final ClientPublicKeysManager clientPublicKeysManager;
@@ -209,7 +206,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final MessagesManager messagesManager,
final ProfilesManager profilesManager,
final SecureStorageClient secureStorageClient,
final SecureValueRecovery2Client secureValueRecovery2Client,
final SecureValueRecoveryClient secureValueRecovery2Client,
final SecureValueRecoveryClient secureValueRecoveryBClient,
final DisconnectionRequestManager disconnectionRequestManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final ClientPublicKeysManager clientPublicKeysManager,
@@ -228,6 +226,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.profilesManager = profilesManager;
this.secureStorageClient = secureStorageClient;
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
this.disconnectionRequestManager = disconnectionRequestManager;
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
this.clientPublicKeysManager = clientPublicKeysManager;
@@ -277,7 +276,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return createTimer.record(() -> {
try {
return accountLockManager.withLock(List.of(pni),
return accountLockManager.withLock(Set.of(pni),
() -> create(number, pni, accountAttributes, accountBadges, aciIdentityKey, pniIdentityKey, primaryDeviceSpec, userAgent), accountLockExecutor);
} catch (final Exception e) {
if (e instanceof RuntimeException runtimeException) {
@@ -309,7 +308,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
account.setNumber(number, pni);
account.setIdentityKey(aciIdentityKey);
account.setPhoneNumberIdentityKey(pniIdentityKey);
account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock));
account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock, aciIdentityKey));
account.setRegistrationLockFromAttributes(accountAttributes);
account.setUnidentifiedAccessKey(accountAttributes.getUnidentifiedAccessKey());
account.setUnrestrictedUnidentifiedAccess(accountAttributes.isUnrestrictedUnidentifiedAccess());
@@ -374,7 +373,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
keysManager.deleteSingleUsePreKeys(aci),
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci))
profilesManager.deleteAll(aci, false))
.thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(aci))
.thenCompose(ignored -> accounts.reclaimAccount(e.getExistingAccount(), account, additionalWriteItems))
.thenCompose(ignored -> {
@@ -388,7 +387,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci),
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci));
profilesManager.deleteAll(aci, false));
})
.join();
}
@@ -416,7 +415,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public CompletableFuture<Pair<Account, Device>> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken) {
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -437,7 +436,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account account = accountAndNextDeviceId.first();
final byte nextDeviceId = accountAndNextDeviceId.second();
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock));
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getIdentityKey(IdentityType.ACI)));
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(
account.getIdentifier(IdentityType.ACI),
@@ -610,7 +609,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -663,15 +662,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
final Map<Byte, Integer> pniRegistrationIds) throws InterruptedException, MismatchedDevicesException {
final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifier();
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
if (originalPhoneNumberIdentifier.equals(targetPhoneNumberIdentifier)) {
return account;
}
try {
return accountLockManager.withLock(List.of(account.getPhoneNumberIdentifier(), targetPhoneNumberIdentifier),
return accountLockManager.withLock(new HashSet<>(List.of(account.getPhoneNumberIdentifier(), targetPhoneNumberIdentifier)),
() -> changeNumber(account, targetNumber, targetPhoneNumberIdentifier, pniIdentityKey, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds), accountLockExecutor);
} catch (final Exception e) {
if (e instanceof MismatchedDevicesException mismatchedDevicesException) {
@@ -699,24 +693,30 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisDelete(account);
// There are three possible states for accounts associated with the target phone number:
// There are four possible states for accounts associated with the target phone number:
//
// 1. An account exists with the target PNI; the caller has proved ownership of the number, so delete the
// 1. The authenticated account already has the given phone number. We don't want to delete the account, but do want
// to update keys.
// 2. An account exists with the target PNI; the caller has proved ownership of the number, so delete the
// account with the target PNI. This will leave a "deleted account" record for the deleted account mapping
// the UUID of the deleted account to the target PNI. We'll then overwrite that so it points to the
// original PNI to facilitate switching back and forth between numbers.
// 2. No account with the target PNI exists, but one has recently been deleted. In that case, add a "deleted
// 3. No account with the target PNI exists, but one has recently been deleted. In that case, add a "deleted
// account" record that maps the ACI of the recently-deleted account to the now-abandoned original PNI
// of the account changing its number (which facilitates ACI consistency in cases that a party is switching
// back and forth between numbers).
// 3. No account with the target PNI exists at all, in which case no additional action is needed.
// 4. No account with the target PNI exists at all, in which case no additional action is needed.
final Optional<UUID> recentlyDeletedAci = accounts.findRecentlyDeletedAccountIdentifier(targetPhoneNumberIdentifier);
final Optional<Account> maybeExistingAccount = getByE164(targetNumber);
final Optional<UUID> maybeDisplacedUuid;
if (maybeExistingAccount.isPresent()) {
delete(maybeExistingAccount.get()).join();
maybeDisplacedUuid = maybeExistingAccount.map(Account::getUuid);
if (maybeExistingAccount.get().getIdentifier(IdentityType.ACI).equals(account.getIdentifier(IdentityType.ACI))) {
maybeDisplacedUuid = Optional.empty();
} else {
delete(maybeExistingAccount.get()).join();
maybeDisplacedUuid = maybeExistingAccount.map(Account::getUuid);
}
} else {
maybeDisplacedUuid = recentlyDeletedAci;
}
@@ -742,45 +742,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
AccountChangeValidator.NUMBER_CHANGE_VALIDATOR);
}
public Account updatePniKeys(final Account account,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> pniSignedPreKeys,
final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
final Map<Byte, Integer> pniRegistrationIds) throws MismatchedDevicesException {
try {
return accountLockManager.withLock(List.of(account.getIdentifier(IdentityType.PNI)), () -> {
validateDevices(account, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds);
final UUID aci = account.getIdentifier(IdentityType.ACI);
final UUID pni = account.getIdentifier(IdentityType.PNI);
final Collection<TransactWriteItem> keyWriteItems =
buildPniKeyWriteItems(pni, pniSignedPreKeys, pniPqLastResortPreKeys);
return redisDeleteAsync(account)
.thenCompose(ignored -> keysManager.deleteSingleUsePreKeys(pni))
.thenCompose(ignored -> updateTransactionallyWithRetriesAsync(account,
a -> setPniKeys(a, pniIdentityKey, pniRegistrationIds),
accounts::updateTransactionallyAsync,
() -> accounts.getByAccountIdentifierAsync(aci).thenApply(Optional::orElseThrow),
a -> keyWriteItems,
AccountChangeValidator.GENERAL_CHANGE_VALIDATOR,
MAX_UPDATE_ATTEMPTS))
.join();
}, accountLockExecutor);
} catch (final Exception e) {
if (e instanceof MismatchedDevicesException mismatchedDevicesException) {
throw mismatchedDevicesException;
} else if (e instanceof RuntimeException runtimeException) {
throw runtimeException;
}
logger.error("Unexpected exception when updating PNI key material", e);
throw new RuntimeException(e);
}
}
private Collection<TransactWriteItem> buildPniKeyWriteItems(
final UUID phoneNumberIdentifier,
final Map<Byte, ECSignedPreKey> pniSignedPreKeys,
@@ -1119,42 +1080,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return CompletableFuture.failedFuture(new OptimisticLockRetryLimitExceededException());
}
private CompletionStage<Account> updateTransactionallyWithRetriesAsync(final Account account,
final Consumer<Account> updater,
final BiFunction<Account, Collection<TransactWriteItem>, CompletionStage<Void>> persister,
final Supplier<CompletionStage<Account>> retriever,
final Function<Account, Collection<TransactWriteItem>> additionalWriteItemProvider,
final AccountChangeValidator changeValidator,
final int remainingTries) {
final Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
final Collection<TransactWriteItem> additionalWriteItems = additionalWriteItemProvider.apply(account);
updater.accept(account);
if (remainingTries > 0) {
return persister.apply(account, additionalWriteItems)
.thenApply(ignored -> {
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
account.markStale();
changeValidator.validateChange(originalAccount, updatedAccount);
return updatedAccount;
})
.exceptionallyCompose(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException) {
return retriever.get().thenCompose(refreshedAccount ->
updateTransactionallyWithRetriesAsync(refreshedAccount, updater, persister, retriever, additionalWriteItemProvider, changeValidator, remainingTries - 1));
} else {
throw ExceptionUtils.wrap(throwable);
}
});
}
return CompletableFuture.failedFuture(new OptimisticLockRetryLimitExceededException());
}
public Account updateDevice(Account account, byte deviceId, Consumer<Device> deviceUpdater) {
return update(account, a -> {
a.getDevice(deviceId).ifPresent(deviceUpdater);
@@ -1263,7 +1188,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public CompletableFuture<Void> delete(final Account account, final DeletionReason deletionReason) {
final Timer.Sample sample = Timer.start();
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()), () -> delete(account),
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()), () -> delete(account),
accountLockExecutor)
.whenComplete((ignored, throwable) -> {
sample.stop(deleteTimer);
@@ -1292,24 +1217,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
account.getIdentifier(IdentityType.ACI),
device.getId())))
.toList();
final CompletableFuture<Void> svr2DeleteBackupFuture = secureValueRecovery2Client.deleteBackups(account.getUuid())
.exceptionally(ExceptionUtils.exceptionallyHandler(SecureValueRecoveryException.class, exception -> {
final List<String> svrStatusCodesToIgnore = dynamicConfigurationManager.getConfiguration().getSvrStatusCodesToIgnoreForAccountDeletion();
if (svrStatusCodesToIgnore.contains(exception.getStatusCode())) {
logger.warn("Ignoring failure to delete svr2 backup for account: " + account.getUuid(), exception);
return null;
}
logger.warn("Failed to delete svr2 backup for account: " + account.getUuid(), exception);
throw new CompletionException(exception);
}));
return CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
svr2DeleteBackupFuture,
secureValueRecovery2Client.removeData(account.getUuid()),
secureValueRecoveryBClient.removeData(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
messagesManager.clear(account.getUuid()),
profilesManager.deleteAll(account.getUuid()),
profilesManager.deleteAll(account.getUuid(), true),
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
.thenCompose(ignored -> redisDeleteAsync(account))
@@ -4,14 +4,11 @@
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ObjectUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -21,7 +18,7 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
@@ -52,86 +49,57 @@ public class ChangeNumberManager {
final String senderUserAgent)
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException {
if (!(ObjectUtils.allNotNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds) ||
ObjectUtils.allNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds))) {
throw new IllegalArgumentException("PNI identity key, signed pre-keys, device messages, and registration IDs must be all null or all non-null");
}
final long serverTimestamp = clock.millis();
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI));
if (number.equals(account.getNumber())) {
// The client has gotten confused/desynchronized with us about their own phone number, most likely due to losing
// our OK response to an immediately preceding change-number request, and are sending a change they don't realize
// is a no-op change.
//
// We don't need to actually do a number-change operation in our DB, but we *do* need to accept their new key
// material and distribute the sync messages, to be sure all clients agree with us and each other about what their
// keys are. Pretend this change-number request was actually a PNI key distribution request.
if (pniIdentityKey == null) {
return account;
}
return updatePniKeys(account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, deviceMessages, pniRegistrationIds, senderUserAgent);
// Note that these for-validation envelopes do NOT have the "updated PNI" field set, and we'll need to populate that
// after actually changing the account's number.
final Map<Byte, Envelope> messagesByDeviceId = deviceMessages.stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> message.toEnvelope(serviceIdentifier,
serviceIdentifier,
Device.PRIMARY_ID,
serverTimestamp,
false,
false,
true,
null,
clock)));
final Map<Byte, Integer> registrationIdsByDeviceId = deviceMessages.stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, IncomingMessage::destinationRegistrationId));
// Make sure we can plausibly deliver the messages to other devices on the account before making any changes to the
// account itself
if (!messagesByDeviceId.isEmpty()) {
MessageSender.validateIndividualMessageBundle(account,
serviceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
senderUserAgent);
}
final Account updatedAccount = accountsManager.changeNumber(
account, number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
if (deviceMessages != null) {
sendDeviceMessages(updatedAccount, deviceMessages, senderUserAgent);
}
return updatedAccount;
}
public Account updatePniKeys(final Account account,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
final List<IncomingMessage> deviceMessages,
final Map<Byte, Integer> pniRegistrationIds,
final String senderUserAgent) throws MismatchedDevicesException, MessageTooLargeException {
// Don't try to be smart about ignoring unnecessary retries. If we make literally no change we will skip the ddb
// write anyway. Linked devices can handle some wasted extra key rotations.
final Account updatedAccount = accountsManager.updatePniKeys(
account, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
sendDeviceMessages(updatedAccount, deviceMessages, senderUserAgent);
return updatedAccount;
}
private void sendDeviceMessages(final Account account,
final List<IncomingMessage> deviceMessages,
final String senderUserAgent) throws MessageTooLargeException, MismatchedDevicesException {
try {
final long serverTimestamp = clock.millis();
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getUuid());
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
final String updatedPniString = updatedAccount.getIdentifier(IdentityType.PNI).toString();
final Map<Byte, Envelope> messagesByDeviceId = deviceMessages.stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setClientTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
.setContent(ByteString.copyFrom(message.content()))
.setSourceServiceId(serviceIdentifier.toServiceIdentifierString())
.setSourceDevice(Device.PRIMARY_ID)
.setUpdatedPni(account.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.setEphemeral(false)
.build()));
messagesByDeviceId.replaceAll((deviceId, envelope) ->
envelope.toBuilder().setUpdatedPni(updatedPniString).build());
final Map<Byte, Integer> registrationIdsByDeviceId = deviceMessages.stream()
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, IncomingMessage::destinationRegistrationId));
messageSender.sendMessages(account,
messageSender.sendMessages(updatedAccount,
serviceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
senderUserAgent);
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
logger.warn("Changed number but could not send all device messages for {}", account.getIdentifier(IdentityType.ACI), e);
throw e;
}
return updatedAccount;
}
}
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.storage;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@@ -41,7 +42,7 @@ public class ClientPublicKeysManager {
* @return a future that completes when the given key has been stored
*/
public CompletableFuture<Void> setPublicKey(final Account account, final byte deviceId, final ECPublicKey publicKey) {
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
() -> clientPublicKeys.setPublicKey(account.getIdentifier(IdentityType.ACI), deviceId, publicKey),
accountLockExecutor);
}
@@ -13,7 +13,6 @@ import java.time.Duration;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.OptionalInt;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -21,6 +20,7 @@ import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.DeviceNameByteArrayAdapter;
@@ -44,6 +44,11 @@ public class Device {
@JsonDeserialize(using = DeviceNameByteArrayAdapter.Deserializer.class)
private byte[] name;
@JsonProperty("createdAt")
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
private byte[] createdAtCiphertext;
@JsonProperty
private String authToken;
@@ -110,6 +115,14 @@ public class Device {
return this.created;
}
public void setCreatedAtCiphertext(byte[] createdAtCiphertext) {
this.createdAtCiphertext = createdAtCiphertext;
}
public byte[] getCreatedAtCiphertext() {
return this.createdAtCiphertext;
}
public String getGcmId() {
return gcmId;
}
@@ -5,11 +5,13 @@ import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
import org.whispersystems.textsecuregcm.util.Util;
public record DeviceSpec(
@@ -27,7 +29,9 @@ public record DeviceSpec(
KEMSignedPreKey aciPqLastResortPreKey,
KEMSignedPreKey pniPqLastResortPreKey) {
public Device toDevice(final byte deviceId, final Clock clock) {
public Device toDevice(final byte deviceId, final Clock clock, final IdentityKey aciIdentityKey) {
final long created = clock.millis();
final Device device = new Device();
device.setId(deviceId);
device.setAuthTokenHash(SaltedTokenHash.generateFor(password()));
@@ -36,7 +40,9 @@ public record DeviceSpec(
device.setPhoneNumberIdentityRegistrationId(pniRegistrationId());
device.setName(deviceNameCiphertext());
device.setCapabilities(capabilities());
device.setCreated(clock.millis());
device.setCreated(created);
device.setCreatedAtCiphertext(
EncryptDeviceCreationTimestampUtil.encrypt(created, aciIdentityKey, deviceId, aciRegistrationId()));
device.setLastSeen(Util.todayInMillis());
device.setUserAgent(signalAgent());
@@ -25,14 +25,10 @@ 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.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -45,8 +41,6 @@ public class MessagePersister implements Managed {
private final MessagesManager messagesManager;
private final AccountsManager accountsManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final DisconnectionRequestManager disconnectionRequestManager;
private final Duration persistDelay;
@@ -84,8 +78,6 @@ public class MessagePersister implements Managed {
final MessagesManager messagesManager,
final AccountsManager accountsManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final DisconnectionRequestManager disconnectionRequestManager,
final Duration persistDelay,
final int dedicatedProcessWorkerThreadCount) {
@@ -93,8 +85,6 @@ public class MessagePersister implements Managed {
this.messagesManager = messagesManager;
this.accountsManager = accountsManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.disconnectionRequestManager = disconnectionRequestManager;
this.persistDelay = persistDelay;
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
@@ -260,9 +250,7 @@ public class MessagePersister implements Managed {
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", accountUuid, deviceId);
accountsManager.removeDevice(account, deviceId)
.thenRun(() -> disconnectionRequestManager.requestDisconnection(accountUuid))
.join();
accountsManager.removeDevice(account, deviceId).join();
}
} finally {
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
@@ -264,7 +264,7 @@ public class Profiles {
/**
* Deletes all profile versions for the given UUID
*
* @return a list of avatar URLs to be deleted
* @return a list of avatar URLs that may be deleted
*/
public CompletableFuture<List<String>> deleteAll(final UUID uuid) {
final Timer.Sample sample = Timer.start();
@@ -60,12 +60,18 @@ public class ProfilesManager {
.thenCompose(ignored -> redisSetAsync(uuid, versionedProfile));
}
public CompletableFuture<Void> deleteAll(UUID uuid) {
/**
* Delete all profiles for the given uuid.
* <p>
* Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
* deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
*/
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
final CompletableFuture<Void> profilesAndAvatars = Mono.fromFuture(profiles.deleteAll(uuid))
.flatMapIterable(Function.identity())
.flatMap(avatar ->
Mono.fromFuture(deleteAvatar(avatar))
Mono.fromFuture(includeAvatar ? deleteAvatar(avatar) : CompletableFuture.completedFuture(null))
// this is best-effort
.retry(3)
.onErrorComplete())
@@ -12,13 +12,9 @@ import java.util.function.Supplier;
public class RemoteConfigsManager {
private final RemoteConfigs remoteConfigs;
private final Supplier<List<RemoteConfig>> remoteConfigSupplier;
public RemoteConfigsManager(RemoteConfigs remoteConfigs) {
this.remoteConfigs = remoteConfigs;
remoteConfigSupplier =
Suppliers.memoizeWithExpiration(remoteConfigs::getAll, 10, TimeUnit.SECONDS);
}
@@ -27,11 +23,4 @@ public class RemoteConfigsManager {
return remoteConfigSupplier.get();
}
public void set(RemoteConfig config) {
remoteConfigs.set(config);
}
public void delete(String name) {
remoteConfigs.delete(name);
}
}
@@ -169,11 +169,13 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
Metrics.counter(VALIDATE_COUNTER_NAME, subscriptionTags(subscription)).increment();
// We only ever acknowledge valid tokens. There are cases where a subscription was once valid and then was
// cancelled, so the user could still be entitled to their purchase. However, if we never acknowledge it, the
// user's charge will eventually be refunded anyway. See
// https://developer.android.com/google/play/billing/integrate#pending
if (state != SubscriptionState.ACTIVE) {
// We only accept tokens in a state where the user may be entitled to their purchase. This is true even in the
// CANCELLED state. For example, a user may subscribe for 1 month, then immediately cancel (disabling auto-renew)
// and then submit their token. In this case they should still be able to retrieve their entitlement.
// See https://developer.android.com/google/play/billing/integrate#life
if (state != SubscriptionState.ACTIVE
&& state != SubscriptionState.IN_GRACE_PERIOD
&& state != SubscriptionState.CANCELED) {
throw ExceptionUtils.wrap(new SubscriptionException.PaymentRequired(
"Cannot acknowledge purchase for subscription in state " + subscription.getSubscriptionState()));
}
@@ -240,11 +242,14 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
final SubscriptionStatus status = switch (SubscriptionState
.fromString(subscription.getSubscriptionState())
.orElse(SubscriptionState.UNSPECIFIED)) {
case ACTIVE -> SubscriptionStatus.ACTIVE;
// In play terminology CANCELLED is the same as an active subscription with cancelAtPeriodEnd set in Stripe. So
// it should map to the ACTIVE stripe status.
case ACTIVE, CANCELED -> SubscriptionStatus.ACTIVE;
case PENDING -> SubscriptionStatus.INCOMPLETE;
case EXPIRED, ON_HOLD, PAUSED -> SubscriptionStatus.PAST_DUE;
case ON_HOLD, PAUSED -> SubscriptionStatus.PAST_DUE;
case IN_GRACE_PERIOD -> SubscriptionStatus.UNPAID;
case CANCELED, PENDING_PURCHASE_CANCELED -> SubscriptionStatus.CANCELED;
// EXPIRED is the equivalent of a Stripe CANCELLED subscription
case EXPIRED, PENDING_PURCHASE_CANCELED -> SubscriptionStatus.CANCELED;
case UNSPECIFIED -> SubscriptionStatus.UNKNOWN;
};
@@ -0,0 +1,43 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import com.google.common.annotations.VisibleForTesting;
import org.signal.libsignal.protocol.IdentityKey;
import java.nio.ByteBuffer;
public class EncryptDeviceCreationTimestampUtil {
@VisibleForTesting
final static String ENCRYPTION_INFO = "deviceCreatedAt";
/**
* Encrypts the provided timestamp with the ACI identity key using the
* Hybrid Public Key Encryption scheme as defined in (<a href="https://www.rfc-editor.org/rfc/rfc9180.html">RFC 9180</a>).
*
* @param createdAt The timestamp in milliseconds since epoch when a given device was linked to the account.
* @param aciIdentityKey The ACI identity key associated with the account.
* @param deviceId The ID of the given device.
* @param registrationId The registration ID of the given device.
*
* @return The timestamp ciphertext
*/
public static byte[] encrypt(
final long createdAt,
final IdentityKey aciIdentityKey,
final byte deviceId,
final int registrationId) {
final ByteBuffer timestampBytes = ByteBuffer.allocate(8);
timestampBytes.putLong(createdAt);
// "Associated data" is metadata that ties the ciphertext to a specific context to prevent an adversary from
// swapping the ciphertext of two devices on the same account.
final ByteBuffer associatedData = ByteBuffer.allocate(5);
associatedData.put(deviceId);
associatedData.putInt(registrationId);
return aciIdentityKey.getPublicKey().seal(timestampBytes.array(), ENCRYPTION_INFO, associatedData.array());
}
}
@@ -12,6 +12,7 @@ import java.time.Duration;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import jdk.jfr.consumer.RecordedEvent;
@@ -35,36 +36,32 @@ public class VirtualThreadPinEventMonitor implements Managed {
private static final long MAX_JFR_REPOSITORY_SIZE = 1024 * 1024 * 4L; // 4MiB
private final ExecutorService executorService;
private final Supplier<Set<String>> allowList;
private final Duration pinEventThreshold;
private final RecordingStream recordingStream;
private final BiConsumer<RecordedEvent, Boolean> pinEventConsumer;
private final Consumer<RecordedEvent> pinEventConsumer;
@VisibleForTesting
VirtualThreadPinEventMonitor(
final ExecutorService executorService,
final Supplier<Set<String>> allowList,
final Duration pinEventThreshold,
final BiConsumer<RecordedEvent, Boolean> pinEventConsumer) {
final Consumer<RecordedEvent> pinEventConsumer) {
this.executorService = executorService;
this.allowList = allowList;
this.pinEventThreshold = pinEventThreshold;
this.pinEventConsumer = pinEventConsumer;
this.recordingStream = new RecordingStream();
}
public VirtualThreadPinEventMonitor(
final ExecutorService executorService,
final Supplier<Set<String>> allowList,
final Duration pinEventThreshold) {
this(executorService, allowList, pinEventThreshold, VirtualThreadPinEventMonitor::processPinEvent);
this(executorService, pinEventThreshold, VirtualThreadPinEventMonitor::processPinEvent);
}
@Override
public void start() {
recordingStream.setMaxSize(MAX_JFR_REPOSITORY_SIZE);
recordingStream.enable(JFR_THREAD_PINNED_EVENT_NAME).withThreshold(pinEventThreshold).withStackTrace();
recordingStream.onEvent(JFR_THREAD_PINNED_EVENT_NAME, event -> pinEventConsumer.accept(event, allowed(event)));
recordingStream.onEvent(JFR_THREAD_PINNED_EVENT_NAME, pinEventConsumer);
executorService.submit(recordingStream::start);
}
@@ -76,30 +73,9 @@ public class VirtualThreadPinEventMonitor implements Managed {
recordingStream.close();
}
private static void processPinEvent(final RecordedEvent event, final boolean allowedPinEvent) {
if (allowedPinEvent) {
logger.info("Long allowed virtual thread pin event detected {}", prettyEventString(event));
} else {
logger.error("Long forbidden virtual thread pin event detected {}", prettyEventString(event));
}
Metrics.counter(PIN_COUNTER_NAME, "allowed", String.valueOf(allowedPinEvent)).increment();
}
private boolean allowed(final RecordedEvent event) {
final Set<String> allowedMethodFrames = allowList.get();
if (event.getStackTrace() == null) {
return false;
}
for (RecordedFrame st : event.getStackTrace().getFrames()) {
if (!st.isJavaFrame()) {
continue;
}
final String qualifiedName = "%s.%s".formatted(st.getMethod().getType().getName(), st.getMethod().getName());
if (allowedMethodFrames.stream().anyMatch(qualifiedName::contains)) {
return true;
}
}
return false;
private static void processPinEvent(final RecordedEvent event) {
logger.info("Long virtual thread pin event detected {}", prettyEventString(event));
Metrics.counter(PIN_COUNTER_NAME).increment();
}
private static String prettyEventString(final RecordedEvent event) {
@@ -33,6 +33,7 @@ import reactor.core.scheduler.Scheduler;
public class AuthenticatedConnectListener implements WebSocketConnectListener {
private static final String OPEN_WEBSOCKET_GAUGE_NAME = name(WebSocketConnection.class, "openWebsockets");
private static final String NEW_CONNECTION_COUNTER_NAME = name(AuthenticatedConnectListener.class, "newConnections");
private static final String CONNECTED_DURATION_TIMER_NAME =
name(AuthenticatedConnectListener.class, "connectedDuration");
@@ -84,10 +85,10 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
this.experimentEnrollmentManager = experimentEnrollmentManager;
openAuthenticatedWebSocketCounter =
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "true"));
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "true"));
openUnauthenticatedWebSocketCounter =
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "false"));
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "false"));
}
@Override
@@ -54,6 +54,7 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
this.timeoutExecutor = timeoutExecutor;
this.timeout = timeout;
this.openWebSocketCounter = new OpenWebSocketCounter(MetricsUtil.name(getClass(), "openWebsockets"),
MetricsUtil.name(getClass(), "newConnections"),
MetricsUtil.name(getClass(), "sessionDuration"));
}
@@ -15,7 +15,6 @@ import java.util.Set;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -56,7 +55,7 @@ public class CertificateCommand extends Command {
}
private void runCaCommand() {
ECKeyPair keyPair = Curve.generateKeyPair();
ECKeyPair keyPair = ECKeyPair.generate();
System.out.println("Public key : " + Base64.getEncoder().encodeToString(keyPair.getPublicKey().serialize()));
System.out.println("Private key: " + Base64.getEncoder().encodeToString(keyPair.getPrivateKey().serialize()));
}
@@ -72,7 +71,7 @@ public class CertificateCommand extends Command {
return;
}
ECPrivateKey key = Curve.decodePrivatePoint(Base64.getDecoder().decode(namespace.getString("key")));
ECPrivateKey key = new ECPrivateKey(Base64.getDecoder().decode(namespace.getString("key")));
int keyId = namespace.getInt("keyId");
if (RESERVED_CERTIFICATE_IDS.contains(keyId)) {
@@ -80,7 +79,7 @@ public class CertificateCommand extends Command {
String.format("Key ID %08x has been reserved or revoked and may not be used in new certificates.", keyId));
}
ECKeyPair keyPair = Curve.generateKeyPair();
ECKeyPair keyPair = ECKeyPair.generate();
byte[] certificate = MessageProtos.ServerCertificate.Certificate.newBuilder()
.setId(keyId)
@@ -89,11 +88,7 @@ public class CertificateCommand extends Command {
.toByteArray();
byte[] signature;
try {
signature = Curve.calculateSignature(key, certificate);
} catch (org.signal.libsignal.protocol.InvalidKeyException e) {
throw new InvalidKeyException(e);
}
signature = key.calculateSignature(certificate);
byte[] signedCertificate = MessageProtos.ServerCertificate.newBuilder()
.setCertificate(ByteString.copyFrom(certificate))
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecoveryBController;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
@@ -45,7 +46,7 @@ import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -86,7 +87,6 @@ record CommandDependencies(
AccountsManager accountsManager,
ProfilesManager profilesManager,
ReportMessageManager reportMessageManager,
DisconnectionRequestManager disconnectionRequestManager,
MessagesCache messagesCache,
MessagesManager messagesManager,
KeysManager keysManager,
@@ -173,6 +173,8 @@ record CommandDependencies(
configuration.getSecureStorageServiceConfiguration());
ExternalServiceCredentialsGenerator secureValueRecovery2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
configuration.getSvr2Configuration());
ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator = SecureValueRecoveryBController.credentialsGenerator(
configuration.getSvrbConfiguration());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(MetricRegistry.name(WhisperServerService.class, "awsSdkMetrics-%d"));
@@ -238,10 +240,18 @@ record CommandDependencies(
.getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder);
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
redisClientResourcesBuilder);
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
secureValueRecovery2CredentialsGenerator, secureValueRecoveryServiceExecutor,
SecureValueRecoveryClient secureValueRecovery2Client = new SecureValueRecoveryClient(
secureValueRecovery2CredentialsGenerator,
secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
configuration.getSvr2Configuration());
configuration.getSvr2Configuration(),
() -> dynamicConfigurationManager.getConfiguration().getSvr2StatusCodesToIgnoreForAccountDeletion());
SecureValueRecoveryClient secureValueRecoveryBClient = new SecureValueRecoveryClient(
secureValueRecoveryBCredentialsGenerator,
secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
configuration.getSvrbConfiguration(),
() -> dynamicConfigurationManager.getConfiguration().getSvrbStatusCodesToIgnoreForAccountDeletion());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
@@ -264,7 +274,7 @@ record CommandDependencies(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
secureStorageClient, secureValueRecovery2Client, secureValueRecoveryBClient, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
@@ -322,7 +332,6 @@ record CommandDependencies(
accountsManager,
profilesManager,
reportMessageManager,
disconnectionRequestManager,
messagesCache,
messagesManager,
keys,
@@ -0,0 +1,87 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Duration;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;
public class EncryptDeviceCreationTimestampCommand extends AbstractSinglePassCrawlAccountsCommand {
@VisibleForTesting
static final String DRY_RUN_ARGUMENT = "dry-run";
private static final int MAX_CONCURRENCY = 16;
private static final String ENCRYPTED_CREATION_TIMESTAMP_COUNTER_NAME =
name(EncryptDeviceCreationTimestampCommand.class, "encryptedCreationTimestamp");
private static final String PROCESSED_ACCOUNT_COUNTER_NAME =
name(EncryptDeviceCreationTimestampCommand.class, "processedAccount");
private static final Logger log = LoggerFactory.getLogger(EncryptDeviceCreationTimestampCommand.class);
public EncryptDeviceCreationTimestampCommand() {
super("encrypt-device-creation-timestamps", "Encrypts the creation timestamp of devices on accounts");
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--dry-run")
.type(Boolean.class)
.dest(DRY_RUN_ARGUMENT)
.required(false)
.setDefault(true)
.help("If true, don't actually update device records");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final boolean isDryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
final Counter encryptedTimestampCounter =
Metrics.counter(ENCRYPTED_CREATION_TIMESTAMP_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
final Counter processedAccountCounter =
Metrics.counter(PROCESSED_ACCOUNT_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
accounts
.flatMap(account ->
Flux.fromIterable(account.getDevices())
.flatMap(device -> {
final byte[] createdAtCiphertext = EncryptDeviceCreationTimestampUtil.encrypt(
device.getCreated(), account.getIdentityKey(IdentityType.ACI),
device.getId(), device.getRegistrationId(IdentityType.ACI));
final Mono<Void> encryptTimestampMono = isDryRun
? Mono.empty()
: Mono.fromFuture(() -> getCommandDependencies().accountsManager().updateDeviceAsync(
account, device.getId(), d -> d.setCreatedAtCiphertext(createdAtCiphertext))
.thenRun(Util.NOOP));
return encryptTimestampMono
.doOnSuccess(_ -> encryptedTimestampCounter.increment())
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.onErrorResume(throwable -> {
log.warn("Failed to encrypt creation timestamp on device {}, account {}", device.getId(), account.getUuid(), throwable);
return Mono.empty();
});
}, MAX_CONCURRENCY),
MAX_CONCURRENCY)
.doOnComplete(processedAccountCounter::increment)
.then()
.block();
}
}
@@ -65,8 +65,6 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
deps.messagesManager(),
deps.accountsManager(),
deps.dynamicConfigurationManager(),
new ExperimentEnrollmentManager(deps.dynamicConfigurationManager()),
deps.disconnectionRequestManager(),
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
namespace.getInt(WORKER_COUNT));
@@ -110,10 +110,7 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
final Mono<Long> accountUpdate = dryRun
? Mono.just((long) expiredDevices.size())
: deleteDevices(account, expiredDevices, maxRetries)
.flatMap(count ->
Mono.fromCompletionStage(getCommandDependencies().disconnectionRequestManager().requestDisconnection(account.getUuid()))
.then(Mono.just(count)));
: deleteDevices(account, expiredDevices, maxRetries);
return accountUpdate
.doOnNext(successCounter::increment)
@@ -212,6 +212,10 @@ service BackupsAnonymous {
/**
* Retrieve an upload form that can be used to perform a resumable upload
*
* Trying to request an upload form larger than the maximum supported upload
* size will return a PRECONDITION_FAILED error. The maximum upload size is
* subject to change.
*/
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
@@ -333,7 +337,9 @@ message RefreshResponse {
message GetUploadFormRequest {
SignedPresentation signed_presentation = 1;
message MessagesUploadType {}
message MessagesUploadType {
uint64 uploadLength = 1;
}
message MediaUploadType {}
oneof upload_type {
/**
@@ -10,6 +10,7 @@ option java_multiple_files = true;
package org.signal.chat.device;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
/**
* Provides methods for working with devices attached to a Signal account.
@@ -84,6 +85,18 @@ message GetDevicesResponse {
* device last connected to the server.
*/
uint64 last_seen = 4;
/**
* The registration ID of the given device.
*/
uint32 registration_id = 5 [(require.range).max = 0x3fff];
/**
* A sequence of bytes that encodes the time,
* in milliseconds since the epoch, at which this device was
* attached to its parent account.
*/
bytes created_at_ciphertext = 6;
}
/**
@@ -0,0 +1,30 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
public class TestcontainersImages {
private static final String DYNAMO_DB = "${dynamodb.image}";
private static final String LOCAL_STACK = "${localstack.image}";
private static final String REDIS = "${redis.image}";
private static final String REDIS_CLUSTER = "${redis-cluster.image}";
public static String getDynamoDb() {
return DYNAMO_DB;
}
public static String getLocalStack() {
return LOCAL_STACK;
}
public static String getRedis() {
return REDIS;
}
public static String getRedisCluster() {
return REDIS_CLUSTER;
}
}
@@ -9,6 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.util.Resources;
@@ -25,6 +26,7 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
@@ -51,8 +53,12 @@ class WhisperServerServiceTest {
private static final WebSocketClient webSocketClient = new WebSocketClient();
private static final DropwizardAppExtension<WhisperServerConfiguration> EXTENSION = new DropwizardAppExtension<>(
WhisperServerService.class, Resources.getResource("config/test.yml").getPath());
WhisperServerService.class, Resources.getResource("config/test.yml").getPath(),
// Tables will be created by the local DynamoDbExtension
ConfigOverride.config("dynamoDbClient.initTables", "false"));
@RegisterExtension
public static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.values());
@AfterAll
static void teardown() {
@@ -118,8 +124,6 @@ class WhisperServerServiceTest {
assertEquals(401, whoami.getStatus());
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
assertTrue(whoamiTimestamp >= start);
}
@Test
@@ -142,11 +146,7 @@ class WhisperServerServiceTest {
void dynamoDb() {
// confirm that local dynamodb nominally works
final AwsCredentialsProvider awsCredentialsProvider = EXTENSION.getConfiguration().getAwsCredentialsConfiguration()
.build();
final DynamoDbClient dynamoDbClient = EXTENSION.getConfiguration().getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider, new NoopAwsSdkMetricPublisher());
final DynamoDbClient dynamoDbClient = getDynamoDbClient();
final DynamoDbExtension.TableSchema numbers = DynamoDbExtensionSchema.Tables.NUMBERS;
final AttributeValue numberAV = AttributeValues.s("+12125550001");
@@ -176,4 +176,12 @@ class WhisperServerServiceTest {
.build());
}
private static DynamoDbClient getDynamoDbClient() {
final AwsCredentialsProvider awsCredentialsProvider = EXTENSION.getConfiguration().getAwsCredentialsConfiguration()
.build();
return EXTENSION.getConfiguration().getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider, new NoopAwsSdkMetricPublisher());
}
}
@@ -15,7 +15,7 @@ import java.util.Base64;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -39,7 +39,7 @@ class CertificateGeneratorTest {
final byte deviceId = 4;
final CertificateGenerator certificateGenerator = new CertificateGenerator(
Base64.getDecoder().decode(SIGNING_CERTIFICATE),
Curve.decodePrivatePoint(Base64.getDecoder().decode(SIGNING_KEY)), 1);
new ECPrivateKey(Base64.getDecoder().decode(SIGNING_KEY)), 1);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
when(account.getUuid()).thenReturn(UUID.randomUUID());
@@ -62,8 +62,8 @@ import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
@@ -306,7 +306,7 @@ public class BackupManagerTest {
GenericServerSecretParams.generate(),
BackupLevel.FREE, backupKey, aci);
final ECKeyPair keyPair = Curve.generateKeyPair();
final ECKeyPair keyPair = ECKeyPair.generate();
// haven't set a public key yet, but should fail before hitting the database anyway
assertThatExceptionOfType(StatusRuntimeException.class)
@@ -328,7 +328,7 @@ public class BackupManagerTest {
GenericServerSecretParams.generate(),
BackupLevel.FREE, backupKey, aci);
final ECKeyPair keyPair = Curve.generateKeyPair();
final ECKeyPair keyPair = ECKeyPair.generate();
backupManager.setPublicKey(
presentation,
keyPair.getPrivateKey().calculateSignature(presentation.serialize()),
@@ -349,7 +349,7 @@ public class BackupManagerTest {
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
BackupLevel.FREE, backupKey, aci);
final ECKeyPair keyPair = Curve.generateKeyPair();
final ECKeyPair keyPair = ECKeyPair.generate();
final byte[] signature = keyPair.getPrivateKey().calculateSignature(presentation.serialize());
// haven't set a public key yet
@@ -365,8 +365,8 @@ public class BackupManagerTest {
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
BackupLevel.FREE, backupKey, aci);
final ECKeyPair keyPair1 = Curve.generateKeyPair();
final ECKeyPair keyPair2 = Curve.generateKeyPair();
final ECKeyPair keyPair1 = ECKeyPair.generate();
final ECKeyPair keyPair2 = ECKeyPair.generate();
final byte[] signature1 = keyPair1.getPrivateKey().calculateSignature(presentation.serialize());
final byte[] signature2 = keyPair2.getPrivateKey().calculateSignature(presentation.serialize());
@@ -388,7 +388,7 @@ public class BackupManagerTest {
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
BackupLevel.FREE, backupKey, aci);
final ECKeyPair keyPair = Curve.generateKeyPair();
final ECKeyPair keyPair = ECKeyPair.generate();
final byte[] signature = keyPair.getPrivateKey().calculateSignature(presentation.serialize());
// an invalid signature
@@ -423,7 +423,7 @@ public class BackupManagerTest {
testClock.pin(Instant.ofEpochSecond(1).plus(Duration.ofDays(1)));
final BackupAuthCredentialPresentation oldCredential = backupAuthTestUtil.getPresentation(BackupLevel.FREE,
backupKey, aci);
final ECKeyPair keyPair = Curve.generateKeyPair();
final ECKeyPair keyPair = ECKeyPair.generate();
final byte[] signature = keyPair.getPrivateKey().calculateSignature(oldCredential.serialize());
backupManager.setPublicKey(oldCredential, signature, keyPair.getPublicKey()).join();
@@ -1091,7 +1091,7 @@ public class BackupManagerTest {
byte[] privateKey = new byte[32];
ByteBuffer.wrap(privateKey).put(backupId);
try {
backupsDb.setPublicKey(backupId, backupLevel, Curve.decodePrivatePoint(privateKey).publicKey()).join();
backupsDb.setPublicKey(backupId, backupLevel, new ECPrivateKey(privateKey).publicKey()).join();
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
@@ -26,7 +26,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
@@ -95,7 +95,7 @@ public class BackupsDbTest {
final byte[] backupId = TestRandomUtil.nextBytes(16);
// Refresh media/messages at t=0D
testClock.pin(days(0));
backupsDb.setPublicKey(backupId, BackupLevel.PAID, Curve.generateKeyPair().getPublicKey()).join();
backupsDb.setPublicKey(backupId, BackupLevel.PAID, ECKeyPair.generate().getPublicKey()).join();
this.backupsDb.ttlRefresh(backupUser(backupId, BackupCredentialType.MEDIA, BackupLevel.PAID)).join();
// refresh only messages on t=2D
@@ -138,7 +138,7 @@ public class BackupsDbTest {
final byte[] backupId = TestRandomUtil.nextBytes(16);
// Refresh media/messages at t=0D
testClock.pin(days(0));
backupsDb.setPublicKey(backupId, BackupLevel.PAID, Curve.generateKeyPair().getPublicKey()).join();
backupsDb.setPublicKey(backupId, BackupLevel.PAID, ECKeyPair.generate().getPublicKey()).join();
this.backupsDb.ttlRefresh(backupUser(backupId, BackupCredentialType.MEDIA, BackupLevel.PAID)).join();
if (expirationType == ExpiredBackup.ExpirationType.MEDIA) {
@@ -5,7 +5,10 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.Optional;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
@@ -18,23 +21,76 @@ public class LocalDynamoDbFactory implements DynamoDbClientFactory {
private static final DynamoDbExtension EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.values());
static {
try {
EXTENSION.beforeEach(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
private boolean initExtension = true;
Runtime.getRuntime().addShutdownHook(new Thread(() -> EXTENSION.afterEach(null)));
}
/**
* If true, tables will be created the first time a DynamoDB client is built.
* <p>
* Defaults to {@code true}.
*/
@JsonProperty
boolean initTables = true;
/**
* If specified, will be provided to {@link DynamoDbExtension} to use instead of its embedded container
*/
@Nullable
@JsonProperty
DynamoDbLocalOverrides overrides;
@Override
public DynamoDbClient buildSyncClient(final AwsCredentialsProvider awsCredentialsProvider, final MetricPublisher metricPublisher) {
initExtensionIfNecessary();
initTablesIfNecessary();
return EXTENSION.getDynamoDbClient();
}
@Override
public DynamoDbAsyncClient buildAsyncClient(final AwsCredentialsProvider awsCredentialsProvider, final MetricPublisher metricPublisher) {
initExtensionIfNecessary();
initTablesIfNecessary();
return EXTENSION.getDynamoDbAsyncClient();
}
private void initExtensionIfNecessary() {
if (initExtension) {
try {
Optional.ofNullable(overrides)
.ifPresent(o -> {
Optional.ofNullable(o.endpoint).ifPresent(EXTENSION::setEndpointOverride);
Optional.ofNullable(o.region).ifPresent(EXTENSION::setRegion);
Optional.ofNullable(o.awsCredentialsProvider).ifPresent(p -> EXTENSION.setAwsCredentialsProvider(p.build()));
});
EXTENSION.beforeAll(null);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
EXTENSION.close();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}));
initExtension = false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private void initTablesIfNecessary() {
try {
if (initTables) {
EXTENSION.beforeEach(null);
initTables = false;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private record DynamoDbLocalOverrides(@Nullable String endpoint, @Nullable AwsCredentialsProviderFactory awsCredentialsProvider, @Nullable String region) {}
}
@@ -33,7 +33,6 @@ public class LocalFaultTolerantRedisClusterFactory implements FaultTolerantRedis
if (shutdownHookConfigured.compareAndSet(false, true)) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
redisClusterExtension.afterEach(null);
redisClusterExtension.close();
} catch (Throwable e) {
throw new RuntimeException(e);
@@ -44,7 +43,7 @@ public class LocalFaultTolerantRedisClusterFactory implements FaultTolerantRedis
final RedisClusterConfiguration config = new RedisClusterConfiguration();
config.setConfigurationUri(RedisClusterExtension.getRedisURIs().getFirst().toString());
return new FaultTolerantRedisClusterClient(name, config, clientResourcesBuilder);
return new FaultTolerantRedisClusterClient(name, config, clientResourcesBuilder.socketAddressResolver(redisClusterExtension.getSocketAddressResolver()));
}
}
@@ -62,7 +62,6 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
@@ -103,7 +102,7 @@ class AccountControllerV2Test {
private static final long SESSION_EXPIRATION_SECONDS = Duration.ofMinutes(10).toSeconds();
private static final ECKeyPair IDENTITY_KEY_PAIR = Curve.generateKeyPair();
private static final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
private static final IdentityKey IDENTITY_KEY = new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey());
private static final String NEW_NUMBER = PhoneNumberUtil.getInstance().format(
@@ -240,7 +239,7 @@ class AccountControllerV2Test {
.put(Entity.entity(
// +4407700900111 is a valid number but not normalized - it has an optional '0' after the country code
new ChangeNumberRequest(encodeSessionId("session"), null, "+4407700900111", null,
new IdentityKey(Curve.generateKeyPair().getPublicKey()),
new IdentityKey(ECKeyPair.generate().getPublicKey()),
Collections.emptyList(),
Collections.emptyMap(), null, Collections.emptyMap()),
MediaType.APPLICATION_JSON_TYPE))) {
@@ -604,168 +603,6 @@ class AccountControllerV2Test {
}
}
@Nested
class PhoneNumberIdentityKeyDistribution {
@BeforeEach
void setUp() throws Exception {
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
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);
final UUID uuid = account.getUuid();
final UUID pni = account.getPhoneNumberIdentifier();
final String number = account.getNumber();
final List<Device> devices = account.getDevices();
final Account updatedAccount = mock(Account.class);
when(updatedAccount.getUuid()).thenReturn(uuid);
when(updatedAccount.getNumber()).thenReturn(number);
when(updatedAccount.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(pni);
when(updatedAccount.getDevices()).thenReturn(devices);
for (byte i = 1; i <= 3; i++) {
final Optional<Device> d = account.getDevice(i);
when(updatedAccount.getDevice(i)).thenReturn(d);
}
return updatedAccount;
});
}
@Test
void pniKeyDistributionSuccess() throws Exception {
final AccountIdentityResponse accountIdentityResponse =
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()), AccountIdentityResponse.class);
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());
assertEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
}
@Test
void unprocessableRequestJson() {
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/phone_number_identity_key_distribution")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = request.put(Entity.json(unprocessableJson()))) {
assertEquals(400, response.getStatus());
}
}
@Test
void missingBasicAuthorization() {
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/phone_number_identity_key_distribution")
.request();
try (Response response = request.put(Entity.json(requestJson()))) {
assertEquals(401, response.getStatus());
}
}
@Test
void invalidBasicAuthorization() {
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/phone_number_identity_key_distribution")
.request()
.header(HttpHeaders.AUTHORIZATION, "Basic but-invalid");
try (Response response = request.put(Entity.json(requestJson()))) {
assertEquals(401, response.getStatus());
}
}
@Test
void invalidRequestBody() {
final Invocation.Builder request = resources.getJerseyTest()
.target("/v2/accounts/phone_number_identity_key_distribution")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = request.put(Entity.json(invalidRequestJson()))) {
assertEquals(422, response.getStatus());
}
}
@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}
*/
private static String requestJson() {
final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(1, IDENTITY_KEY_PAIR);
final KEMSignedPreKey pniLastResortPreKey = KeysHelper.signedKEMPreKey(2, IDENTITY_KEY_PAIR);
return String.format("""
{
"pniIdentityKey": "%s",
"deviceMessages": [],
"devicePniSignedPrekeys": {},
"devicePniSignedPrekeys": {"1": {"keyId": %d, "publicKey": "%s", "signature": "%s"}},
"devicePniPqLastResortPrekeys": {"1": {"keyId": %d, "publicKey": "%s", "signature": "%s"}},
"pniRegistrationIds": {"1": 17}
}
""", Base64.getEncoder().encodeToString(IDENTITY_KEY.serialize()),
pniSignedPreKey.keyId(), Base64.getEncoder().encodeToString(pniSignedPreKey.serializedPublicKey()), Base64.getEncoder().encodeToString(pniSignedPreKey.signature()),
pniLastResortPreKey.keyId(), Base64.getEncoder().encodeToString(pniLastResortPreKey.serializedPublicKey()), Base64.getEncoder().encodeToString(pniLastResortPreKey.signature()));
}
/**
* Request JSON in the shape of {@link org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest}, but that
* fails validation
*/
private static String invalidRequestJson() {
return """
{
"pniIdentityKey": null,
"deviceMessages": [],
"devicePniSignedPrekeys": {},
"pniRegistrationIds": {}
}
""";
}
/**
* Request JSON that cannot be marshalled into
* {@link org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest}
*/
private static String unprocessableJson() {
return """
{
"pniIdentityKey": []
}
""";
}
}
@Nested
class PhoneNumberDiscoverability {
@@ -964,8 +801,8 @@ class AccountControllerV2Test {
final boolean unrestrictedUnidentifiedAccess, final boolean discoverableByPhoneNumber,
List<AccountBadge> badges, List<DeviceData> devices) {
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final Account account = new Account();
account.setUuid(aci);
@@ -47,7 +47,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -247,7 +247,7 @@ public class ArchiveControllerTest {
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
.header("X-Signal-ZK-Auth-Signature", "aaa")
.put(Entity.entity(
new ArchiveController.SetPublicKeyRequest(Curve.generateKeyPair().getPublicKey()),
new ArchiveController.SetPublicKeyRequest(ECKeyPair.generate().getPublicKey()),
MediaType.APPLICATION_JSON_TYPE));
assertThat(response.getStatus()).isEqualTo(204);
}
@@ -574,6 +574,46 @@ public class ArchiveControllerTest {
assertThat(response.getStatus()).isEqualTo(204);
}
static Stream<Arguments> messagesUploadForm() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE), true),
Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false)
);
}
@ParameterizedTest
@MethodSource
public void messagesUploadForm(Optional<Long> uploadLength, boolean expectSuccess) throws VerificationFailedException {
final BackupAuthCredentialPresentation presentation =
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
when(backupManager.authenticateBackupUser(any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
when(backupManager.createMessageBackupUploadDescriptor(any()))
.thenReturn(CompletableFuture.completedFuture(
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
final WebTarget builder = resources.getJerseyTest().target("v1/archives/upload/form");
final Response response = uploadLength
.map(length -> builder.queryParam("uploadLength", length))
.orElse(builder)
.request()
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
.header("X-Signal-ZK-Auth-Signature", "aaa")
.get();
if (expectSuccess) {
assertThat(response.getStatus()).isEqualTo(200);
ArchiveController.UploadDescriptorResponse desc = response.readEntity(ArchiveController.UploadDescriptorResponse.class);
assertThat(desc.cdn()).isEqualTo(3);
assertThat(desc.key()).isEqualTo("abc");
assertThat(desc.headers()).containsExactlyEntriesOf(Map.of("k", "v"));
assertThat(desc.signedUploadLocation()).isEqualTo("example.org");
} else {
assertThat(response.getStatus()).isEqualTo(413);
}
}
@Test
public void mediaUploadForm() throws VerificationFailedException {
final BackupAuthCredentialPresentation presentation =
@@ -35,7 +35,8 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
@@ -56,7 +57,15 @@ import org.whispersystems.textsecuregcm.util.SystemMapper;
@ExtendWith(DropwizardExtensionsSupport.class)
class CertificateControllerTest {
private static final String caPublicKey = "BWh+UOhT1hD8bkb+MFRvb6tVqhoG8YYGCzOd7mgjo8cV";
private static final ECPublicKey caPublicKey;
static {
try {
caPublicKey = new ECPublicKey(Base64.getDecoder().decode("BWh+UOhT1hD8bkb+MFRvb6tVqhoG8YYGCzOd7mgjo8cV"));
} catch (InvalidKeyException e) {
throw new AssertionError("Statically-defined key was invalid", e);
}
}
@SuppressWarnings("unused")
private static final String caPrivateKey = "EO3Mnf0kfVlVnwSaqPoQnAxhnnGL1JTdXqktCKEe9Eo=";
@@ -76,7 +85,7 @@ class CertificateControllerTest {
static {
try {
certificateGenerator = new CertificateGenerator(Base64.getDecoder().decode(signingCertificate),
Curve.decodePrivatePoint(Base64.getDecoder().decode(signingKey)), 1);
new ECPrivateKey(Base64.getDecoder().decode(signingKey)), 1);
serverZkAuthOperations = new ServerZkAuthOperations(serverSecretParams);
} catch (IOException | InvalidKeyException e) {
throw new AssertionError(e);
@@ -112,11 +121,12 @@ class CertificateControllerTest {
ServerCertificate serverCertificateHolder = certificate.getSigner();
ServerCertificate.Certificate serverCertificate = ServerCertificate.Certificate.parseFrom(
serverCertificateHolder.getCertificate());
ECPublicKey serverPublicKey = new ECPublicKey(serverCertificate.getKey().toByteArray());
assertTrue(Curve.verifySignature(Curve.decodePoint(serverCertificate.getKey().toByteArray(), 0),
assertTrue(serverPublicKey.verifySignature(
certificateHolder.getCertificate().toByteArray(), certificateHolder.getSignature().toByteArray()));
assertTrue(Curve.verifySignature(Curve.decodePoint(Base64.getDecoder().decode(caPublicKey), 0),
serverCertificateHolder.getCertificate().toByteArray(), serverCertificateHolder.getSignature().toByteArray()));
assertTrue(caPublicKey.verifySignature(serverCertificateHolder.getCertificate().toByteArray(),
serverCertificateHolder.getSignature().toByteArray()));
assertEquals(certificate.getSender(), AuthHelper.VALID_NUMBER);
assertEquals(certificate.getSenderDevice(), 1L);
@@ -141,11 +151,12 @@ class CertificateControllerTest {
ServerCertificate serverCertificateHolder = certificate.getSigner();
ServerCertificate.Certificate serverCertificate = ServerCertificate.Certificate.parseFrom(
serverCertificateHolder.getCertificate());
ECPublicKey serverPublicKey = new ECPublicKey(serverCertificate.getKey().toByteArray());
assertTrue(Curve.verifySignature(Curve.decodePoint(serverCertificate.getKey().toByteArray(), 0),
certificateHolder.getCertificate().toByteArray(), certificateHolder.getSignature().toByteArray()));
assertTrue(Curve.verifySignature(Curve.decodePoint(Base64.getDecoder().decode(caPublicKey), 0),
serverCertificateHolder.getCertificate().toByteArray(), serverCertificateHolder.getSignature().toByteArray()));
assertTrue(serverPublicKey.verifySignature(certificateHolder.getCertificate().toByteArray(),
certificateHolder.getSignature().toByteArray()));
assertTrue(caPublicKey.verifySignature(serverCertificateHolder.getCertificate().toByteArray(),
serverCertificateHolder.getSignature().toByteArray()));
assertEquals(certificate.getSender(), AuthHelper.VALID_NUMBER);
assertEquals(certificate.getSenderDevice(), 1L);
@@ -170,11 +181,12 @@ class CertificateControllerTest {
ServerCertificate serverCertificateHolder = certificate.getSigner();
ServerCertificate.Certificate serverCertificate = ServerCertificate.Certificate.parseFrom(
serverCertificateHolder.getCertificate());
ECPublicKey serverPublicKey = new ECPublicKey(serverCertificate.getKey().toByteArray());
assertTrue(Curve.verifySignature(Curve.decodePoint(serverCertificate.getKey().toByteArray(), 0),
certificateHolder.getCertificate().toByteArray(), certificateHolder.getSignature().toByteArray()));
assertTrue(Curve.verifySignature(Curve.decodePoint(Base64.getDecoder().decode(caPublicKey), 0),
serverCertificateHolder.getCertificate().toByteArray(), serverCertificateHolder.getSignature().toByteArray()));
assertTrue(serverPublicKey.verifySignature(certificateHolder.getCertificate().toByteArray(),
certificateHolder.getSignature().toByteArray()));
assertTrue(caPublicKey.verifySignature(serverCertificateHolder.getCertificate().toByteArray(),
serverCertificateHolder.getSignature().toByteArray()));
assertTrue(StringUtils.isBlank(certificate.getSender()));
assertEquals(certificate.getSenderDevice(), 1L);
@@ -57,7 +57,6 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.ArgumentCaptor;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -191,12 +190,16 @@ class DeviceControllerTest {
final byte[] deviceName = "refreshed-device-name".getBytes(StandardCharsets.UTF_8);
final long deviceCreated = System.currentTimeMillis();
final long deviceLastSeen = deviceCreated + 1;
final int registrationId = 2;
final byte[] createdAtCiphertext = "timestamp ciphertext".getBytes(StandardCharsets.UTF_8);
final Device refreshedDevice = mock(Device.class);
when(refreshedDevice.getId()).thenReturn(deviceId);
when(refreshedDevice.getName()).thenReturn(deviceName);
when(refreshedDevice.getCreated()).thenReturn(deviceCreated);
when(refreshedDevice.getLastSeen()).thenReturn(deviceLastSeen);
when(refreshedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
when(refreshedDevice.getCreatedAtCiphertext()).thenReturn(createdAtCiphertext);
final Account refreshedAccount = mock(Account.class);
when(refreshedAccount.getDevices()).thenReturn(List.of(refreshedDevice));
@@ -214,6 +217,8 @@ class DeviceControllerTest {
assertArrayEquals(deviceName, deviceInfoList.devices().getFirst().name());
assertEquals(deviceCreated, deviceInfoList.devices().getFirst().created());
assertEquals(deviceLastSeen, deviceInfoList.devices().getFirst().lastSeen());
assertEquals(registrationId, deviceInfoList.devices().getFirst().registrationId());
assertArrayEquals(createdAtCiphertext, deviceInfoList.devices().getFirst().createdAtCiphertext());
}
@ParameterizedTest
@@ -234,15 +239,16 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(aciIdentityKey);
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
@@ -251,7 +257,7 @@ class DeviceControllerTest {
final Account a = invocation.getArgument(0);
final DeviceSpec deviceSpec = invocation.getArgument(1);
return CompletableFuture.completedFuture(new Pair<>(a, deviceSpec.toDevice(NEXT_DEVICE_ID, testClock)));
return CompletableFuture.completedFuture(new Pair<>(a, deviceSpec.toDevice(NEXT_DEVICE_ID, testClock, aciIdentityKey)));
});
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
@@ -274,7 +280,7 @@ class DeviceControllerTest {
final ArgumentCaptor<DeviceSpec> deviceSpecCaptor = ArgumentCaptor.forClass(DeviceSpec.class);
verify(accountsManager).addDevice(eq(account), deviceSpecCaptor.capture(), any());
final Device device = deviceSpecCaptor.getValue().toDevice(NEXT_DEVICE_ID, testClock);
final Device device = deviceSpecCaptor.getValue().toDevice(NEXT_DEVICE_ID, testClock, aciIdentityKey);
assertEquals(fetchesMessages, device.getFetchesMessages());
@@ -315,8 +321,8 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -367,8 +373,8 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -403,8 +409,8 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -452,8 +458,8 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -503,8 +509,8 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -577,8 +583,8 @@ class DeviceControllerTest {
}
private static Stream<Arguments> linkDeviceAtomicMissingProperty() {
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -603,8 +609,8 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -670,8 +676,8 @@ class DeviceControllerTest {
}
private static Stream<Arguments> linkDeviceAtomicInvalidSignature() {
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -703,8 +709,8 @@ class DeviceControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
@@ -735,22 +741,23 @@ class DeviceControllerTest {
when(existingDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(account.getDevices()).thenReturn(List.of(existingDevice));
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(aciIdentityKey);
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(accountsManager.addDevice(any(), any(), any())).thenAnswer(invocation -> {
final Account a = invocation.getArgument(0);
final DeviceSpec deviceSpec = invocation.getArgument(1);
return CompletableFuture.completedFuture(new Pair<>(a, deviceSpec.toDevice(NEXT_DEVICE_ID, testClock)));
return CompletableFuture.completedFuture(new Pair<>(a, deviceSpec.toDevice(NEXT_DEVICE_ID, testClock, aciIdentityKey)));
});
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
@@ -935,7 +942,7 @@ class DeviceControllerTest {
@Test
void setPublicKey() {
final SetPublicKeyRequest request = new SetPublicKeyRequest(Curve.generateKeyPair().getPublicKey());
final SetPublicKeyRequest request = new SetPublicKeyRequest(ECKeyPair.generate().getPublicKey());
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/public_key")
@@ -954,7 +961,9 @@ class DeviceControllerTest {
final DeviceInfo deviceInfo = new DeviceInfo(Device.PRIMARY_ID,
"Device name ciphertext".getBytes(StandardCharsets.UTF_8),
System.currentTimeMillis(),
System.currentTimeMillis());
System.currentTimeMillis(),
1,
"timestamp ciphertext".getBytes(StandardCharsets.UTF_8));
final String tokenIdentifier = Base64.getUrlEncoder().withoutPadding().encodeToString(new byte[32]);
@@ -977,6 +986,8 @@ class DeviceControllerTest {
assertArrayEquals(deviceInfo.name(), retrievedDeviceInfo.name());
assertEquals(deviceInfo.created(), retrievedDeviceInfo.created());
assertEquals(deviceInfo.lastSeen(), retrievedDeviceInfo.lastSeen());
assertEquals(deviceInfo.registrationId(), retrievedDeviceInfo.registrationId());
assertArrayEquals(deviceInfo.createdAtCiphertext(), retrievedDeviceInfo.createdAtCiphertext());
}
}
@@ -1392,8 +1403,8 @@ class DeviceControllerTest {
final AccountAttributes accountAttributes = new AccountAttributes(true, 1234, 5678, null,
null, true, Set.of());
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final LinkDeviceRequest request = new LinkDeviceRequest(verificationCode,
accountAttributes,
@@ -58,7 +58,7 @@ import org.signal.keytransparency.client.SearchProof;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.UpdateValue;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.KeyTransparencyDistinguishedKeyResponse;
import org.whispersystems.textsecuregcm.entities.KeyTransparencyMonitorRequest;
@@ -86,7 +86,7 @@ public class KeyTransparencyControllerTest {
public static final byte[] USERNAME_HASH = TestRandomUtil.nextBytes(20);
private static final TestRemoteAddressFilterProvider TEST_REMOTE_ADDRESS_FILTER_PROVIDER
= new TestRemoteAddressFilterProvider("127.0.0.1");
public static final IdentityKey ACI_IDENTITY_KEY = new IdentityKey(Curve.generateKeyPair().getPublicKey());
public static final IdentityKey ACI_IDENTITY_KEY = new IdentityKey(ECKeyPair.generate().getPublicKey());
private static final byte[] COMMITMENT_INDEX = new byte[32];
public static final byte[] UNIDENTIFIED_ACCESS_KEY = new byte[16];
private final KeyTransparencyServiceClient keyTransparencyServiceClient = mock(KeyTransparencyServiceClient.class);
@@ -53,7 +53,6 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -111,10 +110,10 @@ class KeysControllerTest {
private static final int SAMPLE_PNI_REGISTRATION_ID = 1717;
private final ECKeyPair IDENTITY_KEY_PAIR = Curve.generateKeyPair();
private final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
private final IdentityKey IDENTITY_KEY = new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey());
private final ECKeyPair PNI_IDENTITY_KEY_PAIR = Curve.generateKeyPair();
private final ECKeyPair PNI_IDENTITY_KEY_PAIR = ECKeyPair.generate();
private final IdentityKey PNI_IDENTITY_KEY = new IdentityKey(PNI_IDENTITY_KEY_PAIR.getPublicKey());
private final ECPreKey SAMPLE_KEY = KeysHelper.ecPreKey(1234);
@@ -124,12 +123,12 @@ class KeysControllerTest {
private final ECPreKey SAMPLE_KEY_PNI = KeysHelper.ecPreKey(7777);
private final KEMSignedPreKey SAMPLE_PQ_KEY = KeysHelper.signedKEMPreKey(2424, Curve.generateKeyPair());
private final KEMSignedPreKey SAMPLE_PQ_KEY2 = KeysHelper.signedKEMPreKey(6868, Curve.generateKeyPair());
private final KEMSignedPreKey SAMPLE_PQ_KEY3 = KeysHelper.signedKEMPreKey(1313, Curve.generateKeyPair());
private final KEMSignedPreKey SAMPLE_PQ_KEY4 = KeysHelper.signedKEMPreKey(7676, Curve.generateKeyPair());
private final KEMSignedPreKey SAMPLE_PQ_KEY = KeysHelper.signedKEMPreKey(2424, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY2 = KeysHelper.signedKEMPreKey(6868, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY3 = KeysHelper.signedKEMPreKey(1313, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY4 = KeysHelper.signedKEMPreKey(7676, ECKeyPair.generate());
private final KEMSignedPreKey SAMPLE_PQ_KEY_PNI = KeysHelper.signedKEMPreKey(8888, Curve.generateKeyPair());
private final KEMSignedPreKey SAMPLE_PQ_KEY_PNI = KeysHelper.signedKEMPreKey(8888, ECKeyPair.generate());
private final ECSignedPreKey SAMPLE_SIGNED_KEY = KeysHelper.signedECPreKey(1111, IDENTITY_KEY_PAIR);
private final ECSignedPreKey SAMPLE_SIGNED_KEY2 = KeysHelper.signedECPreKey(2222, IDENTITY_KEY_PAIR);
@@ -860,7 +859,7 @@ class KeysControllerTest {
@Test
void putKeysStructurallyInvalidSignedECKey() {
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final KEMSignedPreKey wrongPreKey = KeysHelper.signedKEMPreKey(1, identityKeyPair);
final WeaklyTypedPreKeyState preKeyState =
@@ -878,7 +877,7 @@ class KeysControllerTest {
@Test
void putKeysStructurallyInvalidUnsignedECKey() {
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final WeaklyTypedPreKey wrongPreKey = new WeaklyTypedPreKey(1, "cluck cluck i'm a parrot".getBytes());
final WeaklyTypedPreKeyState preKeyState =
@@ -896,7 +895,7 @@ class KeysControllerTest {
@Test
void putKeysStructurallyInvalidPQOneTimeKey() {
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final WeaklyTypedSignedPreKey wrongPreKey = WeaklyTypedSignedPreKey.fromSignedPreKey(KeysHelper.signedECPreKey(1, identityKeyPair));
final WeaklyTypedPreKeyState preKeyState =
@@ -914,7 +913,7 @@ class KeysControllerTest {
@Test
void putKeysStructurallyInvalidPQLastResortKey() {
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final WeaklyTypedSignedPreKey wrongPreKey = WeaklyTypedSignedPreKey.fromSignedPreKey(KeysHelper.signedECPreKey(1, identityKeyPair));
final WeaklyTypedPreKeyState preKeyState =
@@ -1028,7 +1027,7 @@ class KeysControllerTest {
@Test
void putPrekeyWithInvalidSignature() {
final ECSignedPreKey badSignedPreKey = KeysHelper.signedECPreKey(1, Curve.generateKeyPair());
final ECSignedPreKey badSignedPreKey = KeysHelper.signedECPreKey(1, ECKeyPair.generate());
final SetKeysRequest setKeysRequest = new SetKeysRequest(List.of(), badSignedPreKey, null, null);
Response response =
resources.getJerseyTest()
@@ -1106,7 +1105,7 @@ class KeysControllerTest {
// Mismatched identity key
Arguments.of(
new IdentityKey(Curve.generateKeyPair().getPublicKey()),
new IdentityKey(ECKeyPair.generate().getPublicKey()),
ecSignedPreKey,
Optional.of(ecSignedPreKey),
lastResortKey,
@@ -63,7 +63,7 @@ import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.ArgumentCaptor;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerPublicParams;
import org.signal.libsignal.zkgroup.ServerSecretParams;
@@ -131,10 +131,10 @@ class ProfileControllerTest {
private static final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
private static final byte[] UNIDENTIFIED_ACCESS_KEY = "sixteenbytes1234".getBytes(StandardCharsets.UTF_8);
private static final IdentityKey ACCOUNT_IDENTITY_KEY = new IdentityKey(Curve.generateKeyPair().getPublicKey());
private static final IdentityKey ACCOUNT_PHONE_NUMBER_IDENTITY_KEY = new IdentityKey(Curve.generateKeyPair().getPublicKey());
private static final IdentityKey ACCOUNT_TWO_IDENTITY_KEY = new IdentityKey(Curve.generateKeyPair().getPublicKey());
private static final IdentityKey ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY = new IdentityKey(Curve.generateKeyPair().getPublicKey());
private static final IdentityKey ACCOUNT_IDENTITY_KEY = new IdentityKey(ECKeyPair.generate().getPublicKey());
private static final IdentityKey ACCOUNT_PHONE_NUMBER_IDENTITY_KEY = new IdentityKey(ECKeyPair.generate().getPublicKey());
private static final IdentityKey ACCOUNT_TWO_IDENTITY_KEY = new IdentityKey(ECKeyPair.generate().getPublicKey());
private static final IdentityKey ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY = new IdentityKey(ECKeyPair.generate().getPublicKey());
private static final String BASE_64_URL_USERNAME_HASH = "9p6Tip7BFefFOJzv4kv4GyXEYsBVfk_WbjNejdlOvQE";
private static final byte[] USERNAME_HASH = Base64.getUrlDecoder().decode(BASE_64_URL_USERNAME_HASH);
@SuppressWarnings("unchecked")
@@ -930,14 +930,14 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
assertThat(profile.getBaseProfileResponse().getIdentityKey()).isEqualTo(ACCOUNT_TWO_IDENTITY_KEY);
assertThat(profile.getName()).containsExactly(name);
assertThat(profile.getAbout()).containsExactly(about);
assertThat(profile.getAboutEmoji()).containsExactly(emoji);
assertThat(profile.getAvatar()).isEqualTo("profiles/validavatar");
assertThat(profile.getPhoneNumberSharing()).containsExactly(phoneNumberSharing);
assertThat(profile.getBaseProfileResponse().getUuid()).isEqualTo(new AciServiceIdentifier(AuthHelper.VALID_UUID_TWO));
assertThat(profile.getBaseProfileResponse().getBadges()).hasSize(1).element(0).has(new Condition<>(
assertThat(profile.baseProfileResponse().getIdentityKey()).isEqualTo(ACCOUNT_TWO_IDENTITY_KEY);
assertThat(profile.name()).containsExactly(name);
assertThat(profile.about()).containsExactly(about);
assertThat(profile.aboutEmoji()).containsExactly(emoji);
assertThat(profile.avatar()).isEqualTo("profiles/validavatar");
assertThat(profile.phoneNumberSharing()).containsExactly(phoneNumberSharing);
assertThat(profile.baseProfileResponse().getUuid()).isEqualTo(new AciServiceIdentifier(AuthHelper.VALID_UUID_TWO));
assertThat(profile.baseProfileResponse().getBadges()).hasSize(1).element(0).has(new Condition<>(
badge -> "Test Badge".equals(badge.getName()), "has badge with expected name"));
verify(rateLimiter, times(1)).validate(AuthHelper.VALID_UUID);
@@ -982,7 +982,7 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
assertThat(profile.getPaymentAddress()).containsExactly(paymentAddress);
assertThat(profile.paymentAddress()).containsExactly(paymentAddress);
}
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version));
@@ -994,7 +994,7 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
assertThat(profile.getPaymentAddress()).containsExactly(paymentAddress);
assertThat(profile.paymentAddress()).containsExactly(paymentAddress);
}
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("someotherversion")));
@@ -1006,7 +1006,7 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
assertThat(profile.getPaymentAddress()).isNull();
assertThat(profile.paymentAddress()).isNull();
}
}
@@ -1026,7 +1026,7 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(ExpiringProfileKeyCredentialProfileResponse.class);
assertThat(profile.getVersionedProfileResponse().getBaseProfileResponse().getUuid())
assertThat(profile.getVersionedProfileResponse().baseProfileResponse().getUuid())
.isEqualTo(new AciServiceIdentifier(AuthHelper.VALID_UUID));
assertThat(profile.getCredential()).isNull();
@@ -1245,7 +1245,7 @@ class ProfileControllerTest {
.headers(authHeaders)
.get(ExpiringProfileKeyCredentialProfileResponse.class);
assertThat(profile.getVersionedProfileResponse().getBaseProfileResponse().getUuid())
assertThat(profile.getVersionedProfileResponse().baseProfileResponse().getUuid())
.isEqualTo(new AciServiceIdentifier(AuthHelper.VALID_UUID));
assertThat(profile.getCredential()).isEqualTo(credentialResponse);
@@ -1376,9 +1376,9 @@ class ProfileControllerTest {
.equals(expectedIdentityKeys.get(element.uuid())),
"is an expected UUID with the correct identity key");
final IdentityKey validAciIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
final IdentityKey secondValidPniIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
final IdentityKey invalidAciIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
final IdentityKey validAciIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
final IdentityKey secondValidPniIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
final IdentityKey invalidAciIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
try (final Response response = resources.getJerseyTest().target("/v1/profile/identity_check/batch").request()
.post(Entity.json(new BatchIdentityCheckRequest(List.of(
@@ -1409,7 +1409,7 @@ class ProfileControllerTest {
for (int i = 0; i < 900; i++) {
largeElementList.add(
new BatchIdentityCheckRequest.Element(new AciServiceIdentifier(UUID.randomUUID()),
convertKeyToFingerprint(new IdentityKey(Curve.generateKeyPair().getPublicKey()))));
convertKeyToFingerprint(new IdentityKey(ECKeyPair.generate().getPublicKey()))));
}
try (final Response response = resources.getJerseyTest().target("/v1/profile/identity_check/batch").request()
@@ -1444,9 +1444,9 @@ class ProfileControllerTest {
{ "uuid": "%s", "fingerprint": "%s" }
]
}
""", AuthHelper.VALID_UUID, Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(Curve.generateKeyPair().getPublicKey()))),
"PNI:" + AuthHelper.VALID_PNI_TWO, Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(Curve.generateKeyPair().getPublicKey()))),
AuthHelper.INVALID_UUID, Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(Curve.generateKeyPair().getPublicKey()))));
""", AuthHelper.VALID_UUID, Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(ECKeyPair.generate().getPublicKey()))),
"PNI:" + AuthHelper.VALID_PNI_TWO, Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(ECKeyPair.generate().getPublicKey()))),
AuthHelper.INVALID_UUID, Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(ECKeyPair.generate().getPublicKey()))));
try (final Response response = resources.getJerseyTest().target("/v1/profile/identity_check/batch").request()
.post(Entity.entity(json, "application/json"))) {
@@ -1505,7 +1505,7 @@ class ProfileControllerTest {
{ "uuid": null, "fingerprint": "%s" }
]
}
""", Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(Curve.generateKeyPair().getPublicKey())))),
""", Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(ECKeyPair.generate().getPublicKey())))),
422),
Arguments.of( // a blank string is invalid
String.format("""
@@ -1514,7 +1514,7 @@ class ProfileControllerTest {
{ "uuid": " ", "fingerprint": "%s" }
]
}
""", Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(Curve.generateKeyPair().getPublicKey())))),
""", Base64.getEncoder().encodeToString(convertKeyToFingerprint(new IdentityKey(ECKeyPair.generate().getPublicKey())))),
400)
);
}
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -32,6 +31,7 @@ import java.util.Base64;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -54,7 +54,6 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.ArgumentSets;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
@@ -519,7 +518,7 @@ class RegistrationControllerTest {
}
}
static Stream<Arguments> atomicAccountCreationConflictingChannel() {
static List<Arguments> atomicAccountCreationConflictingChannel() {
final IdentityKey aciIdentityKey;
final IdentityKey pniIdentityKey;
final ECSignedPreKey aciSignedPreKey;
@@ -527,8 +526,8 @@ class RegistrationControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
{
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
@@ -544,48 +543,48 @@ class RegistrationControllerTest {
final AccountAttributes pushAccountAttributes =
new AccountAttributes(false, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true, Set.of());
return Stream.of(
// "Fetches messages" is true, but an APNs token is provided
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId("apns-token")),
Optional.empty())),
return List.of(
Arguments.argumentSet("\"Fetches messages\" is true, but an APNs token is provided",
new RegistrationRequest("session-id",
new byte[0],
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId("apns-token")),
Optional.empty()))),
// "Fetches messages" is true, but an FCM (GCM) token is provided
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.of(new GcmRegistrationId("gcm-token")))),
Arguments.argumentSet("\"Fetches messages\" is true, but an FCM (GCM) token is provided",
new RegistrationRequest("session-id",
new byte[0],
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.of(new GcmRegistrationId("gcm-token"))))),
// "Fetches messages" is false, but multiple types of push tokens are provided
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
pushAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId("apns-token")),
Optional.of(new GcmRegistrationId("gcm-token"))))
Arguments.argumentSet("\"Fetches messages\" is false, but multiple types of push tokens are provided",
new RegistrationRequest("session-id",
new byte[0],
pushAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId("apns-token")),
Optional.of(new GcmRegistrationId("gcm-token")))))
);
}
@@ -608,7 +607,7 @@ class RegistrationControllerTest {
}
}
static Stream<Arguments> atomicAccountCreationPartialSignedPreKeys() {
static List<Arguments> atomicAccountCreationPartialSignedPreKeys() {
final IdentityKey aciIdentityKey;
final IdentityKey pniIdentityKey;
final ECSignedPreKey aciSignedPreKey;
@@ -616,8 +615,8 @@ class RegistrationControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
{
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
@@ -630,90 +629,90 @@ class RegistrationControllerTest {
final AccountAttributes accountAttributes =
new AccountAttributes(true, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true, Set.of());
return Stream.of(
// Signed PNI EC pre-key is missing
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
null,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty())),
return List.of(
Arguments.argumentSet("Signed PNI EC pre-key is missing",
new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
null,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty()))),
// Signed ACI EC pre-key is missing
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
null,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty())),
Arguments.argumentSet("Signed ACI EC pre-key is missing",
new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(null,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty()))),
// Signed PNI KEM pre-key is missing
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
null,
Optional.empty(),
Optional.empty())),
Arguments.argumentSet("Signed PNI KEM pre-key is missing",
new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
null,
Optional.empty(),
Optional.empty()))),
// Signed ACI KEM pre-key is missing
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
null,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty())),
Arguments.argumentSet("Signed ACI KEM pre-key is missing",
new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
null,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty()))),
// All signed pre-keys are present, but ACI identity key is missing
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
null,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty())),
Arguments.argumentSet("All signed pre-keys are present, but ACI identity key is missing",
new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
null,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty()))),
// All signed pre-keys are present, but PNI identity key is missing
Arguments.of(new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
null,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty()))
Arguments.argumentSet("All signed pre-keys are present, but PNI identity key is missing",
new RegistrationRequest("session-id",
new byte[0],
accountAttributes,
true,
aciIdentityKey,
null,
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty())))
);
}
@@ -789,7 +788,7 @@ class RegistrationControllerTest {
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
assertEquals(200, response.getStatus());
final AccountCreationResponse creationResponse = response.readEntity(AccountCreationResponse.class);
assertEquals(existingAccount, creationResponse.isReregistration());
assertEquals(existingAccount, creationResponse.reregistration());
}
}
@@ -806,7 +805,7 @@ class RegistrationControllerTest {
&& Objects.equals(a.recoveryPassword(), b.recoveryPassword());
}
private static Stream<Arguments> atomicAccountCreationSuccess() {
private static List<Arguments> atomicAccountCreationSuccess() {
final IdentityKey aciIdentityKey;
final IdentityKey pniIdentityKey;
final ECSignedPreKey aciSignedPreKey;
@@ -814,8 +813,8 @@ class RegistrationControllerTest {
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
{
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
@@ -840,20 +839,20 @@ class RegistrationControllerTest {
final String apnsToken = "apns-token";
final String gcmToken = "gcm-token";
return Stream.of(
// Fetches messages; no push tokens
Arguments.of(new RegistrationRequest("session-id",
return List.of(
Arguments.argumentSet("Fetches messages; no push tokens",
new RegistrationRequest("session-id",
new byte[0],
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty()),
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.empty())),
aciIdentityKey,
pniIdentityKey,
new DeviceSpec(
@@ -871,19 +870,19 @@ class RegistrationControllerTest {
aciPqLastResortPreKey,
pniPqLastResortPreKey)),
// Has APNs tokens
Arguments.of(new RegistrationRequest("session-id",
Arguments.argumentSet("Has APNs tokens",
new RegistrationRequest("session-id",
new byte[0],
pushAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId(apnsToken)),
Optional.empty()),
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.of(new ApnRegistrationId(apnsToken)),
Optional.empty())),
aciIdentityKey,
pniIdentityKey,
new DeviceSpec(
@@ -901,19 +900,19 @@ class RegistrationControllerTest {
aciPqLastResortPreKey,
pniPqLastResortPreKey)),
// Has GCM token
Arguments.of(new RegistrationRequest("session-id",
Arguments.argumentSet("Has GCM token",
new RegistrationRequest("session-id",
new byte[0],
pushAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.of(new GcmRegistrationId(gcmToken))),
new DeviceActivationRequest(aciSignedPreKey,
pniSignedPreKey,
aciPqLastResortPreKey,
pniPqLastResortPreKey,
Optional.empty(),
Optional.of(new GcmRegistrationId(gcmToken)))),
aciIdentityKey,
pniIdentityKey,
new DeviceSpec(
@@ -942,8 +941,8 @@ class RegistrationControllerTest {
final int registrationId,
int pniRegistrationId) {
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
final IdentityKey pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
@@ -965,7 +964,6 @@ class RegistrationControllerTest {
KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair),
Optional.empty(),
Optional.empty()));
try {
return SystemMapper.jsonMapper().writerWithDefaultPrettyPrinter().writeValueAsString(request);
} catch (final JsonProcessingException e) {
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
@@ -16,32 +17,36 @@ import static org.mockito.Mockito.when;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.InstanceOfAssertFactory;
import org.assertj.core.data.Offset;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.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.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.params.IntRangeSource;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfig;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@ExtendWith(DropwizardExtensionsSupport.class)
class RemoteConfigControllerTest {
@@ -63,20 +68,19 @@ class RemoteConfigControllerTest {
@BeforeEach
void setup() throws Exception {
when(remoteConfigsManager.getAll()).thenReturn(new LinkedList<>() {{
add(new RemoteConfig("android.stickers", 25, Set.of(AuthHelper.VALID_UUID_3, AuthHelper.INVALID_UUID), null,
null, null));
add(new RemoteConfig("ios.stickers", 50, Set.of(), null, null, null));
add(new RemoteConfig("always.true", 100, Set.of(), null, null, null));
add(new RemoteConfig("only.special", 0, Set.of(AuthHelper.VALID_UUID), null, null, null));
add(new RemoteConfig("value.always.true", 100, Set.of(), "foo", "bar", null));
add(new RemoteConfig("value.only.special", 0, Set.of(AuthHelper.VALID_UUID), "abc", "xyz", null));
add(new RemoteConfig("value.always.false", 0, Set.of(), "red", "green", null));
add(new RemoteConfig("linked.config.0", 50, Set.of(), null, null, null));
add(new RemoteConfig("linked.config.1", 50, Set.of(), null, null, "linked.config.0"));
add(new RemoteConfig("unlinked.config", 50, Set.of(), null, null, null));
}});
when(remoteConfigsManager.getAll()).thenReturn(
List.of(
new RemoteConfig("android.stickers", 100, Set.of(), null, null, null),
new RemoteConfig("ios.stickers", 100, Set.of(), null, null, null),
new RemoteConfig("desktop.stickers", 100, Set.of(), null, null, null),
new RemoteConfig("always.true", 100, Set.of(), null, null, null),
new RemoteConfig("only.special", 0, Set.of(AuthHelper.VALID_UUID), null, null, null),
new RemoteConfig("value.always.true", 100, Set.of(), "foo", "bar", null),
new RemoteConfig("value.only.special", 0, Set.of(AuthHelper.VALID_UUID), "abc", "xyz", null),
new RemoteConfig("value.always.false", 0, Set.of(), "red", "green", null),
new RemoteConfig("linked.config.0", 50, Set.of(), null, null, null),
new RemoteConfig("linked.config.1", 50, Set.of(), null, null, "linked.config.0"),
new RemoteConfig("unlinked.config", 50, Set.of(), null, null, null)));
}
@AfterEach
@@ -84,119 +88,100 @@ class RemoteConfigControllerTest {
reset(remoteConfigsManager);
}
@Test
void testRetrieveConfig() {
UserRemoteConfigList configuration = resources.getJerseyTest()
.target("/v1/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(UserRemoteConfigList.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.getConfig()).hasSize(11);
assertThat(configuration.getConfig().get(0).getName()).isEqualTo("android.stickers");
assertThat(configuration.getConfig().get(1).getName()).isEqualTo("ios.stickers");
assertThat(configuration.getConfig().get(2).getName()).isEqualTo("always.true");
assertThat(configuration.getConfig().get(2).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(3).getName()).isEqualTo("only.special");
assertThat(configuration.getConfig().get(3).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(4).getName()).isEqualTo("value.always.true");
assertThat(configuration.getConfig().get(4).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(4).getValue()).isEqualTo("bar");
assertThat(configuration.getConfig().get(5).getName()).isEqualTo("value.only.special");
assertThat(configuration.getConfig().get(5).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(5).getValue()).isEqualTo("xyz");
assertThat(configuration.getConfig().get(6).getName()).isEqualTo("value.always.false");
assertThat(configuration.getConfig().get(6).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(6).getValue()).isEqualTo("red");
assertThat(configuration.getConfig().get(7).getName()).isEqualTo("linked.config.0");
assertThat(configuration.getConfig().get(8).getName()).isEqualTo("linked.config.1");
assertThat(configuration.getConfig().get(9).getName()).isEqualTo("unlinked.config");
assertThat(configuration.getConfig().get(10).getName()).isEqualTo("global.maxGroupSize");
}
@Test
void testServerEpochTime() {
Object serverEpochTime = resources.getJerseyTest()
.target("/v1/config/")
@ParameterizedTest
@EnumSource
void testRetrieveConfig(ClientPlatform platform) {
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(Map.class)
.get("serverEpochTime");
assertThat(serverEpochTime).asInstanceOf(new InstanceOfAssertFactory<>(Number.class, Assertions::assertThat))
.extracting(Number::longValue)
.isEqualTo(PINNED_EPOCH_SECONDS);
}
@Test
void testRetrieveConfigNotSpecial() {
UserRemoteConfigList configuration = resources.getJerseyTest()
.target("/v1/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.get(UserRemoteConfigList.class);
.header("User-Agent", String.format("Signal-%s/7.6.2", platform.name()))
.get(RemoteConfigurationResponse.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.getConfig()).hasSize(11);
assertThat(configuration.getConfig().get(0).getName()).isEqualTo("android.stickers");
assertThat(configuration.getConfig().get(1).getName()).isEqualTo("ios.stickers");
assertThat(configuration.getConfig().get(2).getName()).isEqualTo("always.true");
assertThat(configuration.getConfig().get(2).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(3).getName()).isEqualTo("only.special");
assertThat(configuration.getConfig().get(3).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(4).getName()).isEqualTo("value.always.true");
assertThat(configuration.getConfig().get(4).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(4).getValue()).isEqualTo("bar");
assertThat(configuration.getConfig().get(5).getName()).isEqualTo("value.only.special");
assertThat(configuration.getConfig().get(5).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(5).getValue()).isEqualTo("abc");
assertThat(configuration.getConfig().get(6).getName()).isEqualTo("value.always.false");
assertThat(configuration.getConfig().get(6).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(6).getValue()).isEqualTo("red");
assertThat(configuration.getConfig().get(7).getName()).isEqualTo("linked.config.0");
assertThat(configuration.getConfig().get(8).getName()).isEqualTo("linked.config.1");
assertThat(configuration.getConfig().get(9).getName()).isEqualTo("unlinked.config");
assertThat(configuration.getConfig().get(10).getName()).isEqualTo("global.maxGroupSize");
assertThat(configuration.config()).hasSize(10);
assertThat(configuration.config()).containsKeys(platform.name().toLowerCase() + ".stickers", "linked.config.0", "linked.config.1", "unlinked.config");
assertThat(configuration.config()).contains(
entry("always.true", "true"),
entry("only.special", "true"),
entry("value.always.true", "bar"),
entry("value.only.special", "xyz"),
entry("value.always.false", "red"),
entry("global.maxGroupSize", "42"));
}
@ParameterizedTest
@EnumSource
void testRetrieveConfigNotSpecial(ClientPlatform platform) {
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.header("User-Agent", String.format("Signal-%s/7.6.2", platform.name()))
.get(RemoteConfigurationResponse.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.config()).hasSize(10);
assertThat(configuration.config()).containsKeys(platform.name().toLowerCase() + ".stickers", "linked.config.0", "linked.config.1", "unlinked.config");
assertThat(configuration.config()).contains(
entry("always.true", "true"),
entry("only.special", "false"),
entry("value.always.true", "bar"),
entry("value.only.special", "abc"),
entry("value.always.false", "red"),
entry("global.maxGroupSize", "42"));
}
@Test
void testRetrieveConfigUnrecognizedPlatform() {
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.header("User-Agent", "Third-Party-Signal-Client/1.0.0")
.get(RemoteConfigurationResponse.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.config()).hasSize(9);
assertThat(configuration.config()).containsKeys("linked.config.0", "linked.config.1", "unlinked.config");
assertThat(configuration.config()).contains(
entry("always.true", "true"),
entry("only.special", "false"),
entry("value.always.true", "bar"),
entry("value.only.special", "abc"),
entry("value.always.false", "red"),
entry("global.maxGroupSize", "42"));
}
@Test
void testHashKeyLinkedConfigs() {
boolean allUnlinkedConfigsMatched = true;
for (AuthHelper.TestAccount testAccount : AuthHelper.TEST_ACCOUNTS) {
UserRemoteConfigList configuration = resources.getJerseyTest()
.target("/v1/config/")
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", testAccount.getAuthHeader())
.get(UserRemoteConfigList.class);
.get(RemoteConfigurationResponse.class);
assertThat(configuration.getConfig()).hasSize(11);
final UserRemoteConfig linkedConfig0 = configuration.getConfig().get(7);
assertThat(linkedConfig0.getName()).isEqualTo("linked.config.0");
final UserRemoteConfig linkedConfig1 = configuration.getConfig().get(8);
assertThat(linkedConfig1.getName()).isEqualTo("linked.config.1");
final UserRemoteConfig unlinkedConfig = configuration.getConfig().get(9);
assertThat(unlinkedConfig.getName()).isEqualTo("unlinked.config");
assertThat(linkedConfig0.isEnabled() == linkedConfig1.isEnabled()).isTrue();
allUnlinkedConfigsMatched &= (linkedConfig0.isEnabled() == unlinkedConfig.isEnabled());
assertThat(configuration.config().get("linked.config.0")).isEqualTo(configuration.config().get("linked.config.1"));
allUnlinkedConfigsMatched &= (configuration.config().get("linked.config.0") == configuration.config().get("unlinked.config"));
}
// with 20 test accounts, 1 in 2^20 chance that this fails when it shouldn't, but
// AuthHelper#generateTestAccounts uses a constant random seed that doesn't fail as of the time
// of this writing; if this starts failing for no apparent reason, it's likely that we've
// changed the order of the sequence of random numbers used during test initialization in such
// a way that we've accidentally picked an unlucky set of accounts here
assertThat(allUnlinkedConfigsMatched).isFalse();
}
@Test
void testRetrieveConfigUnauthorized() {
Response response = resources.getJerseyTest()
.target("/v1/config/")
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.INVALID_PASSWORD))
.get();
@@ -207,32 +192,155 @@ class RemoteConfigControllerTest {
}
@Test
void testMath() throws NoSuchAlgorithmException {
List<RemoteConfig> remoteConfigList = remoteConfigsManager.getAll();
Map<String, Integer> enabledMap = new HashMap<>();
MessageDigest digest = MessageDigest.getInstance("SHA1");
int iterations = 100000;
Random random = new Random(9424242L); // the seed value doesn't matter so much as it's constant to make the test not flaky
void testRetrieveConfigUnchanged() {
Response response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/7.6.2 Android/34 libsignal/0.46.0")
.get();
for (int i=0;i<iterations;i++) {
for (RemoteConfig config : remoteConfigList) {
int count = enabledMap.getOrDefault(config.getName(), 0);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getLength()).isPositive();
final EntityTag etag = response.getEntityTag();
assertThat(etag).isNotNull();
if (RemoteConfigController.isInBucket(digest, AuthHelper.getRandomUUID(random), config.getName().getBytes(), config.getPercentage(), new HashSet<>())) {
count++;
}
response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/7.6.2 Android/34 libsignal/0.46.0")
.header("If-None-Match", etag)
.get();
enabledMap.put(config.getName(), count);
}
}
assertThat(response.getStatus()).isEqualTo(304);
assertThat(response.getLength()).isNotPositive();
}
for (RemoteConfig config : remoteConfigList) {
double targetNumber = iterations * (config.getPercentage() / 100.0);
double variance = targetNumber * 0.01;
@Test
void testRetrieveConfigChanged() {
Response response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/7.6.2 Android/34 libsignal/0.46.0")
.get();
assertThat(enabledMap.get(config.getName())).isBetween((int) (targetNumber - variance),
(int) (targetNumber + variance));
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getLength()).isPositive();
final EntityTag etag = response.getEntityTag();
assertThat(etag).isNotNull();
final List<RemoteConfig> configs = new ArrayList<>(remoteConfigsManager.getAll());
configs.add(new RemoteConfig("android.new.config", 100, Set.of(), null, null, null));
when(remoteConfigsManager.getAll()).thenReturn(configs);
response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/7.6.2 Android/34 libsignal/0.46.0")
.header("If-None-Match", etag)
.get();
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getLength()).isPositive();
}
@ParameterizedTest
@MethodSource
void testEtag(boolean expect304, String userAgent1, String authHeader1, String userAgent2, String authHeader2) {
// Use a deterministic config; account 1 is special, 2 and 3 are identical
List<RemoteConfig> configs = remoteConfigsManager.getAll().stream().filter(config -> config.getPercentage() == 0 || config.getPercentage() == 100).toList();
when(remoteConfigsManager.getAll()).thenReturn(configs);
Response response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", authHeader1)
.header("User-Agent", userAgent1)
.get();
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getLength()).isPositive();
final EntityTag etag = response.getEntityTag();
assertThat(etag).isNotNull();
response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", authHeader2)
.header("User-Agent", userAgent2)
.header("If-None-Match", etag)
.get();
if (expect304) {
assertThat(response.getStatus()).isEqualTo(304);
assertThat(response.getLength()).isNotPositive();
} else {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getLength()).isPositive();
}
}
static List<Arguments> testEtag() {
final String uuid1AuthHeader = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD);
final String uuid2AuthHeader = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO);
final String uuid3AuthHeader = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_3, AuthHelper.VALID_PASSWORD_3_PRIMARY);
final String ios762 = "Signal-iOS/7.6.2 iOS/18.5 libsignal/0.46.0";
final String android762 = "Signal-Android/7.6.2 Android/34 libsignal/0.46.0";
final String android763 = "Signal-Android/7.6.3 Android/34 libsignal/0.46.0";
// boolean is expect304
return List.of(
Arguments.argumentSet("User change", false, android762, uuid1AuthHeader, android762, uuid2AuthHeader),
Arguments.argumentSet("Irrelevant user change", true, android762, uuid2AuthHeader, android762, uuid3AuthHeader),
Arguments.argumentSet("User agent change", false, android762, uuid1AuthHeader, ios762, uuid1AuthHeader),
Arguments.argumentSet("Irrelevant user agent change", true, android762, uuid1AuthHeader, android763, uuid1AuthHeader)
);
}
@ParameterizedTest
@IntRangeSource(from = 1, to = 99)
void testMath(int percentage) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Random random = new Random(9424242L); // the seed value doesn't matter so much as it's constant to make the test not flaky
final int iterations = 10000;
int enabledCount = 0;
for (int i = 0; i < iterations; i++) {
if (RemoteConfigController.isInBucket(digest, AuthHelper.getRandomUUID(random), "test".getBytes(), percentage, Set.of())) {
enabledCount++;
}
}
// https://en.wikipedia.org/wiki/Binomial_distribution#Expected_value_and_variance
final double expectedCount = iterations * percentage / 100.0;
final double stdev = Math.sqrt(expectedCount * (1 - percentage / 100.0));
// 3 standard deviations = 99.73% chance of success for one bucket, 23.5%
// chance of any failure in 99 buckets; if this starts failing after a
// change, run it again with a few different random seeds to make sure it
// fails only about on about one seed in four
assertThat((double) enabledCount).isCloseTo(expectedCount, Offset.offset(3 * stdev));
}
@ParameterizedTest
@ValueSource(ints = {0, 100})
void testMathExactForZeroOrOneHundred(int percentage) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Random random = new Random();
final int iterations = 10000;
int enabledCount = 0;
for (int i = 0; i < iterations; i++) {
if (RemoteConfigController.isInBucket(digest, AuthHelper.getRandomUUID(random), "test".getBytes(), percentage, Set.of())) {
enabledCount++;
}
}
assertThat(enabledCount).isEqualTo(iterations * percentage / 100);
}
}
@@ -0,0 +1,238 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.InstanceOfAssertFactory;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfig;
import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
@ExtendWith(DropwizardExtensionsSupport.class)
class RemoteConfigControllerV1Test {
private static final RemoteConfigsManager remoteConfigsManager = mock(RemoteConfigsManager.class);
private static final long PINNED_EPOCH_SECONDS = 1701287216L;
private static final TestClock TEST_CLOCK = TestClock.pinned(Instant.ofEpochSecond(PINNED_EPOCH_SECONDS));
private static final ResourceExtension resources = ResourceExtension.builder()
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addProvider(new DeviceLimitExceededExceptionMapper())
.addResource(new RemoteConfigControllerV1(remoteConfigsManager, Map.of("maxGroupSize", "42"), TEST_CLOCK))
.build();
@BeforeEach
void setup() throws Exception {
when(remoteConfigsManager.getAll()).thenReturn(new LinkedList<>() {{
add(new RemoteConfig("android.stickers", 25, Set.of(AuthHelper.VALID_UUID_3, AuthHelper.INVALID_UUID), null,
null, null));
add(new RemoteConfig("ios.stickers", 50, Set.of(), null, null, null));
add(new RemoteConfig("always.true", 100, Set.of(), null, null, null));
add(new RemoteConfig("only.special", 0, Set.of(AuthHelper.VALID_UUID), null, null, null));
add(new RemoteConfig("value.always.true", 100, Set.of(), "foo", "bar", null));
add(new RemoteConfig("value.only.special", 0, Set.of(AuthHelper.VALID_UUID), "abc", "xyz", null));
add(new RemoteConfig("value.always.false", 0, Set.of(), "red", "green", null));
add(new RemoteConfig("linked.config.0", 50, Set.of(), null, null, null));
add(new RemoteConfig("linked.config.1", 50, Set.of(), null, null, "linked.config.0"));
add(new RemoteConfig("unlinked.config", 50, Set.of(), null, null, null));
}});
}
@AfterEach
void teardown() {
reset(remoteConfigsManager);
}
@Test
void testRetrieveConfig() {
UserRemoteConfigList configuration = resources.getJerseyTest()
.target("/v1/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(UserRemoteConfigList.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.getConfig()).hasSize(11);
assertThat(configuration.getConfig().get(0).getName()).isEqualTo("android.stickers");
assertThat(configuration.getConfig().get(1).getName()).isEqualTo("ios.stickers");
assertThat(configuration.getConfig().get(2).getName()).isEqualTo("always.true");
assertThat(configuration.getConfig().get(2).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(3).getName()).isEqualTo("only.special");
assertThat(configuration.getConfig().get(3).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(4).getName()).isEqualTo("value.always.true");
assertThat(configuration.getConfig().get(4).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(4).getValue()).isEqualTo("bar");
assertThat(configuration.getConfig().get(5).getName()).isEqualTo("value.only.special");
assertThat(configuration.getConfig().get(5).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(5).getValue()).isEqualTo("xyz");
assertThat(configuration.getConfig().get(6).getName()).isEqualTo("value.always.false");
assertThat(configuration.getConfig().get(6).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(6).getValue()).isEqualTo("red");
assertThat(configuration.getConfig().get(7).getName()).isEqualTo("linked.config.0");
assertThat(configuration.getConfig().get(8).getName()).isEqualTo("linked.config.1");
assertThat(configuration.getConfig().get(9).getName()).isEqualTo("unlinked.config");
assertThat(configuration.getConfig().get(10).getName()).isEqualTo("global.maxGroupSize");
}
@Test
void testServerEpochTime() {
Object serverEpochTime = resources.getJerseyTest()
.target("/v1/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(Map.class)
.get("serverEpochTime");
assertThat(serverEpochTime).asInstanceOf(new InstanceOfAssertFactory<>(Number.class, Assertions::assertThat))
.extracting(Number::longValue)
.isEqualTo(PINNED_EPOCH_SECONDS);
}
@Test
void testRetrieveConfigNotSpecial() {
UserRemoteConfigList configuration = resources.getJerseyTest()
.target("/v1/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.get(UserRemoteConfigList.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.getConfig()).hasSize(11);
assertThat(configuration.getConfig().get(0).getName()).isEqualTo("android.stickers");
assertThat(configuration.getConfig().get(1).getName()).isEqualTo("ios.stickers");
assertThat(configuration.getConfig().get(2).getName()).isEqualTo("always.true");
assertThat(configuration.getConfig().get(2).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(3).getName()).isEqualTo("only.special");
assertThat(configuration.getConfig().get(3).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(2).getValue()).isNull();
assertThat(configuration.getConfig().get(4).getName()).isEqualTo("value.always.true");
assertThat(configuration.getConfig().get(4).isEnabled()).isEqualTo(true);
assertThat(configuration.getConfig().get(4).getValue()).isEqualTo("bar");
assertThat(configuration.getConfig().get(5).getName()).isEqualTo("value.only.special");
assertThat(configuration.getConfig().get(5).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(5).getValue()).isEqualTo("abc");
assertThat(configuration.getConfig().get(6).getName()).isEqualTo("value.always.false");
assertThat(configuration.getConfig().get(6).isEnabled()).isEqualTo(false);
assertThat(configuration.getConfig().get(6).getValue()).isEqualTo("red");
assertThat(configuration.getConfig().get(7).getName()).isEqualTo("linked.config.0");
assertThat(configuration.getConfig().get(8).getName()).isEqualTo("linked.config.1");
assertThat(configuration.getConfig().get(9).getName()).isEqualTo("unlinked.config");
assertThat(configuration.getConfig().get(10).getName()).isEqualTo("global.maxGroupSize");
}
@Test
void testHashKeyLinkedConfigs() {
boolean allUnlinkedConfigsMatched = true;
for (AuthHelper.TestAccount testAccount : AuthHelper.TEST_ACCOUNTS) {
UserRemoteConfigList configuration = resources.getJerseyTest()
.target("/v1/config/")
.request()
.header("Authorization", testAccount.getAuthHeader())
.get(UserRemoteConfigList.class);
assertThat(configuration.getConfig()).hasSize(11);
final UserRemoteConfig linkedConfig0 = configuration.getConfig().get(7);
assertThat(linkedConfig0.getName()).isEqualTo("linked.config.0");
final UserRemoteConfig linkedConfig1 = configuration.getConfig().get(8);
assertThat(linkedConfig1.getName()).isEqualTo("linked.config.1");
final UserRemoteConfig unlinkedConfig = configuration.getConfig().get(9);
assertThat(unlinkedConfig.getName()).isEqualTo("unlinked.config");
assertThat(linkedConfig0.isEnabled() == linkedConfig1.isEnabled()).isTrue();
allUnlinkedConfigsMatched &= (linkedConfig0.isEnabled() == unlinkedConfig.isEnabled());
}
assertThat(allUnlinkedConfigsMatched).isFalse();
}
@Test
void testRetrieveConfigUnauthorized() {
Response response = resources.getJerseyTest()
.target("/v1/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.INVALID_PASSWORD))
.get();
assertThat(response.getStatus()).isEqualTo(401);
verifyNoMoreInteractions(remoteConfigsManager);
}
@Test
void testMath() throws NoSuchAlgorithmException {
List<RemoteConfig> remoteConfigList = remoteConfigsManager.getAll();
Map<String, Integer> enabledMap = new HashMap<>();
MessageDigest digest = MessageDigest.getInstance("SHA256");
int iterations = 100000;
Random random = new Random(9424242L); // the seed value doesn't matter so much as it's constant to make the test not flaky
for (int i=0;i<iterations;i++) {
for (RemoteConfig config : remoteConfigList) {
int count = enabledMap.getOrDefault(config.getName(), 0);
if (RemoteConfigControllerV1.isInBucket(digest, AuthHelper.getRandomUUID(random), config.getName().getBytes(), config.getPercentage(), new HashSet<>())) {
count++;
}
enabledMap.put(config.getName(), count);
}
}
for (RemoteConfig config : remoteConfigList) {
double targetNumber = iterations * (config.getPercentage() / 100.0);
double variance = targetNumber * 0.01;
assertThat(enabledMap.get(config.getName())).isBetween((int) (targetNumber - variance),
(int) (targetNumber + variance));
}
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.entities;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Clock;
import java.util.UUID;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
@@ -75,7 +76,8 @@ class OutgoingMessageEntityTest {
false,
false,
true,
reportSpamToken);
reportSpamToken,
Clock.systemUTC());
MessageProtos.Envelope envelope = baseEnvelope.toBuilder().setServerGuid(UUID.randomUUID().toString()).build();
@@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Flux;
@@ -66,37 +67,37 @@ abstract class IdleDevicePushNotificationExperimentTest {
assertEquals(DeviceLastSeenState.MISSING_DEVICE_STATE, experiment.getState(null, null));
assertEquals(DeviceLastSeenState.MISSING_DEVICE_STATE, experiment.getState(mock(Account.class), null));
final long createdAtMillis = CURRENT_TIME.minus(Duration.ofDays(14)).toEpochMilli();
final int registrationId = 123;
{
final Device apnsDevice = mock(Device.class);
when(apnsDevice.getApnId()).thenReturn("apns-token");
when(apnsDevice.getCreated()).thenReturn(createdAtMillis);
when(apnsDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
when(apnsDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
assertEquals(
new DeviceLastSeenState(true, createdAtMillis, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.APNS),
new DeviceLastSeenState(true, registrationId, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.APNS),
experiment.getState(mock(Account.class), apnsDevice));
}
{
final Device fcmDevice = mock(Device.class);
when(fcmDevice.getGcmId()).thenReturn("fcm-token");
when(fcmDevice.getCreated()).thenReturn(createdAtMillis);
when(fcmDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
when(fcmDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
assertEquals(
new DeviceLastSeenState(true, createdAtMillis, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.FCM),
new DeviceLastSeenState(true, registrationId, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.FCM),
experiment.getState(mock(Account.class), fcmDevice));
}
{
final Device noTokenDevice = mock(Device.class);
when(noTokenDevice.getCreated()).thenReturn(createdAtMillis);
when(noTokenDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
when(noTokenDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
assertEquals(
new DeviceLastSeenState(true, createdAtMillis, false, CURRENT_TIME.toEpochMilli(), null),
new DeviceLastSeenState(true, registrationId, false, CURRENT_TIME.toEpochMilli(), null),
experiment.getState(mock(Account.class), noTokenDevice));
}
}
@@ -150,10 +151,10 @@ abstract class IdleDevicePushNotificationExperimentTest {
IdleDevicePushNotificationExperiment.Outcome.DELETED
),
// Device re-registered (i.e. "created" timestamp changed)
// Device re-registered (i.e. registration ID changed)
Arguments.of(
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS),
new DeviceLastSeenState(true, 1, true, 1, DeviceLastSeenState.PushTokenType.APNS),
new DeviceLastSeenState(true, 123, true, 0, DeviceLastSeenState.PushTokenType.APNS),
new DeviceLastSeenState(true, 1234, true, 1, DeviceLastSeenState.PushTokenType.APNS),
IdleDevicePushNotificationExperiment.Outcome.DELETED
),
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@@ -17,6 +18,7 @@ import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.time.Clock;
import java.util.Arrays;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -26,8 +28,14 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
import org.signal.chat.backup.BackupsAnonymousGrpc;
@@ -46,7 +54,7 @@ import org.signal.chat.backup.ListMediaRequest;
import org.signal.chat.backup.ListMediaResponse;
import org.signal.chat.backup.SetPublicKeyRequest;
import org.signal.chat.backup.SignedPresentation;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
@@ -56,6 +64,7 @@ import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@@ -89,7 +98,7 @@ class BackupsAnonymousGrpcServiceTest extends
void setPublicKey() {
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
assertThatNoException().isThrownBy(() -> unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
.setPublicKey(ByteString.copyFrom(ECKeyPair.generate().getPublicKey().serialize()))
.setSignedPresentation(signedPresentation(presentation))
.build()));
}
@@ -294,6 +303,42 @@ class BackupsAnonymousGrpcServiceTest extends
.isEqualTo(Status.RESOURCE_EXHAUSTED);
}
static Stream<Arguments> messagesUploadForm() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE), true),
Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false)
);
}
@ParameterizedTest
@MethodSource
public void messagesUploadForm(Optional<Long> uploadLength, boolean expectSuccess) {
when(backupManager.createMessageBackupUploadDescriptor(any()))
.thenReturn(CompletableFuture.completedFuture(
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
final GetUploadFormRequest.MessagesUploadType.Builder builder = GetUploadFormRequest.MessagesUploadType.newBuilder();
uploadLength.ifPresent(builder::setUploadLength);
final GetUploadFormRequest request = GetUploadFormRequest.newBuilder()
.setMessages(builder.build())
.setSignedPresentation(signedPresentation(presentation))
.build();
if (expectSuccess) {
final GetUploadFormResponse uploadForm = unauthenticatedServiceStub().getUploadForm(request);
assertThat(uploadForm.getCdn()).isEqualTo(3);
assertThat(uploadForm.getKey()).isEqualTo("abc");
assertThat(uploadForm.getHeadersMap()).containsExactlyEntriesOf(Map.of("k", "v"));
assertThat(uploadForm.getSignedUploadLocation()).isEqualTo("example.org");
} else {
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> unauthenticatedServiceStub().getUploadForm(request))
.extracting(StatusRuntimeException::getStatus)
.extracting(Status::getCode)
.isEqualTo(Status.FAILED_PRECONDITION.getCode());
}
}
@Test
void readAuth() {
when(backupManager.generateReadAuth(any(), eq(3))).thenReturn(Map.of("key", "value"));
@@ -48,6 +48,7 @@ import org.signal.chat.device.SetDeviceNameRequest;
import org.signal.chat.device.SetDeviceNameResponse;
import org.signal.chat.device.SetPushTokenRequest;
import org.signal.chat.device.SetPushTokenResponse;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -102,11 +103,17 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
final Instant primaryDeviceLastSeen = primaryDeviceCreated.plus(Duration.ofHours(6));
final Instant linkedDeviceCreated = Instant.now().minus(Duration.ofDays(1)).truncatedTo(ChronoUnit.MILLIS);
final Instant linkedDeviceLastSeen = linkedDeviceCreated.plus(Duration.ofHours(7));
final int primaryRegistrationId = 1234;
final int linkedRegistrationId = 1235;
final byte[] primaryCreatedAtCiphertext = "primary_timestamp_ciphertext".getBytes(StandardCharsets.UTF_8);
final byte[] linkedCreatedAtCiphertext = "linked_timestamp_ciphertext".getBytes(StandardCharsets.UTF_8);
final Device primaryDevice = mock(Device.class);
when(primaryDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(primaryDevice.getCreated()).thenReturn(primaryDeviceCreated.toEpochMilli());
when(primaryDevice.getLastSeen()).thenReturn(primaryDeviceLastSeen.toEpochMilli());
when(primaryDevice.getRegistrationId(IdentityType.ACI)).thenReturn(primaryRegistrationId);
when(primaryDevice.getCreatedAtCiphertext()).thenReturn(primaryCreatedAtCiphertext);
final String linkedDeviceName = "A linked device";
@@ -115,6 +122,8 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
when(linkedDevice.getCreated()).thenReturn(linkedDeviceCreated.toEpochMilli());
when(linkedDevice.getLastSeen()).thenReturn(linkedDeviceLastSeen.toEpochMilli());
when(linkedDevice.getName()).thenReturn(linkedDeviceName.getBytes(StandardCharsets.UTF_8));
when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedRegistrationId);
when(linkedDevice.getCreatedAtCiphertext()).thenReturn(linkedCreatedAtCiphertext);
when(authenticatedAccount.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice));
@@ -123,12 +132,16 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
.setId(Device.PRIMARY_ID)
.setCreated(primaryDeviceCreated.toEpochMilli())
.setLastSeen(primaryDeviceLastSeen.toEpochMilli())
.setRegistrationId(primaryRegistrationId)
.setCreatedAtCiphertext(ByteString.copyFrom(primaryCreatedAtCiphertext))
.build())
.addDevices(GetDevicesResponse.LinkedDevice.newBuilder()
.setId(Device.PRIMARY_ID + 1)
.setCreated(linkedDeviceCreated.toEpochMilli())
.setLastSeen(linkedDeviceLastSeen.toEpochMilli())
.setName(ByteString.copyFrom(linkedDeviceName.getBytes(StandardCharsets.UTF_8)))
.setRegistrationId(linkedRegistrationId)
.setCreatedAtCiphertext(ByteString.copyFrom(linkedCreatedAtCiphertext))
.build())
.build();
@@ -40,7 +40,6 @@ import org.signal.chat.keys.KeysAnonymousGrpc;
import org.signal.chat.keys.ReactorKeysAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
@@ -86,7 +85,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final Device targetDevice = DevicesHelper.createDevice(Device.PRIMARY_ID);
when(targetAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(targetDevice));
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final UUID uuid = UUID.randomUUID();
final AciServiceIdentifier identifier = new AciServiceIdentifier(uuid);
@@ -98,7 +97,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
when(accountsManager.getByServiceIdentifierAsync(identifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
final ECPreKey ecPreKey = new ECPreKey(1, Curve.generateKeyPair().getPublicKey());
final ECPreKey ecPreKey = new ECPreKey(1, ECKeyPair.generate().getPublicKey());
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
@@ -137,7 +136,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final Device targetDevice = DevicesHelper.createDevice(Device.PRIMARY_ID);
when(targetAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(targetDevice));
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final UUID uuid = UUID.randomUUID();
final AciServiceIdentifier identifier = new AciServiceIdentifier(uuid);
@@ -149,7 +148,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
when(accountsManager.getByServiceIdentifierAsync(identifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
final ECPreKey ecPreKey = new ECPreKey(1, Curve.generateKeyPair().getPublicKey());
final ECPreKey ecPreKey = new ECPreKey(1, ECKeyPair.generate().getPublicKey());
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
@@ -312,7 +311,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(accountIdentifier);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(Curve.generateKeyPair().getPublicKey()));
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevices()).thenReturn(Collections.emptyList());
when(targetAccount.getDevice(anyByte())).thenReturn(Optional.empty());
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
@@ -338,15 +337,15 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final Account mismatchedAciFingerprintAccount = mock(Account.class);
final UUID mismatchedAciFingerprintAccountIdentifier = UUID.randomUUID();
final IdentityKey mismatchedAciFingerprintAccountIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
final IdentityKey mismatchedAciFingerprintAccountIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
final Account matchingAciFingerprintAccount = mock(Account.class);
final UUID matchingAciFingerprintAccountIdentifier = UUID.randomUUID();
final IdentityKey matchingAciFingerprintAccountIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
final IdentityKey matchingAciFingerprintAccountIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
final Account mismatchedPniFingerprintAccount = mock(Account.class);
final UUID mismatchedPniFingerprintAccountIdentifier = UUID.randomUUID();
final IdentityKey mismatchedPniFingerpringAccountIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
final IdentityKey mismatchedPniFingerpringAccountIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
when(mismatchedAciFingerprintAccount.getIdentityKey(IdentityType.ACI)).thenReturn(mismatchedAciFingerprintAccountIdentityKey);
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(mismatchedAciFingerprintAccountIdentifier)))
@@ -362,13 +361,13 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final Flux<CheckIdentityKeyRequest> requests = Flux.just(
buildCheckIdentityKeyRequest(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI, mismatchedAciFingerprintAccountIdentifier,
new IdentityKey(Curve.generateKeyPair().getPublicKey())),
new IdentityKey(ECKeyPair.generate().getPublicKey())),
buildCheckIdentityKeyRequest(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI, matchingAciFingerprintAccountIdentifier,
matchingAciFingerprintAccountIdentityKey),
buildCheckIdentityKeyRequest(org.signal.chat.common.IdentityType.IDENTITY_TYPE_PNI, UUID.randomUUID(),
new IdentityKey(Curve.generateKeyPair().getPublicKey())),
new IdentityKey(ECKeyPair.generate().getPublicKey())),
buildCheckIdentityKeyRequest(org.signal.chat.common.IdentityType.IDENTITY_TYPE_PNI, mismatchedPniFingerprintAccountIdentifier,
new IdentityKey(Curve.generateKeyPair().getPublicKey()))
new IdentityKey(ECKeyPair.generate().getPublicKey()))
);
final Map<UUID, IdentityKey> expectedResponses = Map.of(
@@ -52,7 +52,6 @@ import org.signal.chat.keys.SetKemLastResortPreKeyRequest;
import org.signal.chat.keys.SetOneTimeEcPreKeysRequest;
import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
@@ -72,9 +71,9 @@ import reactor.core.publisher.Mono;
class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.KeysBlockingStub> {
private static final ECKeyPair ACI_IDENTITY_KEY_PAIR = Curve.generateKeyPair();
private static final ECKeyPair ACI_IDENTITY_KEY_PAIR = ECKeyPair.generate();
private static final ECKeyPair PNI_IDENTITY_KEY_PAIR = Curve.generateKeyPair();
private static final ECKeyPair PNI_IDENTITY_KEY_PAIR = ECKeyPair.generate();
protected static final UUID AUTHENTICATED_PNI = UUID.randomUUID();
@@ -147,7 +146,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final List<ECPreKey> preKeys = new ArrayList<>();
for (int keyId = 0; keyId < 100; keyId++) {
preKeys.add(new ECPreKey(keyId, Curve.generateKeyPair().getPublicKey()));
preKeys.add(new ECPreKey(keyId, ECKeyPair.generate().getPublicKey()));
}
when(keysManager.storeEcOneTimePreKeys(any(), anyByte(), any()))
@@ -183,7 +182,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
.addPreKeys(EcPreKey.newBuilder()
.setKeyId(1)
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
.setPublicKey(ByteString.copyFrom(ECKeyPair.generate().getPublicKey().serialize()))
.build())
.build();
@@ -460,7 +459,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
void getPreKeys(final org.signal.chat.common.IdentityType grpcIdentityType) {
final Account targetAccount = mock(Account.class);
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final UUID identifier = UUID.randomUUID();
@@ -482,7 +481,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final byte deviceId2 = 2;
for (final byte deviceId : List.of(deviceId1, deviceId2)) {
ecOneTimePreKeys.put(deviceId, new ECPreKey(1, Curve.generateKeyPair().getPublicKey()));
ecOneTimePreKeys.put(deviceId, new ECPreKey(1, ECKeyPair.generate().getPublicKey()));
kemPreKeys.put(deviceId, KeysHelper.signedKEMPreKey(2, identityKeyPair));
ecSignedPreKeys.put(deviceId, KeysHelper.signedECPreKey(3, identityKeyPair));
@@ -597,7 +596,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(accountIdentifier);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(Curve.generateKeyPair().getPublicKey()));
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevices()).thenReturn(Collections.emptyList());
when(targetAccount.getDevice(anyByte())).thenReturn(Optional.empty());
@@ -617,7 +616,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
void getPreKeysRateLimited() {
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(UUID.randomUUID());
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(Curve.generateKeyPair().getPublicKey()));
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevices()).thenReturn(Collections.emptyList());
when(targetAccount.getDevice(anyByte())).thenReturn(Optional.empty());
@@ -27,7 +27,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
@@ -50,7 +49,6 @@ import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.ProfileAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
@@ -113,7 +111,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(targetUuid);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final List<Badge> badges = List.of(new Badge(
@@ -136,7 +134,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.hasCapability(any())).thenReturn(false);
when(account.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier)).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -159,7 +157,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
verify(accountsManager).getByServiceIdentifierAsync(serviceIdentifier);
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
assertEquals(expectedResponse, response);
}
@@ -172,7 +170,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final List<Badge> badges = List.of(new Badge(
@@ -192,7 +190,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier)).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
@@ -211,7 +209,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
verify(accountsManager).getByServiceIdentifierAsync(serviceIdentifier);
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
assertEquals(expectedResponse, response);
}
@@ -232,8 +230,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(
CompletableFuture.completedFuture(accountNotFound ? Optional.empty() : Optional.of(account)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
accountNotFound ? Optional.empty() : Optional.of(account));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(
@@ -283,8 +281,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(authorizedServiceIdentifier), expiration);
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(
CompletableFuture.completedFuture(Optional.empty()));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
Optional.empty());
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetUnversionedProfileRequest.newBuilder()
@@ -303,7 +301,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetUnversionedProfileRequest.newBuilder()
@@ -320,25 +318,21 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final boolean expectResponseHasPaymentAddress) {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final VersionedProfile profile = mock(VersionedProfile.class);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
when(profile.name()).thenReturn(name);
when(profile.aboutEmoji()).thenReturn(emoji);
when(profile.about()).thenReturn(about);
when(profile.paymentAddress()).thenReturn(paymentAddress);
when(profile.avatar()).thenReturn(avatar);
final VersionedProfile profile = new VersionedProfile(accountVersion, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, new byte[0]);
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -357,7 +351,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar);
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing));
if (expectResponseHasPaymentAddress) {
expectedResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
@@ -381,8 +376,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -406,8 +401,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(
CompletableFuture.completedFuture(accountNotFound ? Optional.empty() : Optional.of(account)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
accountNotFound ? Optional.empty() : Optional.of(account));
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
@@ -467,8 +462,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(targetUuid, "someVersion")).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
@@ -502,8 +497,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn(
CompletableFuture.completedFuture(missingAccount ? Optional.empty() : Optional.of(account)));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(
missingAccount ? Optional.empty() : Optional.of(account));
final GetExpiringProfileKeyCredentialAnonymousRequest.Builder requestBuilder = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
.setRequest(GetExpiringProfileKeyCredentialRequest.newBuilder()
@@ -540,9 +535,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn(
CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(targetUuid, "someVersion")).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(
Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.empty());
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -571,8 +566,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8));
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(targetUuid, "someVersion")).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
@@ -16,6 +16,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.refEq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -67,7 +68,7 @@ import org.signal.chat.profile.SetProfileRequest.AvatarChange;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerPublicParams;
@@ -109,7 +110,6 @@ import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcService, ProfileGrpc.ProfileBlockingStub> {
@@ -174,7 +174,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
Locale.LanguageRange.parse("en-us")));
when(rateLimiters.getProfileLimiter()).thenReturn(rateLimiter);
when(rateLimiter.validateReactive(any(UUID.class))).thenReturn(Mono.empty());
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
@@ -186,11 +185,10 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(profile.paymentAddress()).thenReturn(null);
when(profile.avatar()).thenReturn("");
when(accountsManager.getByAccountIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.getByAccountIdentifier(any())).thenReturn(Optional.of(account));
when(accountsManager.update(any(), any())).thenReturn(null);
when(profilesManager.getAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(profilesManager.setAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
@@ -237,7 +235,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
verify(profilesManager).setAsync(eq(account.getUuid()), profileArgumentCaptor.capture());
verify(profilesManager).set(eq(account.getUuid()), profileArgumentCaptor.capture());
final VersionedProfile profile = profileArgumentCaptor.getValue();
@@ -267,9 +265,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(profile.avatar()).thenReturn(currentAvatar);
when(profilesManager.getAsync(any(), anyString())).thenReturn(CompletableFuture.completedFuture(
hasPreviousProfile ? Optional.of(profile) : Optional.empty()));
when(profilesManager.setAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(profilesManager.get(any(), anyString())).thenReturn(hasPreviousProfile ? Optional.of(profile) : Optional.empty());
final SetProfileResponse response = authenticatedServiceStub().setProfile(request);
@@ -374,7 +370,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
disallowedPhoneNumber,
PhoneNumberUtil.PhoneNumberFormat.E164));
when(profilesManager.getAsync(any(), anyString())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(profilesManager.get(any(), anyString())).thenReturn(Optional.of(profile));
if (hasExistingPaymentAddress) {
assertDoesNotThrow(() -> authenticatedServiceStub().setProfile(request),
@@ -422,7 +418,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"})
void getUnversionedProfile(final IdentityType identityType) {
void getUnversionedProfile(final IdentityType identityType) throws Exception {
final UUID targetUuid = UUID.randomUUID();
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier targetIdentifier =
identityType == IdentityType.IDENTITY_TYPE_ACI ? new AciServiceIdentifier(targetUuid) : new PniServiceIdentifier(targetUuid);
@@ -434,7 +430,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.build())
.build();
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final List<Badge> badges = List.of(new Badge(
@@ -457,7 +453,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.hasCapability(any())).thenReturn(false);
when(account.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request);
@@ -481,15 +477,15 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
expectedResponse = prototypeExpectedResponse;
}
verify(rateLimiter).validateReactive(AUTHENTICATED_ACI);
verify(accountsManager).getByServiceIdentifierAsync(targetIdentifier);
verify(rateLimiter).validate(AUTHENTICATED_ACI);
verify(accountsManager).getByServiceIdentifier(targetIdentifier);
assertEquals(expectedResponse, response);
}
@Test
void getUnversionedProfileTargetAccountNotFound() {
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
@@ -503,11 +499,11 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"})
void getUnversionedProfileRatelimited(final IdentityType identityType) {
void getUnversionedProfileRatelimited(final IdentityType identityType) throws Exception {
final Duration retryAfterDuration = Duration.ofMinutes(7);
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(rateLimiter.validateReactive(any(UUID.class)))
.thenReturn(Mono.error(new RateLimitExceededException(retryAfterDuration)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
doThrow(new RateLimitExceededException(retryAfterDuration))
.when(rateLimiter).validate(any(UUID.class));
final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
@@ -522,13 +518,16 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@ParameterizedTest
@MethodSource
void getVersionedProfile(final String requestVersion, @Nullable final String accountVersion, final boolean expectResponseHasPaymentAddress) {
final VersionedProfile profile = mock(VersionedProfile.class);
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
final VersionedProfile profile = new VersionedProfile(accountVersion, name, avatar, emoji, about, paymentAddress,
phoneNumberSharing, new byte[0]);
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
@@ -537,15 +536,9 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setVersion(requestVersion)
.build();
when(profile.name()).thenReturn(name);
when(profile.about()).thenReturn(about);
when(profile.aboutEmoji()).thenReturn(emoji);
when(profile.avatar()).thenReturn(avatar);
when(profile.paymentAddress()).thenReturn(paymentAddress);
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
@@ -553,7 +546,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar);
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing));
if (expectResponseHasPaymentAddress) {
expectedResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
@@ -579,8 +573,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.build())
.setVersion("versionWithNoProfile")
.build();
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(missingAccount ? Optional.empty() : Optional.of(account)));
when(profilesManager.getAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(missingProfile ? Optional.empty() : Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getVersionedProfile(request));
}
@@ -638,8 +632,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.getUuid()).thenReturn(targetUuid);
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(targetUuid, "someVersion")).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
@@ -677,7 +671,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
void getExpiringProfileKeyCredentialRateLimited() {
final Duration retryAfterDuration = MockUtils.updateRateLimiterResponseToFail(
rateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(5));
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
@@ -699,9 +693,10 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final UUID targetUuid = UUID.randomUUID();
when(account.getUuid()).thenReturn(targetUuid);
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn(CompletableFuture.completedFuture(
missingAccount ? Optional.empty() : Optional.of(account)));
when(profilesManager.getAsync(targetUuid, "someVersion")).thenReturn(CompletableFuture.completedFuture(missingProfile ? Optional.empty() : Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid)))
.thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion"))
.thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
@@ -735,8 +730,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.getUuid()).thenReturn(targetUuid);
when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8));
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(targetUuid))).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(profilesManager.getAsync(targetUuid, "someVersion")).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
@@ -36,7 +36,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@@ -106,7 +105,7 @@ abstract class AbstractNoiseHandlerTest extends AbstractLeakDetectionTest {
@BeforeEach
void setUp() {
serverKeyPair = Curve.generateKeyPair();
serverKeyPair = ECKeyPair.generate();
noiseHandshakeCompleteHandler = new NoiseHandshakeCompleteHandler();
clientPublicKeysManager = mock(ClientPublicKeysManager.class);
embeddedChannel = new EmbeddedChannel(
@@ -48,7 +48,6 @@ import org.signal.chat.rpc.GetAuthenticatedDeviceRequest;
import org.signal.chat.rpc.GetAuthenticatedDeviceResponse;
import org.signal.chat.rpc.GetRequestAttributesRequest;
import org.signal.chat.rpc.RequestAttributesGrpc;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
@@ -97,8 +96,8 @@ public abstract class AbstractNoiseTunnelServerIntegrationTest extends AbstractL
@BeforeEach
void setUp() throws Exception {
clientKeyPair = Curve.generateKeyPair();
serverKeyPair = Curve.generateKeyPair();
clientKeyPair = ECKeyPair.generate();
serverKeyPair = ECKeyPair.generate();
grpcClientConnectionManager = new GrpcClientConnectionManager();
@@ -214,7 +213,7 @@ public abstract class AbstractNoiseTunnelServerIntegrationTest extends AbstractL
// Try to verify the server's public key with something other than the key with which it was signed
try (final NoiseTunnelClient client = authenticated()
.setServerPublicKey(Curve.generateKeyPair().getPublicKey())
.setServerPublicKey(ECKeyPair.generate().getPublicKey())
.build()) {
final ManagedChannel channel = buildManagedChannel(client.getLocalAddress());
@@ -235,7 +234,7 @@ public abstract class AbstractNoiseTunnelServerIntegrationTest extends AbstractL
void connectAuthenticatedMismatchedClientPublicKey() throws InterruptedException, ExecutionException, TimeoutException {
when(clientPublicKeysManager.findPublicKey(ACCOUNT_IDENTIFIER, DEVICE_ID))
.thenReturn(CompletableFuture.completedFuture(Optional.of(Curve.generateKeyPair().getPublicKey())));
.thenReturn(CompletableFuture.completedFuture(Optional.of(ECKeyPair.generate().getPublicKey())));
try (final NoiseTunnelClient client = authenticated().build()) {
final ManagedChannel channel = buildManagedChannel(client.getLocalAddress());
@@ -323,7 +322,7 @@ public abstract class AbstractNoiseTunnelServerIntegrationTest extends AbstractL
// Try to verify the server's public key with something other than the key with which it was signed
try (final NoiseTunnelClient client = anonymous()
.setServerPublicKey(Curve.generateKeyPair().getPublicKey())
.setServerPublicKey(ECKeyPair.generate().getPublicKey())
.build()) {
final ManagedChannel channel = buildManagedChannel(client.getLocalAddress());
@@ -31,7 +31,6 @@ import java.util.concurrent.ThreadLocalRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
import org.junit.jupiter.api.Test;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
@@ -42,7 +41,7 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
class NoiseAuthenticatedHandlerTest extends AbstractNoiseHandlerTest {
private final ECKeyPair clientKeyPair = Curve.generateKeyPair();
private final ECKeyPair clientKeyPair = ECKeyPair.generate();
@Override
protected CipherStatePair doHandshake() throws Throwable {
@@ -177,7 +176,7 @@ class NoiseAuthenticatedHandlerTest extends AbstractNoiseHandlerTest {
final byte deviceId = randomDeviceId();
when(clientPublicKeysManager.findPublicKey(accountIdentifier, deviceId))
.thenReturn(CompletableFuture.completedFuture(Optional.of(Curve.generateKeyPair().getPublicKey())));
.thenReturn(CompletableFuture.completedFuture(Optional.of(ECKeyPair.generate().getPublicKey())));
doHandshake(
identityPayload(accountIdentifier, deviceId),
@@ -14,7 +14,6 @@ import javax.crypto.ShortBufferException;
import io.netty.buffer.ByteBufUtil;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.grpc.net.client.NoiseClientHandshakeHelper;
@@ -40,8 +39,8 @@ public class NoiseHandshakeHelperTest {
}
void doHandshake(final HandshakePattern pattern, final byte[] requestPayload, final byte[] responsePayload) throws ShortBufferException, NoiseHandshakeException {
final ECKeyPair serverKeyPair = Curve.generateKeyPair();
final ECKeyPair clientKeyPair = Curve.generateKeyPair();
final ECKeyPair serverKeyPair = ECKeyPair.generate();
final ECKeyPair clientKeyPair = ECKeyPair.generate();
NoiseHandshakeHelper serverHelper = new NoiseHandshakeHelper(pattern, serverKeyPair);
NoiseClientHandshakeHelper clientHelper = switch (pattern) {
@@ -18,6 +18,8 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import io.micrometer.core.instrument.Tag;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -25,8 +27,10 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@@ -38,31 +42,30 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.tests.util.MultiRecipientMessageHelper;
import org.whispersystems.textsecuregcm.tests.util.TestRecipient;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class MessageSenderTest {
private MessagesManager messagesManager;
private PushNotificationManager pushNotificationManager;
private MessageSender messageSender;
private ExperimentEnrollmentManager experimentEnrollmentManager;
@BeforeEach
void setUp() {
messagesManager = mock(MessagesManager.class);
pushNotificationManager = mock(PushNotificationManager.class);
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
messageSender = new MessageSender(messagesManager, pushNotificationManager, experimentEnrollmentManager);
messageSender = new MessageSender(messagesManager, pushNotificationManager);
}
@@ -258,13 +261,183 @@ class MessageSenderTest {
mismatchedDevicesException.getMismatchedDevicesByServiceIdentifier());
}
@ParameterizedTest
@MethodSource
void validateIndividualMessageBundle(final Account destination,
final ServiceIdentifier destinationIdentifier,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final Map<Byte, Integer> registrationIdsByDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Byte> syncMessageSenderDeviceId,
@Nullable final Class<? extends Exception> expectedExceptionClass) {
final Executable validateIndividualMessageBundle = () -> MessageSender.validateIndividualMessageBundle(destination,
destinationIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
syncMessageSenderDeviceId,
"Signal/Test");
if (expectedExceptionClass != null) {
assertThrows(expectedExceptionClass, validateIndividualMessageBundle);
} else {
assertDoesNotThrow(validateIndividualMessageBundle);
}
}
private static List<Arguments> validateIndividualMessageBundle() {
final ServiceIdentifier destinationIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte primaryDeviceId = Device.PRIMARY_ID;
final byte linkedDeviceId = primaryDeviceId + 1;
final int primaryDeviceRegistrationId = 17;
final int linkedDeviceRegistrationId = primaryDeviceRegistrationId + 1;
final Device primaryDevice = mock(Device.class);
when(primaryDevice.getId()).thenReturn(primaryDeviceId);
when(primaryDevice.getRegistrationId(IdentityType.ACI)).thenReturn(primaryDeviceRegistrationId);
final Device linkedDevice = mock(Device.class);
when(linkedDevice.getId()).thenReturn(linkedDeviceId);
when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(linkedDeviceRegistrationId);
final Account destination = mock(Account.class);
when(destination.isIdentifiedBy(any())).thenReturn(false);
when(destination.isIdentifiedBy(destinationIdentifier)).thenReturn(true);
when(destination.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice));
when(destination.getDevice(anyByte())).thenReturn(Optional.empty());
when(destination.getDevice(primaryDeviceId)).thenReturn(Optional.of(primaryDevice));
when(destination.getDevice(linkedDeviceId)).thenReturn(Optional.of(linkedDevice));
return List.of(
Arguments.argumentSet("Valid",
destination,
destinationIdentifier,
Map.of(
primaryDeviceId, generateEnvelope(null, 16),
linkedDeviceId, generateEnvelope(null, 16)),
Map.of(
primaryDeviceId, primaryDeviceRegistrationId,
linkedDeviceId, linkedDeviceRegistrationId),
Optional.empty(),
null),
Arguments.argumentSet("Mismatched service ID",
destination,
new AciServiceIdentifier(UUID.randomUUID()),
Map.of(
primaryDeviceId, generateEnvelope(null, 16),
linkedDeviceId, generateEnvelope(null, 16)),
Map.of(
primaryDeviceId, primaryDeviceRegistrationId,
linkedDeviceId, linkedDeviceRegistrationId),
Optional.empty(),
IllegalArgumentException.class),
Arguments.argumentSet("Sync message without source on all messages",
destination,
destinationIdentifier,
Map.of(linkedDeviceId, generateEnvelope(null, 16)),
Map.of(linkedDeviceId, linkedDeviceRegistrationId),
Optional.of(primaryDevice),
IllegalArgumentException.class),
Arguments.argumentSet("Sync message to other account",
destination,
destinationIdentifier,
Map.of(linkedDeviceId, generateEnvelope(new AciServiceIdentifier(UUID.randomUUID()), 16)),
Map.of(linkedDeviceId, linkedDeviceRegistrationId),
Optional.of(primaryDevice),
IllegalArgumentException.class),
Arguments.argumentSet("Sync message to other account",
destination,
destinationIdentifier,
Map.of(linkedDeviceId, generateEnvelope(new AciServiceIdentifier(UUID.randomUUID()), 16)),
Map.of(linkedDeviceId, linkedDeviceRegistrationId),
Optional.of(primaryDevice),
IllegalArgumentException.class),
Arguments.argumentSet("Non-sync message addressed to sender",
destination,
destinationIdentifier,
Map.of(
primaryDeviceId, generateEnvelope(destinationIdentifier, 16),
linkedDeviceId, generateEnvelope(destinationIdentifier, 16)),
Map.of(
primaryDeviceId, primaryDeviceRegistrationId,
linkedDeviceId, linkedDeviceRegistrationId),
Optional.empty(),
IllegalArgumentException.class),
Arguments.argumentSet("Non-sync message addressed to sender",
destination,
destinationIdentifier,
Map.of(
primaryDeviceId, generateEnvelope(destinationIdentifier, 16),
linkedDeviceId, generateEnvelope(destinationIdentifier, 16)),
Map.of(
primaryDeviceId, primaryDeviceRegistrationId,
linkedDeviceId, linkedDeviceRegistrationId),
Optional.empty(),
IllegalArgumentException.class),
Arguments.argumentSet("Mismatched devices in message set",
destination,
destinationIdentifier,
Map.of(
primaryDeviceId, generateEnvelope(null, 16),
linkedDeviceId + 1, generateEnvelope(null, 16)),
Map.of(
primaryDeviceId, primaryDeviceRegistrationId,
linkedDeviceId + 1, linkedDeviceRegistrationId),
Optional.empty(),
MismatchedDevicesException.class),
Arguments.argumentSet("Mismatched registration IDs",
destination,
destinationIdentifier,
Map.of(
primaryDeviceId, generateEnvelope(null, 16),
linkedDeviceId, generateEnvelope(null, 16)),
Map.of(
primaryDeviceId, primaryDeviceRegistrationId,
linkedDeviceId, linkedDeviceRegistrationId + 1),
Optional.empty(),
MismatchedDevicesException.class),
Arguments.argumentSet("Oversized message",
destination,
destinationIdentifier,
Map.of(
primaryDeviceId, generateEnvelope(null, MessageSender.MAX_MESSAGE_SIZE + 1),
linkedDeviceId, generateEnvelope(null, MessageSender.MAX_MESSAGE_SIZE + 1)),
Map.of(
primaryDeviceId, primaryDeviceRegistrationId,
linkedDeviceId, linkedDeviceRegistrationId),
Optional.empty(),
MessageTooLargeException.class)
);
}
private static MessageProtos.Envelope generateEnvelope(@Nullable ServiceIdentifier sourceIdentifier, final int contentLength) {
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(contentLength)));
if (sourceIdentifier != null) {
envelopeBuilder.setSourceServiceId(sourceIdentifier.toServiceIdentifierString());
}
return envelopeBuilder.build();
}
@Test
void validateContentLength() {
assertThrows(MessageTooLargeException.class, () ->
MessageSender.validateContentLength(MessageSender.MAX_MESSAGE_SIZE + 1, false, false, false, null));
MessageSender.validateContentLength(MessageSender.MAX_MESSAGE_SIZE + 1, false, false, false, Tag.of(UserAgentTagUtil.PLATFORM_TAG, "test")));
assertDoesNotThrow(() ->
MessageSender.validateContentLength(MessageSender.MAX_MESSAGE_SIZE, false, false, false, null));
MessageSender.validateContentLength(MessageSender.MAX_MESSAGE_SIZE, false, false, false, Tag.of(UserAgentTagUtil.PLATFORM_TAG, "test")));
}
@ParameterizedTest
@@ -1,26 +1,24 @@
package org.whispersystems.textsecuregcm.redis;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.RedisException;
import io.lettuce.core.resource.ClientResources;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
// ThreadMode.SEPARATE_THREAD protects against hangs in the remote Redis calls, as this mode allows the test code to be
// preempted by the timeout check
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
@@ -60,13 +58,13 @@ class FaultTolerantRedisClientTest {
faultTolerantRedisClient = buildRedisClient(null, ClientResources.builder());
final ExecutionException asyncException = assertThrows(ExecutionException.class,
() -> faultTolerantRedisClient.withConnection(connection -> connection.async().blpop(2 * TIMEOUT.toMillis() / 1000d, "key"))
() -> faultTolerantRedisClient.withConnection(connection -> connection.async().blpop(10 * TIMEOUT.toMillis() / 1000d, "key"))
.get());
assertInstanceOf(RedisCommandTimeoutException.class, asyncException.getCause());
assertThrows(RedisCommandTimeoutException.class,
() -> faultTolerantRedisClient.withConnection(connection -> connection.sync().blpop(2 * TIMEOUT.toMillis() / 1000d, "key")));
() -> faultTolerantRedisClient.withConnection(connection -> connection.sync().blpop(10 * TIMEOUT.toMillis() / 1000d, "key")));
}
@Test
@@ -87,11 +85,11 @@ class FaultTolerantRedisClientTest {
// the first call should time out and open the breaker
assertThrows(RedisCommandTimeoutException.class,
() -> faultTolerantRedisClient.withConnection(connection -> connection.sync().blpop(2 * TIMEOUT.toMillis() / 1000d, key)));
() -> faultTolerantRedisClient.withConnection(connection -> connection.sync().blpop(10 * TIMEOUT.toMillis() / 1000d, key)));
// the second call gets blocked by the breaker
final RedisException e = assertThrows(RedisException.class,
() -> faultTolerantRedisClient.withConnection(connection -> connection.sync().blpop(2 * TIMEOUT.toMillis() / 1000d, key)));
() -> faultTolerantRedisClient.withConnection(connection -> connection.sync().blpop(10 * TIMEOUT.toMillis() / 1000d, key)));
assertInstanceOf(CallNotPermittedException.class, e.getCause());
// wait for breaker to be half-open
@@ -91,7 +91,8 @@ class FaultTolerantRedisClusterClientTest {
@Nullable final CircuitBreakerConfiguration circuitBreakerConfiguration,
final ClientResources.Builder clientResourcesBuilder) {
return new FaultTolerantRedisClusterClient("test", clientResourcesBuilder,
return new FaultTolerantRedisClusterClient("test",
clientResourcesBuilder.socketAddressResolver(REDIS_CLUSTER_EXTENSION.getSocketAddressResolver()),
RedisClusterExtension.getRedisURIs(), TIMEOUT,
Optional.ofNullable(circuitBreakerConfiguration).orElseGet(CircuitBreakerConfiguration::new),
RETRY_CONFIGURATION);
@@ -338,11 +339,13 @@ class FaultTolerantRedisClusterClientTest {
}
void openBreaker(final RedisURI redisURI) {
urisToChannelBreakers.get(redisURI).forEach(handler -> handler.breaker.transitionToOpenState());
urisToChannelBreakers.get(REDIS_CLUSTER_EXTENSION.getExposedRedisURI(redisURI))
.forEach(handler -> handler.breaker.transitionToOpenState());
}
void closeBreaker(final RedisURI redisURI) {
urisToChannelBreakers.get(redisURI).forEach(handler -> handler.breaker.transitionToClosedState());
urisToChannelBreakers.get(REDIS_CLUSTER_EXTENSION.getExposedRedisURI(redisURI))
.forEach(handler -> handler.breaker.transitionToClosedState());
}
}
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more