Compare commits

..
Author SHA1 Message Date
Ravi Khadiwala 18c9b177f3 Relax issuing constraints in IssuedReceiptManager 2024-12-10 11:47:44 -06:00
Ravi Khadiwala 1970741049 Remove IssuedReceiptMigrationCommand 2024-12-10 11:46:17 -06:00
Ravi Khadiwala f16428ce2a Register IssuedReceiptMigrationCommand 2024-12-10 11:46:17 -06:00
Ravi Khadiwala 14427523ae Add a tag->tag-set migration command 2024-12-06 14:54:45 -06:00
Ravi Khadiwala 236b0496d3 Write a set field in IssuedReceiptsManager 2024-12-06 14:53:10 -06:00
Ravi Khadiwala f68ddf66e9 Day align DeviceCheck backup vouchers 2024-12-06 14:52:50 -06:00
Jon Chambers 20685b6d69 Clear "canceled at" timestamp when setting a new subscrition ID 2024-12-06 15:51:57 -05:00
Jon Chambers 4988b4e0f5 Refresh accounts before returning device lists 2024-12-05 14:35:18 -05:00
Katherine 651e444875 Delete from SVR3 in account deletion flow 2024-12-05 11:36:33 -05:00
Jon Chambers 2093fed554 Drop the unused setUnauthenticatedDelivery endpoint 2024-12-03 14:06:05 -06:00
Ravi Khadiwala cc7bb8b549 Map stripe idempotency errors to 400 2024-12-03 14:05:43 -06:00
Ravi Khadiwala a99ac14c6a Write number->pni mapping before checking rrp table 2024-12-03 14:05:31 -06:00
Ravi Khadiwala 2c163352c3 Add DeviceCheck API for iOS Testflight backup enablement 2024-12-03 14:05:02 -06:00
Jon Chambers fb6c4eca34 Retire RemoveE164RecentlyDeletedAccountsCommand 2024-12-02 11:17:03 -05:00
Jon Chambers 142e2cbe9d Update to the latest version of the spam filter 2024-12-02 10:59:51 -05:00
Jon Chambers c70dd119d3 Remove AbstractDynamoDbStore as a base class from Accounts 2024-12-02 10:57:45 -05:00
Katherine 9e312cbdfa Normalize Benin phone numbers to the new format before sending to registration service 2024-12-02 10:57:27 -05:00
Jon Chambers 4d87b741cd Add a command to remove e164-associated "recently-deleted account" records 2024-11-27 12:29:42 -05:00
Jon Chambers d08bc4c413 Write "recently deleted account" rows exclusively by PNI 2024-11-27 12:29:42 -05:00
Ravi Khadiwala f5d3d1e65d Remove BackfillBeninPhoneNumberFormsCommand 2024-11-27 12:21:30 -05:00
Jon Chambers 916314233f Retire DeleteE164RegistrationRecoveryPasswordsCommand 2024-11-27 12:12:58 -05:00
Jonathan Klabunde Tomer c7e6ee7297 Update to the latest version of the spam filter 2024-11-26 16:36:45 -08:00
Jonathan Klabunde Tomer 557a6ecd4f Read deleted accounts by PNI rather than e164 2024-11-26 16:35:40 -08:00
Ameya Lokare 0e04cac800 Crawler to backfill PNI records of alternate forms of existing phone numbers 2024-11-26 18:46:08 -05:00
Jon Chambers 1db9258d39 Add a command to remove e164-associated registration recovery passwords 2024-11-26 18:38:27 -05:00
Jon Chambers 2803c2acdb Write registration recovery passwords exclusively by PNI 2024-11-26 18:31:36 -05:00
Ravi Khadiwala 8be43566a4 Fix swagger oneof annotations 2024-11-26 17:40:05 -05:00
Ameya Lokare d865cec2a4 Insert alternate forms of phone numbers -> PNI atomically 2024-11-26 17:39:53 -05:00
Jon Chambers 6f0370a073 Update to the latest version of the spam filter 2024-11-26 17:39:37 -05:00
Jon Chambers 5b9f8177f2 Read registration recovery passwords exclusively by PNI 2024-11-26 17:31:08 -05:00
Jon Chambers 6967e4e54b Retire MigrateRegistrationRecoveryPasswordsCommand 2024-11-26 17:23:49 -05:00
Jon Chambers 96fb0ac3ae Add a utility method for testing if a number begins with a decimal prefix 2024-11-26 14:13:06 -06:00
Jon Chambers 7201938793 Add a utility method for getting alternate forms of (Benin) phone numbers 2024-11-26 14:13:06 -06:00
Jonathan Klabunde Tomer cdd6f78c73 Handle errors in deleted-accounts crawler 2024-11-25 21:22:33 -05:00
Jon Chambers ab94d3045d Add a buffer/shuffle pair to better distribute load across shards 2024-11-25 20:41:25 -05:00
Jon Chambers ff4e2bdfb7 Refresh registration recovery password expirations before retrying an insertion 2024-11-25 16:45:28 -05:00
Jonathan Klabunde Tomer ffed19d198 Create deleted-accounts records keyed by both e164 and PNI 2024-11-25 12:42:16 -08:00
ravi-signal 49d6a5e32d Add error reporting to /v1/devices/transfer_archive 2024-11-25 12:41:51 -08:00
Jon Chambers 3ba7ba4f92 Remove abstract base class from RegistrationRecoveryPasswords 2024-11-25 15:27:30 -05:00
Jon Chambers 43ffc996db Use a segmented scan on a separate scheduler for registration recovery passwords 2024-11-25 14:18:56 -05:00
Jon Chambers 27f5f94c60 Retry registration recovery password migration attempts 2024-11-25 10:39:08 -05:00
Jonathan Klabunde Tomer 1d9734c824 MigrateRegistrationRecoveryPasswordsCommand: un-invert semantics of dryRun flag 2024-11-23 09:23:36 -05:00
Jon Chambers 717fb57a14 Add a command to migrate registration recovery passwords to PNI-associated records 2024-11-22 18:18:40 -05:00
Jon Chambers af1d21c225 Add methods for migrating E164-mapped registration recovery passwords to PNI-mapped records 2024-11-22 18:18:40 -05:00
Jon Chambers 3c8b2a82a3 Store registration recovery passwords by both E164 and PNI 2024-11-22 18:18:40 -05:00
Jonathan Klabunde TomerandChris Eager 0cb6f662c6 Handle multiple values with same ACI in deleted-accounts table
Co-authored-by: Chris Eager <79161849+eager-signal@users.noreply.github.com>
2024-11-22 15:11:27 -08:00
Chris Eager 739ed56b4c Don’t use an existing record's number in AccountsManager re-registration handling 2024-11-22 17:10:08 -06:00
Chris Eager 9a19ef82fd Use pni in DynamoDB account put condition expression 2024-11-22 17:10:08 -06:00
Chris Eager 5627ed141b Update phone number/PNI constraint cancellation reason comment 2024-11-22 17:10:08 -06:00
Chris Eager e4a2af67b1 Update AccountsManager#changeNumber validation to check for PNI equality 2024-11-22 17:06:42 -06:00
Chris Eager cba56f3263 Add @E164 to ChangeNumberRequest 2024-11-22 17:05:07 -06:00
Chris Eager 1c3cf39b8a Remove String e164 from AccountLockManager 2024-11-22 17:04:32 -06:00
Jonathan Klabunde Tomer 6421438f64 Delete deleted-account records by PNI as well as e164 2024-11-22 15:36:15 -05:00
Jon Chambers 8a63682c16 Drop the unused PhoneNumberIdentifiers#getPhoneNumber method 2024-11-22 15:26:44 -05:00
Jon Chambers 13a8c6256d Delete registration recovery passwords by both phone number and PNI 2024-11-22 15:26:44 -05:00
Jon Chambers 8c9cc4cce5 Make PhoneNumberIdentifiers operations asynchronous 2024-11-22 15:26:44 -05:00
Jon Chambers 0023cb2521 Resolve minor warnings/suggestions 2024-11-22 15:10:00 -05:00
Jon Chambers 010ed77345 Use libphonenumber to get country codes 2024-11-22 15:10:00 -05:00
Jon Chambers 00c11f5dd0 Use a more conventional name for a static constant 2024-11-22 15:10:00 -05:00
Jon Chambers 637e424506 Remove an unused "get number prefix" method 2024-11-22 15:10:00 -05:00
Chris Eager eb55b80bdc Add PNI support to AccountLockManager 2024-11-22 14:09:52 -06:00
Chris Eager 73812b06be Fix class names in logger initialization 2024-11-21 16:09:41 -06:00
Ravi Khadiwala d135957f0d Cancel past_due subscriptions immediately 2024-11-21 16:09:17 -06:00
Chris Eager 815fd44ab3 Update to the latest version of the spam filter 2024-11-21 16:08:08 -06:00
Chris Eager 4e8a48ab3d Update MicrometerAwsSdkMetricPublisher maxConcurrency metric name 2024-11-21 16:07:24 -06:00
Chris Eager ea75c39b58 Use MRM shared data views 2024-11-19 15:31:31 -06:00
Jon Chambers 085f013bf9 Update to libphonenumber 8.13.50 in preparation for Benin phone number format changes 2024-11-19 16:20:43 -05:00
104 changed files with 4095 additions and 876 deletions

No files matched your search

@@ -8,10 +8,12 @@ package org.signal.integration;
import java.time.Clock;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.signal.integration.config.Config;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
@@ -19,7 +21,6 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class IntegrationTools {
@@ -27,6 +28,8 @@ public class IntegrationTools {
private final VerificationSessionManager verificationSessionManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
public static IntegrationTools create(final Config config) {
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
@@ -34,30 +37,32 @@ public class IntegrationTools {
final DynamoDbAsyncClient dynamoDbAsyncClient =
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, dynamoDbAsyncClient);
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbAsyncClient, Clock.systemUTC());
final VerificationSessions verificationSessions = new VerificationSessions(
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
return new IntegrationTools(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
new VerificationSessionManager(verificationSessions)
new VerificationSessionManager(verificationSessions),
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers())
);
}
private IntegrationTools(
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final VerificationSessionManager verificationSessionManager) {
final VerificationSessionManager verificationSessionManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers) {
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.verificationSessionManager = verificationSessionManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
}
public CompletableFuture<Void> populateRecoveryPassword(final String e164, final byte[] password) {
return registrationRecoveryPasswordsManager.storeForCurrentNumber(e164, password);
public CompletableFuture<Void> populateRecoveryPassword(final String phoneNumber, final byte[] password) {
return phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber)
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password));
}
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
@@ -8,5 +8,6 @@ package org.signal.integration.config;
import jakarta.validation.constraints.NotBlank;
public record DynamoDbTables(@NotBlank String registrationRecovery,
@NotBlank String verificationSessions) {
@NotBlank String verificationSessions,
@NotBlank String phoneNumberIdentifiers) {
}
+1 -1
View File
@@ -58,7 +58,7 @@
<kotlin.version>1.9.24</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<lettuce.version>6.4.1.RELEASE</lettuce.version>
<libphonenumber.version>8.13.49</libphonenumber.version>
<libphonenumber.version>8.13.50</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<log4j-bom.version>2.23.1</log4j-bom.version>
<luajava.version>3.4.0</luajava.version>
+20 -1
View File
@@ -92,6 +92,14 @@ appleAppStore:
productIdToLevel: {}
appleRootCerts: []
appleDeviceCheck:
production: false
teamId: 0123456789
bundleId: bundle.name
deviceCheck:
backupRedemptionDuration: P30D
backupRedemptionLevel: 201
dynamoDbClient:
region: us-west-2 # AWS Region
@@ -103,6 +111,10 @@ dynamoDbTables:
phoneNumberIdentifierTableName: Example_Accounts_PhoneNumberIdentifiers
usernamesTableName: Example_Accounts_Usernames
usedLinkDeviceTokensTableName: Example_Accounts_UsedLinkDeviceTokens
appleDeviceChecks:
tableName: Example_AppleDeviceChecks
appleDeviceCheckPublicKeys:
tableName: Example_AppleDeviceCheckPublicKeys
backups:
tableName: Example_Backups
clientReleases:
@@ -115,6 +127,11 @@ dynamoDbTables:
tableName: Example_IssuedReceipts
expiration: P30D # Duration of time until rows expire
generator: abcdefg12345678= # random base64-encoded binary sequence
maxIssuedReceiptsPerPaymentId:
STRIPE: 1
BRAINTREE: 1
GOOGLE_PLAY_BILLING: 1
APPLE_APP_STORE: 1
ecKeys:
tableName: Example_Keys
ecSignedPreKeys:
@@ -203,7 +220,9 @@ svr2:
-----END CERTIFICATE-----
svr3:
uri: svr3.example.com
backend1Uri: backend1.example.com
backend2Uri: backend2.example.com
backend3Uri: backend3.example.com
userAuthenticationTokenSharedSecret: secret://svr3.userAuthenticationTokenSharedSecret
userIdTokenSharedSecret: secret://svr3.userIdTokenSharedSecret
svrCaCertificates:
+6
View File
@@ -15,6 +15,7 @@
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<google-androidpublisher.version>v3-rev20241016-2.0.0</google-androidpublisher.version>
<storekit.version>3.2.0</storekit.version>
<webauthn4j.version>0.28.0.RELEASE</webauthn4j.version>
</properties>
<dependencies>
@@ -35,6 +36,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-appattest</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2-jakarta</artifactId>
@@ -16,6 +16,7 @@ import java.util.Map;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
@@ -25,6 +26,7 @@ import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DogstatsdConfiguration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
@@ -96,6 +98,16 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private AppleAppStoreConfiguration appleAppStore;
@NotNull
@Valid
@JsonProperty
private AppleDeviceCheckConfiguration appleDeviceCheck;
@NotNull
@Valid
@JsonProperty
private DeviceCheckConfiguration deviceCheck;
@NotNull
@Valid
@JsonProperty
@@ -359,6 +371,14 @@ public class WhisperServerConfiguration extends Configuration {
return appleAppStore;
}
public AppleDeviceCheckConfiguration getAppleDeviceCheck() {
return appleDeviceCheck;
}
public DeviceCheckConfiguration getDeviceCheck() {
return deviceCheck;
}
public DynamoDbClientFactory getDynamoDbClientConfiguration() {
return dynamoDbClient;
}
@@ -8,6 +8,7 @@ import static com.codahale.metrics.MetricRegistry.name;
import static java.util.Objects.requireNonNull;
import com.google.common.collect.Lists;
import com.webauthn4j.appattest.DeviceCheckManager;
import io.dropwizard.auth.AuthDynamicFeature;
import io.dropwizard.auth.AuthFilter;
import io.dropwizard.auth.AuthValueFactoryProvider;
@@ -114,6 +115,7 @@ import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
import org.whispersystems.textsecuregcm.controllers.CallRoutingControllerV2;
import org.whispersystems.textsecuregcm.controllers.CertificateController;
import org.whispersystems.textsecuregcm.controllers.ChallengeController;
import org.whispersystems.textsecuregcm.controllers.DeviceCheckController;
import org.whispersystems.textsecuregcm.controllers.DeviceController;
import org.whispersystems.textsecuregcm.controllers.DirectoryV2Controller;
import org.whispersystems.textsecuregcm.controllers.DonationController;
@@ -204,6 +206,7 @@ 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.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
@@ -213,6 +216,9 @@ import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.AccountPrincipalSupplier;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeys;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
@@ -394,6 +400,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.workQueue(messageDeletionQueue).build();
Accounts accounts = new Accounts(
clock,
dynamoDbClient,
dynamoDbAsyncClient,
config.getDynamoDbTables().getAccounts().getTableName(),
@@ -404,7 +411,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
ClientReleases clientReleases = new ClientReleases(dynamoDbAsyncClient,
config.getDynamoDbTables().getClientReleases().getTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
config.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfiles().getTableName());
@@ -429,9 +436,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
dynamoDbClient,
dynamoDbAsyncClient
);
dynamoDbAsyncClient,
clock);
ClientPublicKeys clientPublicKeys =
new ClientPublicKeys(dynamoDbAsyncClient, config.getDynamoDbTables().getClientPublicKeys().getTableName());
@@ -473,8 +479,10 @@ 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 secureValueRecoveryServiceExecutor = environment.lifecycle()
.executorService(name(getClass(), "secureValueRecoveryService-%d")).maxThreads(1).minThreads(1).build();
ExecutorService secureValueRecovery2ServiceExecutor = environment.lifecycle()
.executorService(name(getClass(), "secureValueRecoveryService2-%d")).maxThreads(1).minThreads(1).build();
ExecutorService secureValueRecovery3ServiceExecutor = environment.lifecycle()
.executorService(name(getClass(), "secureValueRecoveryService3-%d")).maxThreads(1).minThreads(1).build();
ExecutorService storageServiceExecutor = environment.lifecycle()
.executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
ExecutorService virtualThreadEventLoggerExecutor = environment.lifecycle()
@@ -583,8 +591,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
dynamicConfigurationManager);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
registrationRecoveryPasswords);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
@@ -597,13 +605,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getKeyTransparencyServiceConfiguration().clientPrivateKey().value(),
keyTransparencyCallbackExecutor);
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
secureValueRecovery2ServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
SecureValueRecovery3Client secureValueRecovery3Client = new SecureValueRecovery3Client(svr3CredentialsGenerator,
secureValueRecovery3ServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr3Configuration());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, clock, dynamicConfigurationManager);
messageDeletionAsyncExecutor, clock);
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
@@ -618,7 +628,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, secureValueRecovery3Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
@@ -637,7 +647,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
dynamoDbAsyncClient,
config.getDynamoDbTables().getIssuedReceipts().getGenerator());
config.getDynamoDbTables().getIssuedReceipts().getGenerator(),
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbAsyncClient);
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
@@ -789,6 +800,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
cdn3RemoteStorageManager,
clock);
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
dynamoDbClient,
DeviceCheckManager.createObjectConverter(),
config.getDynamoDbTables().getAppleDeviceChecks().getTableName(),
config.getDynamoDbTables().getAppleDeviceCheckPublicKeys().getTableName());
final DeviceCheckManager deviceCheckManager = new DeviceCheckManager(new AppleDeviceCheckTrustAnchor());
deviceCheckManager.getAttestationDataValidator().setProduction(config.getAppleDeviceCheck().production());
final AppleDeviceCheckManager appleDeviceCheckManager = new AppleDeviceCheckManager(
appleDeviceChecks,
cacheCluster,
deviceCheckManager,
config.getAppleDeviceCheck().teamId(),
config.getAppleDeviceCheck().bundleId());
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(dynamicConfigurationManager);
MaxMindDatabaseManager geoIpCityDatabaseManager = new MaxMindDatabaseManager(
@@ -1074,7 +1099,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, turnTokenGenerator, registrationRecoveryPasswordsManager,
usernameHashZkProofVerifier),
@@ -1092,14 +1117,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, config.getMaxDevices()),
new DeviceCheckController(clock, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
accountsManager, messagesManager, pushNotificationManager, pushNotificationScheduler, reportMessageManager,
multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
@@ -1117,8 +1145,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket()),
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters,
accountsManager, registrationFraudChecker, dynamicConfigurationManager, clock)
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
phoneNumberIdentifiers, rateLimiters, accountsManager, registrationFraudChecker,
dynamicConfigurationManager, clock)
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
@@ -25,6 +25,7 @@ import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
public class PhoneVerificationTokenManager {
@@ -33,13 +34,17 @@ public class PhoneVerificationTokenManager {
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
private static final long VERIFICATION_TIMEOUT_SECONDS = REGISTRATION_RPC_TIMEOUT.plusSeconds(1).getSeconds();
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RegistrationServiceClient registrationServiceClient;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final RegistrationRecoveryChecker registrationRecoveryChecker;
public PhoneVerificationTokenManager(final RegistrationServiceClient registrationServiceClient,
public PhoneVerificationTokenManager(final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RegistrationServiceClient registrationServiceClient,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final RegistrationRecoveryChecker registrationRecoveryChecker) {
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.registrationServiceClient = registrationServiceClient;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.registrationRecoveryChecker = registrationRecoveryChecker;
@@ -109,7 +114,7 @@ public class PhoneVerificationTokenManager {
throw new ForbiddenException("recoveryPassword couldn't be verified");
}
try {
final boolean verified = registrationRecoveryPasswordsManager.verify(number, recoveryPassword)
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(), recoveryPassword)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (!verified) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
@@ -23,11 +23,11 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.Svr3Credentials;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -157,7 +157,7 @@ public class RegistrationLockVerificationManager {
// This allows users to re-register via registration recovery password
// instead of always being forced to fall back to SMS verification.
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
registrationRecoveryPasswordsManager.removeForNumber(updatedAccount.getNumber());
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
}
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
@@ -48,7 +48,7 @@ import org.whispersystems.textsecuregcm.util.Util;
*/
public class BackupAuthManager {
private static final Logger logger = LoggerFactory.getLogger(BackupManager.class);
private static final Logger logger = LoggerFactory.getLogger(BackupAuthManager.class);
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
@@ -235,13 +235,28 @@ public class BackupAuthManager {
.withDescription("receipt serial is already redeemed")
.asRuntimeException();
}
return accountsManager.updateAsync(account, a -> {
final Account.BackupVoucher newPayment = new Account.BackupVoucher(receiptLevel, receiptExpiration);
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
a.setBackupVoucher(merge(existingPayment, newPayment));
});
})
.thenRun(Util.NOOP);
return extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
});
}
/**
* Extend the duration of the backup voucher on an account.
*
* @param account The account to update
* @param backupVoucher The backup voucher to apply to this account
* @return A future that completes once the account has been updated to have at least the level and expiration
* in the provided voucher.
*/
public CompletableFuture<Void> extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
return accountsManager.updateAsync(account, a -> {
// Receipt credential expirations must be day aligned. Make sure any manually set backupVoucher is also day
// aligned
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
backupVoucher.receiptLevel(),
backupVoucher.expiration().truncatedTo(ChronoUnit.DAYS));
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
a.setBackupVoucher(merge(existingPayment, newPayment));
}).thenRun(Util.NOOP);
}
private static Account.BackupVoucher merge(@Nullable final Account.BackupVoucher prev,
@@ -0,0 +1,19 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.time.Duration;
/**
* Configuration for Apple DeviceCheck
*
* @param production Whether this is for production or sandbox attestations
* @param teamId The teamId to validate attestations against
* @param bundleId The bundleId to validation attestations against
*/
public record AppleDeviceCheckConfiguration(
boolean production,
String teamId,
String bundleId) {}
@@ -0,0 +1,15 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.time.Duration;
/**
* Configuration for Device Check operations
*
* @param backupRedemptionDuration How long to grant backup access for redemptions via device check
* @param backupRedemptionLevel What backup level to grant redemptions via device check
*/
public record DeviceCheckConfiguration(Duration backupRedemptionDuration, long backupRedemptionLevel) {}
@@ -48,6 +48,8 @@ public class DynamoDbTables {
private final AccountsTableConfiguration accounts;
private final Table appleDeviceChecks;
private final Table appleDeviceCheckPublicKeys;
private final Table backups;
private final Table clientPublicKeys;
private final Table clientReleases;
@@ -74,6 +76,8 @@ public class DynamoDbTables {
public DynamoDbTables(
@JsonProperty("accounts") final AccountsTableConfiguration accounts,
@JsonProperty("appleDeviceChecks") final Table appleDeviceChecks,
@JsonProperty("appleDeviceCheckPublicKeys") final Table appleDeviceCheckPublicKeys,
@JsonProperty("backups") final Table backups,
@JsonProperty("clientPublicKeys") final Table clientPublicKeys,
@JsonProperty("clientReleases") final Table clientReleases,
@@ -99,6 +103,8 @@ public class DynamoDbTables {
@JsonProperty("verificationSessions") final Table verificationSessions) {
this.accounts = accounts;
this.appleDeviceChecks = appleDeviceChecks;
this.appleDeviceCheckPublicKeys = appleDeviceCheckPublicKeys;
this.backups = backups;
this.clientPublicKeys = clientPublicKeys;
this.clientReleases = clientReleases;
@@ -130,6 +136,18 @@ public class DynamoDbTables {
return accounts;
}
@NotNull
@Valid
public Table getAppleDeviceChecks() {
return appleDeviceChecks;
}
@NotNull
@Valid
public Table getAppleDeviceCheckPublicKeys() {
return appleDeviceCheckPublicKeys;
}
@NotNull
@Valid
public Table getBackups() {
@@ -7,22 +7,37 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import java.time.Duration;
import java.util.EnumMap;
import java.util.Map;
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithExpiration {
private final byte[] generator;
/**
* The maximum number of issued receipts the issued receipt manager should issue for a particular itemId
*/
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
public IssuedReceiptsTableConfiguration(
@JsonProperty("tableName") final String tableName,
@JsonProperty("expiration") final Duration expiration,
@JsonProperty("generator") final byte[] generator) {
@JsonProperty("generator") final byte[] generator,
@JsonProperty("maxIssuedReceiptsPerPaymentId") final Map<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
super(tableName, expiration);
this.generator = generator;
this.maxIssuedReceiptsPerPaymentId = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxIssuedReceiptsPerPaymentId);
}
@NotEmpty
public byte[] getGenerator() {
return generator;
}
public EnumMap<PaymentProvider, Integer> getmaxIssuedReceiptsPerPaymentId() {
return maxIssuedReceiptsPerPaymentId;
}
}
@@ -13,7 +13,9 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public record SecureValueRecovery3Configuration(
@NotBlank String uri,
@NotBlank String backend1Uri,
@NotBlank String backend2Uri,
@NotBlank String backend3Uri,
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
@ExactlySize(32) SecretBytes userIdTokenSharedSecret,
@NotEmpty List<@NotBlank String> svrCaCertificates,
@@ -68,10 +68,6 @@ public class DynamicConfiguration {
@Valid
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false);
@JsonProperty
@Valid
DynamicMessagesConfiguration messagesConfiguration = new DynamicMessagesConfiguration();
@JsonProperty
@Valid
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
@@ -130,10 +126,6 @@ public class DynamicConfiguration {
return metricsConfiguration;
}
public DynamicMessagesConfiguration getMessagesConfiguration() {
return messagesConfiguration;
}
public List<String> getSvrStatusCodesToIgnoreForAccountDeletion() {
return svrStatusCodesToIgnoreForAccountDeletion;
}
@@ -1,13 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
public record DynamicMessagesConfiguration(boolean useSharedMrmData) {
public DynamicMessagesConfiguration() {
this(false);
}
}
@@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameLinkHandle;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -259,7 +260,7 @@ public class AccountController {
// if registration recovery password was sent to us, store it (or refresh its expiration)
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager.storeForCurrentNumber(updatedAccount.getNumber(), registrationRecoveryPassword));
registrationRecoveryPasswordsManager.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword));
}
@GET
@@ -0,0 +1,293 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import com.fasterxml.jackson.annotation.JsonCreator;
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.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.util.Base64;
import java.util.Locale;
import org.glassfish.jersey.server.ManagedAsync;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.ChallengeNotFoundException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckKeyIdNotFoundException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckVerificationFailedException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DuplicatePublicKeyException;
import org.whispersystems.textsecuregcm.storage.devicecheck.RequestReuseException;
import org.whispersystems.textsecuregcm.storage.devicecheck.TooManyKeysException;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.websocket.auth.ReadOnly;
/**
* Process platform device attestations.
* <p>
* Device attestations allow clients that can prove that they are running a signed signal build on valid Apple hardware.
* Currently, this is only used to allow beta builds to access backup functionality, since in-app purchases are not
* available iOS TestFlight builds.
*/
@Path("/v1/devicecheck")
@io.swagger.v3.oas.annotations.tags.Tag(name = "DeviceCheck")
public class DeviceCheckController {
private final Clock clock;
private final BackupAuthManager backupAuthManager;
private final AppleDeviceCheckManager deviceCheckManager;
private final RateLimiters rateLimiters;
private final long backupRedemptionLevel;
private final Duration backupRedemptionDuration;
public DeviceCheckController(
final Clock clock,
final BackupAuthManager backupAuthManager,
final AppleDeviceCheckManager deviceCheckManager,
final RateLimiters rateLimiters,
final long backupRedemptionLevel,
final Duration backupRedemptionDuration) {
this.clock = clock;
this.backupAuthManager = backupAuthManager;
this.deviceCheckManager = deviceCheckManager;
this.backupRedemptionLevel = backupRedemptionLevel;
this.backupRedemptionDuration = backupRedemptionDuration;
this.rateLimiters = rateLimiters;
}
public record ChallengeResponse(
@Schema(description = "A challenge to use when generating attestations or assertions")
String challenge) {}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/attest")
@Operation(summary = "Fetch an attest challenge", description = """
Retrieve a challenge to use in an attestation, which should be provided at `PUT /v1/devicecheck/attest`. To
produce the clientDataHash for [attestKey](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:))
take the SHA256 of the UTF-8 bytes of the returned challenge.
Repeat calls to retrieve a challenge may return the same challenge until it is used in a `PUT`. Callers should
have a single outstanding challenge at any given time.
""")
@ApiResponse(responseCode = "200", description = "The response body includes a challenge")
@ApiResponse(responseCode = "429", description = "Ratelimited.")
@ManagedAsync
public ChallengeResponse attestChallenge(@ReadOnly @Auth AuthenticatedDevice authenticatedDevice)
throws RateLimitExceededException {
rateLimiters.forDescriptor(RateLimiters.For.DEVICE_CHECK_CHALLENGE)
.validate(authenticatedDevice.getAccount().getUuid());
return new ChallengeResponse(deviceCheckManager.createChallenge(
AppleDeviceCheckManager.ChallengeType.ATTEST,
authenticatedDevice.getAccount()));
}
@PUT
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Path("/attest")
@Operation(summary = "Register a keyId", description = """
Register a keyId with an attestation, which can be used to generate assertions from this account.
The attestation should use the SHA-256 of a challenge retrieved at `GET /v1/devicecheck/attest` as the
`clientDataHash`
Registration is idempotent, and you should retry network errors with the same challenge as suggested by [device
check](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:)#discussion),
as long as your challenge has not expired (410). Even if your challenge is expired, you may continue to retry with
your original keyId (and a fresh challenge).
""")
@ApiResponse(responseCode = "204", description = "The keyId was successfully added to the account")
@ApiResponse(responseCode = "410", description = "There was no challenge associated with the account. It may have expired.")
@ApiResponse(responseCode = "401", description = "The attestation could not be verified")
@ApiResponse(responseCode = "413", description = "There are too many unique keyIds associated with this account. This is an unrecoverable error.")
@ApiResponse(responseCode = "409", description = "The provided keyId has already been registered to a different account")
@ManagedAsync
public void attest(
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
@Valid
@NotNull
@Parameter(description = "The keyId, encoded with padded url-safe base64")
@QueryParam("keyId") final String keyId,
@RequestBody(description = "The attestation data, created by [attestKey](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:))")
@NotNull final byte[] attestation) {
try {
deviceCheckManager.registerAttestation(authenticatedDevice.getAccount(), parseKeyId(keyId), attestation);
} catch (TooManyKeysException e) {
throw new WebApplicationException(Response.status(413).build());
} catch (ChallengeNotFoundException e) {
throw new WebApplicationException(Response.status(410).build());
} catch (DeviceCheckVerificationFailedException e) {
throw new WebApplicationException(e.getMessage(), Response.status(401).build());
} catch (DuplicatePublicKeyException e) {
throw new WebApplicationException(Response.status(409).build());
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/assert")
@Operation(summary = "Fetch an assert challenge", description = """
Retrieve a challenge to use in an attestation, which must be provided at `POST /v1/devicecheck/assert`. To produce
the `clientDataHash` for [generateAssertion](https://developer.apple.com/documentation/devicecheck/dcappattestservice/generateassertion(_:clientdatahash:completionhandler:)),
construct the request you intend to `POST` and include the returned challenge as the "challenge"
field. Serialize the request as JSON and take the SHA256 of the request, as described [here](https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity#Assert-your-apps-validity-as-necessary).
Note that the JSON body provided to the PUT must exactly match the input to the `clientDataHash` (field order,
whitespace, etc matters)
Repeat calls to retrieve a challenge may return the same challenge until it is used in a `POST`. Callers should
attempt to only have a single outstanding challenge at any given time.
""")
@ApiResponse(responseCode = "200", description = "The response body includes a challenge")
@ApiResponse(responseCode = "429", description = "Ratelimited.")
@ManagedAsync
public ChallengeResponse assertChallenge(
@ReadOnly @Auth AuthenticatedDevice authenticatedDevice,
@Parameter(schema = @Schema(description = "The type of action you will make an assertion for",
allowableValues = {"backup"},
implementation = String.class))
@QueryParam("action") Action action) throws RateLimitExceededException {
rateLimiters.forDescriptor(RateLimiters.For.DEVICE_CHECK_CHALLENGE)
.validate(authenticatedDevice.getAccount().getUuid());
return new ChallengeResponse(
deviceCheckManager.createChallenge(toChallengeType(action),
authenticatedDevice.getAccount()));
}
@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Path("/assert")
@Operation(summary = "Perform an attested action", description = """
Specify some action to take on the account via the request field. The request must exactly match the request you
provide when [generating the assertion](https://developer.apple.com/documentation/devicecheck/dcappattestservice/generateassertion(_:clientdatahash:completionhandler:)).
The request must include a challenge previously retrieved from `GET /v1/devicecheck/assert`.
Each assertion increments the counter associated with the client's device key. This method enforces that no
assertion with a counter lower than a counter we've already seen is allowed to execute. If a client issues
multiple requests concurrently, or if they retry a request that had an indeterminate outcome, it's possible that
the request will not be accepted because the server has already stored the updated counter. In this case the
request may return 401, and the client should generate a fresh assert for the request.
""")
@ApiResponse(responseCode = "204", description = "The assertion was valid and the corresponding action was executed")
@ApiResponse(responseCode = "404", description = "The provided keyId was not found")
@ApiResponse(responseCode = "410", description = "There was no challenge associated with the account. It may have expired.")
@ApiResponse(responseCode = "401", description = "The assertion could not be verified")
@ManagedAsync
public void assertion(
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
@Valid
@NotNull
@Parameter(description = "The keyId, encoded with padded url-safe base64")
@QueryParam("keyId") final String keyId,
@Valid
@NotNull
@Parameter(description = """
The asserted JSON request data, encoded as a string in padded url-safe base64. This must exactly match the
request you use when generating the assertion (including field ordering, whitespace, etc).
""",
schema = @Schema(implementation = AssertionRequest.class))
@QueryParam("request") final DeviceCheckController.AssertionRequestWrapper request,
@RequestBody(description = "The assertion created by [generateAssertion](https://developer.apple.com/documentation/devicecheck/dcappattestservice/generateassertion(_:clientdatahash:completionhandler:))")
@NotNull final byte[] assertion) {
try {
deviceCheckManager.validateAssert(
authenticatedDevice.getAccount(),
parseKeyId(keyId),
toChallengeType(request.assertionRequest().action()),
request.assertionRequest().challenge(),
request.rawJson(),
assertion);
} catch (ChallengeNotFoundException e) {
throw new WebApplicationException(Response.status(410).build());
} catch (DeviceCheckVerificationFailedException e) {
throw new WebApplicationException(e.getMessage(), Response.status(401).build());
} catch (DeviceCheckKeyIdNotFoundException | RequestReuseException e) {
throw new WebApplicationException(Response.status(404).build());
}
// The request assertion was validated, execute it
switch (request.assertionRequest().action()) {
case BACKUP -> backupAuthManager.extendBackupVoucher(
authenticatedDevice.getAccount(),
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)))
.join();
}
}
public enum Action {
BACKUP;
@JsonCreator
public static Action fromString(final String action) {
for (final Action a : Action.values()) {
if (a.name().toLowerCase(Locale.ROOT).equals(action)) {
return a;
}
}
throw new IllegalArgumentException("Invalid action: " + action);
}
}
public record AssertionRequest(
@Schema(description = "The challenge retrieved at `GET /v1/devicecheck/assert`")
String challenge,
@Schema(description = "The type of action you'd like to perform with this assert",
allowableValues = {"backup"}, implementation = String.class)
Action action) {}
/*
* Parses the base64 encoded AssertionRequest, but preserves the rawJson as well
*/
public record AssertionRequestWrapper(AssertionRequest assertionRequest, byte[] rawJson) {
public static AssertionRequestWrapper fromString(String requestBase64) throws IOException {
final byte[] requestJson = Base64.getUrlDecoder().decode(requestBase64);
final AssertionRequest requestData = SystemMapper.jsonMapper().readValue(requestJson, AssertionRequest.class);
return new AssertionRequestWrapper(requestData, requestJson);
}
}
private static AppleDeviceCheckManager.ChallengeType toChallengeType(final Action action) {
return switch (action) {
case BACKUP -> AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION;
};
}
private static byte[] parseKeyId(final String base64KeyId) {
try {
return Base64.getUrlDecoder().decode(base64KeyId);
} catch (IllegalArgumentException e) {
throw new WebApplicationException(Response.status(422).entity(e.getMessage()).build());
}
}
}
@@ -65,6 +65,7 @@ import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
@@ -141,9 +142,13 @@ public class DeviceController {
@GET
@Produces(MediaType.APPLICATION_JSON)
public DeviceInfoList getDevices(@ReadOnly @Auth AuthenticatedDevice auth) {
return new DeviceInfoList(auth.getAccount().getDevices().stream()
.map(DeviceInfo::forDevice)
.toList());
// Devices may change their own names (and primary devices may change the names of linked devices) and so the device
// state associated with the authenticated account may be stale. Fetch a fresh copy to compensate.
return accounts.getByAccountIdentifier(auth.getAccount().getIdentifier(IdentityType.ACI))
.map(account -> new DeviceInfoList(account.getDevices().stream()
.map(DeviceInfo::forDevice)
.toList()))
.orElseThrow(ForbiddenException::new);
}
@DELETE
@@ -398,14 +403,6 @@ public class DeviceController {
}
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/unauthenticated_delivery")
public void setUnauthenticatedDelivery(@Mutable @Auth AuthenticatedDevice auth) {
assert (auth.getAuthenticatedDevice() != null);
// Deprecated
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/capabilities")
@@ -522,8 +519,10 @@ public class DeviceController {
@Operation(
summary = "Signals that a transfer archive has been uploaded for a specific linked device",
description = """
Signals that a transfer archive has been uploaded for a specific linked device. Devices waiting via the "wait
for transfer archive" endpoint will be notified that the new archive is available.
Signals that a transfer archive has been uploaded or failed for a specific linked device. Devices waiting via
the "wait for transfer archive" endpoint will be notified that the new archive is available.
If the uploader cannot upload the transfer archive, they must signal an error.
""")
@ApiResponse(responseCode = "204", description = "Success")
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
@@ -546,8 +545,11 @@ public class DeviceController {
Waits for a new transfer archive to be uploaded for the authenticated device and returns the location of the
archive when available.
""")
@ApiResponse(responseCode = "200", description = "A new transfer archive was uploaded for the authenticated device",
content = @Content(schema = @Schema(implementation = RemoteAttachment.class)))
@ApiResponse(responseCode = "200", description = "Either a new transfer archive was uploaded for the authenticated device, or the upload has failed",
content = @Content(schema = @Schema(description = """
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
the upload has failed and the destination device should stop waiting
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})))
@ApiResponse(responseCode = "204", description = "No transfer archive was uploaded before the call completed; clients may repeat the call to continue waiting")
@ApiResponse(responseCode = "400", description = "The given timeout was invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
@@ -123,6 +123,7 @@ import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -157,6 +158,7 @@ public class MessageController {
private final ReceiptSender receiptSender;
private final AccountsManager accountsManager;
private final MessagesManager messagesManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ReportMessageManager reportMessageManager;
@@ -216,6 +218,7 @@ public class MessageController {
ReceiptSender receiptSender,
AccountsManager accountsManager,
MessagesManager messagesManager,
PhoneNumberIdentifiers phoneNumberIdentifiers,
PushNotificationManager pushNotificationManager,
PushNotificationScheduler pushNotificationScheduler,
ReportMessageManager reportMessageManager,
@@ -234,6 +237,7 @@ public class MessageController {
this.receiptSender = receiptSender;
this.accountsManager = accountsManager;
this.messagesManager = messagesManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.reportMessageManager = reportMessageManager;
@@ -853,10 +857,10 @@ public class MessageController {
@Nullable SpamReport spamReport,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent
) {
final Optional<String> sourceNumber;
final Optional<UUID> sourceAci;
final Optional<UUID> sourcePni;
if (source.startsWith("+")) {
sourceNumber = Optional.of(source);
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
@@ -864,8 +868,8 @@ public class MessageController {
sourceAci = maybeAccount.map(Account::getUuid);
sourcePni = maybeAccount.map(Account::getPhoneNumberIdentifier);
} else {
sourceAci = accountsManager.findRecentlyDeletedAccountIdentifier(source);
sourcePni = Optional.ofNullable(accountsManager.getPhoneNumberIdentifier(source));
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
}
} else {
sourceAci = Optional.of(UUID.fromString(source));
@@ -874,8 +878,9 @@ public class MessageController {
if (sourceAccount.isEmpty()) {
logger.warn("Could not find source: {}", sourceAci.get());
sourceNumber = accountsManager.findRecentlyDeletedE164(sourceAci.get());
sourcePni = sourceNumber.map(accountsManager::getPhoneNumberIdentifier);
sourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceAci.get());
sourceNumber = sourcePni.flatMap(pni ->
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
} else {
sourceNumber = sourceAccount.map(Account::getNumber);
sourcePni = sourceAccount.map(Account::getPhoneNumberIdentifier);
@@ -952,9 +957,6 @@ public class MessageController {
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
// mrm views phase 3: always set content
messageBuilder.setContent(ByteString.copyFrom(payload));
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
}
@@ -78,7 +78,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
@io.swagger.v3.oas.annotations.tags.Tag(name = "OneTimeDonations")
public class OneTimeDonationController {
private static final Logger logger = LoggerFactory.getLogger(SubscriptionController.class);
private static final Logger logger = LoggerFactory.getLogger(OneTimeDonationController.class);
private static final String EURO_CURRENCY_CODE = "EUR";
@@ -343,9 +343,14 @@ public class SubscriptionController {
public record Error(SetSubscriptionLevelErrorResponse.Error.Type type, String message) {
public enum Type {
// The requested level was invalid
UNSUPPORTED_LEVEL,
// The requested currency was invalid
UNSUPPORTED_CURRENCY,
// The card could not be charged
PAYMENT_REQUIRES_ACTION,
// The request arguments were invalid representing a programmer error
INVALID_ARGUMENTS
}
}
}
@@ -391,6 +396,12 @@ public class SubscriptionController {
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
.build());
}))
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
.build());
}))
.thenApply(unused -> Response.ok(new SetSubscriptionLevelSuccessResponse(level)).build());
}
@@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker.VerificationCheck;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -116,6 +117,7 @@ public class VerificationController {
private final PushNotificationManager pushNotificationManager;
private final RegistrationCaptchaManager registrationCaptchaManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RateLimiters rateLimiters;
private final AccountsManager accountsManager;
private final RegistrationFraudChecker registrationFraudChecker;
@@ -127,6 +129,7 @@ public class VerificationController {
final PushNotificationManager pushNotificationManager,
final RegistrationCaptchaManager registrationCaptchaManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RateLimiters rateLimiters,
final AccountsManager accountsManager,
final RegistrationFraudChecker registrationFraudChecker,
@@ -137,6 +140,7 @@ public class VerificationController {
this.pushNotificationManager = pushNotificationManager;
this.registrationCaptchaManager = registrationCaptchaManager;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.rateLimiters = rateLimiters;
this.accountsManager = accountsManager;
this.registrationFraudChecker = registrationFraudChecker;
@@ -156,7 +160,7 @@ public class VerificationController {
final Phonenumber.PhoneNumber phoneNumber;
try {
phoneNumber = PhoneNumberUtil.getInstance().parse(request.getNumber(), null);
phoneNumber = Util.canonicalizePhoneNumber(PhoneNumberUtil.getInstance().parse(request.getNumber(), null));
} catch (final NumberParseException e) {
throw new ServerErrorException("could not parse already validated number", Response.Status.INTERNAL_SERVER_ERROR);
}
@@ -598,7 +602,7 @@ public class VerificationController {
}
if (resultSession.verified()) {
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
Metrics.counter(VERIFIED_COUNTER_NAME, Tags.of(
@@ -626,8 +630,8 @@ public class VerificationController {
}
/**
* @throws ClientErrorException with {@code 422} status if the ID cannot be decoded
* @throws javax.ws.rs.NotFoundException if the ID cannot be found
* @throws ClientErrorException with {@code 422} status if the ID cannot be decoded
* @throws NotFoundException if the ID cannot be found
*/
private RegistrationServiceSession retrieveRegistrationServiceSession(final String encodedSessionId) {
final byte[] sessionId;
@@ -644,7 +648,7 @@ public class VerificationController {
.orElseThrow(NotFoundException::new);
if (registrationServiceSession.verified()) {
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
return registrationServiceSession;
@@ -20,6 +20,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.E164;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
@@ -34,6 +35,7 @@ public record ChangeNumberRequest(
Must not be combined with `sessionId`.""")
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class) byte[] recoveryPassword,
@E164
@Schema(description="the new phone number for this account")
@NotBlank String number,
@@ -9,8 +9,11 @@ import java.util.Base64;
import javax.annotation.Nullable;
import org.signal.registration.rpc.RegistrationSessionMetadata;
public record RegistrationServiceSession(byte[] id, String number, boolean verified,
@Nullable Long nextSms, @Nullable Long nextVoiceCall,
public record RegistrationServiceSession(byte[] id,
String number,
boolean verified,
@Nullable Long nextSms,
@Nullable Long nextVoiceCall,
@Nullable Long nextVerificationAttempt,
long expiration) {
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.whispersystems.textsecuregcm.util.ValidBase64URLString;
public record RemoteAttachment(
@@ -17,6 +18,6 @@ public record RemoteAttachment(
@NotBlank
@ValidBase64URLString
@Schema(description = "The attachment key")
String key) {
}
@Size(max = 64)
@Schema(description = "The attachment key", maxLength = 64)
String key) implements TransferArchiveResult {}
@@ -0,0 +1,21 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@Schema(description = "Indicates an attachment failed to upload")
public record RemoteAttachmentError(
@Schema(description = "The type of error encountered")
@Valid @NotNull ErrorType error)
implements TransferArchiveResult {
public enum ErrorType {
RELINK_REQUESTED,
CONTINUE_WITHOUT_UPLOAD;
}
}
@@ -0,0 +1,17 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.swagger.v3.oas.annotations.media.Schema;
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
@JsonSubTypes.Type(value = RemoteAttachment.class, name = "success"),
@JsonSubTypes.Type(value = RemoteAttachmentError.class, name = "error"),
})
public sealed interface TransferArchiveResult permits RemoteAttachment, RemoteAttachmentError {}
@@ -9,19 +9,24 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import org.whispersystems.textsecuregcm.storage.Device;
public record TransferArchiveUploadedRequest(@Min(1)
@Max(Device.MAXIMUM_DEVICE_ID)
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
byte destinationDeviceId,
public record TransferArchiveUploadedRequest(
@Min(1)
@Max(Device.MAXIMUM_DEVICE_ID)
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
byte destinationDeviceId,
@Positive
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
long destinationDeviceCreated,
@Positive
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
long destinationDeviceCreated,
@Schema(description = "The location of the transfer archive")
@Valid
RemoteAttachment transferArchive) {
}
@NotNull
@Valid
@Schema(description = """
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
the upload has failed and the destination device should stop waiting
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
TransferArchiveResult transferArchive) {}
@@ -47,6 +47,7 @@ import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -336,7 +337,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.storeForCurrentNumber(account.getNumber(), request.getRegistrationRecoveryPassword().toByteArray())))
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI), request.getRegistrationRecoveryPassword().toByteArray())))
.thenReturn(SetRegistrationRecoveryPasswordResponse.newBuilder().build());
}
}
@@ -57,6 +57,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
WAIT_FOR_TRANSFER_ARCHIVE("waitForTransferArchive", true, new RateLimiterConfig(10, Duration.ofSeconds(30))),
RECORD_DEVICE_TRANSFER_REQUEST("recordDeviceTransferRequest", true, new RateLimiterConfig(10, Duration.ofMillis(100))),
WAIT_FOR_DEVICE_TRANSFER_REQUEST("waitForDeviceTransferRequest", true, new RateLimiterConfig(10, Duration.ofMillis(100))),
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", true, new RateLimiterConfig(10, Duration.ofMinutes(1))),
;
private final String id;
@@ -4,16 +4,15 @@ import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.MetricRecord;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.MetricRecord;
/**
* A Micrometer AWS SDK metric publisher consumes {@link MetricCollection} instances provided by the AWS SDK when it
@@ -80,6 +79,9 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
private static final String CONCURRENT_REQUESTS_DISTRIBUTION_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "concurrentRequests");
private static final String MAX_CONCURRENCY_GAUGE_NAME =
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "maxConcurrency");
private static final String CLIENT_NAME_TAG = "clientName";
/**
@@ -93,7 +95,7 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
this.recordMetricsExecutorService = recordMetricsExecutorService;
this.awsClientName = awsClientName;
mostRecentMaxConcurrency = Metrics.gauge("maxConcurrency",
mostRecentMaxConcurrency = Metrics.gauge(MAX_CONCURRENCY_GAUGE_NAME,
Tags.of(CLIENT_NAME_TAG, awsClientName),
new AtomicInteger(0));
}
@@ -0,0 +1,86 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.securevaluerecovery;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.HttpUtils;
import java.net.URI;
import java.net.http.HttpClient;
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.stream.Stream;
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicAuthHeader;
/**
* A client for sending requests to Signal's secure value recovery v3 service on behalf of authenticated users.
*/
public class SecureValueRecovery3Client {
private final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator;
private final URI backend1Uri;
private final URI backend2Uri;
private final URI backend3Uri;
private final FaultTolerantHttpClient httpClient;
@VisibleForTesting
static final String DELETE_PATH = "/v1/delete";
public SecureValueRecovery3Client(final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator,
final Executor executor, final ScheduledExecutorService retryExecutor,
final SecureValueRecovery3Configuration configuration)
throws CertificateException {
this.secureValueRecoveryCredentialsGenerator = secureValueRecoveryCredentialsGenerator;
this.backend1Uri = URI.create(configuration.backend1Uri()).resolve(DELETE_PATH);
this.backend2Uri = URI.create(configuration.backend2Uri()).resolve(DELETE_PATH);
this.backend3Uri = URI.create(configuration.backend3Uri()).resolve(DELETE_PATH);
this.httpClient = FaultTolerantHttpClient.newBuilder()
.withCircuitBreaker(configuration.circuitBreaker())
.withRetry(configuration.retry())
.withRetryExecutor(retryExecutor)
.withVersion(HttpClient.Version.HTTP_1_1)
.withConnectTimeout(Duration.ofSeconds(10))
.withRedirect(HttpClient.Redirect.NEVER)
.withExecutor(executor)
.withName("secure-value-recovery3")
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_2)
.withTrustedServerCertificates(configuration.svrCaCertificates().toArray(String[]::new))
.build();
}
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) {
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid);
final List<CompletableFuture<HttpResponse<String>>> futures = Stream.of(backend1Uri, backend2Uri, backend3Uri)
.map(uri -> HttpRequest.newBuilder()
.uri(uri)
.DELETE()
.header(HttpHeaders.AUTHORIZATION, basicAuthHeader(credentials))
.build())
.map(request -> httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()))
.toList();
return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new))
.thenApply(ignored -> futures.stream().map(CompletableFuture::join).toList())
.thenAccept(responses -> responses.forEach(response -> {
if (!HttpUtils.isSuccessfulResponse(response.statusCode())) {
throw new SecureValueRecoveryException(String.format("Failed to delete backup in %s", response.uri()), 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.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
@@ -19,12 +20,12 @@ public class AccountLockManager {
private final AmazonDynamoDBLockClient lockClient;
static final String KEY_ACCOUNT_E164 = "P";
static final String KEY_ACCOUNT_PNI = "P";
public AccountLockManager(final DynamoDbClient lockDynamoDb, final String lockTableName) {
this(new AmazonDynamoDBLockClient(
AmazonDynamoDBLockClientOptions.builder(lockDynamoDb, lockTableName)
.withPartitionKeyName(KEY_ACCOUNT_E164)
.withPartitionKeyName(KEY_ACCOUNT_PNI)
.withLeaseDuration(15L)
.withHeartbeatPeriod(2L)
.withTimeUnit(TimeUnit.SECONDS)
@@ -38,33 +39,34 @@ public class AccountLockManager {
}
/**
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone numbers. By design, the
* accounts need not actually exist in order to acquire a lock; this allows lock acquisition for operations that span
* account lifecycle changes (like deleting an account or changing a phone number). The given task runs once locks for
* all given phone numbers have been acquired, and the locks are released as soon as the task completes by any means.
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone number identifiers. By
* design, the accounts need not actually exist in order to acquire a lock; this allows lock acquisition for
* operations that span account lifecycle changes (like deleting an account or changing a phone number). The given
* task runs once locks for all given identifiers have been acquired, and the locks are released as soon as the task
* completes by any means.
*
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
* @param task the task to execute once locks have been acquired
* @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
* @param task the task to execute once locks have been acquired
* @param lockAcquisitionExecutor the executor on which to run blocking lock acquire/release tasks. this executor
* should not use virtual threads.
*
* @throws InterruptedException if interrupted while acquiring a lock
*/
public void withLock(final List<String> e164s, final Runnable task, final Executor lockAcquisitionExecutor) {
if (e164s.isEmpty()) {
throw new IllegalArgumentException("List of e164s to lock must not be empty");
public void withLock(final List<UUID> phoneNumberIdentifiers, final Runnable task,
final Executor lockAcquisitionExecutor) {
if (phoneNumberIdentifiers.isEmpty()) {
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
}
final List<LockItem> lockItems = new ArrayList<>(e164s.size());
final List<LockItem> lockItems = new ArrayList<>(phoneNumberIdentifiers.size());
try {
// Offload the acquire/release tasks to the dedicated lock acquisition executor. The lock client performs blocking
// operations while holding locks which forces thread pinning when this method runs on a virtual thread.
// https://github.com/awslabs/amazon-dynamodb-lock-client/issues/97
CompletableFuture.runAsync(() -> {
for (final String e164 : e164s) {
for (final UUID pni : phoneNumberIdentifiers) {
try {
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(e164)
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
.withAcquireReleasedLocksConsistently(true)
.build()));
} catch (final InterruptedException e) {
@@ -86,32 +88,31 @@ public class AccountLockManager {
}
/**
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone numbers. By design, the
* accounts need not actually exist in order to acquire a lock; this allows lock acquisition for operations that span
* account lifecycle changes (like deleting an account or changing a phone number). The given task runs once locks for
* all given phone numbers have been acquired, and the locks are released as soon as the task completes by any means.
*
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
* @param taskSupplier a supplier for the task to execute once locks have been acquired
* @param executor the executor on which to acquire and release locks
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone number identifiers. By
* design, the accounts need not actually exist in order to acquire a lock; this allows lock acquisition for
* operations that span account lifecycle changes (like deleting an account or changing a phone number). The given
* task runs once locks for all given identifiers have been acquired, and the locks are released as soon as the task
* completes by any means.
*
* @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
* @param taskSupplier a supplier for the task to execute once locks have been acquired
* @param executor the executor on which to acquire and release locks
* @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<String> e164s,
final Supplier<CompletableFuture<T>> taskSupplier,
final Executor executor) {
public <T> CompletableFuture<T> withLockAsync(final List<UUID> phoneNumberIdentifiers,
final Supplier<CompletableFuture<T>> taskSupplier, final Executor executor) {
if (e164s.isEmpty()) {
throw new IllegalArgumentException("List of e164s to lock must not be empty");
if (phoneNumberIdentifiers.isEmpty()) {
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
}
final List<LockItem> lockItems = new ArrayList<>(e164s.size());
final List<LockItem> lockItems = new ArrayList<>(phoneNumberIdentifiers.size());
return CompletableFuture.runAsync(() -> {
for (final String e164 : e164s) {
for (final UUID pni : phoneNumberIdentifiers) {
try {
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(e164)
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
.withAcquireReleasedLocksConsistently(true)
.build()));
} catch (final InterruptedException e) {
@@ -79,7 +79,7 @@ import software.amazon.awssdk.utils.CompletableFutureUtils;
* make sure the field is stored in a DDB attribute and then put back into the account object in {@link Accounts#fromItem(Map)}.
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class Accounts extends AbstractDynamoDbStore {
public class Accounts {
private static final Logger log = LoggerFactory.getLogger(Accounts.class);
@@ -136,10 +136,13 @@ public class Accounts extends AbstractDynamoDbStore {
// unidentified access key; byte[] or null
static final String ATTR_UAK = "UAK";
static final String DELETED_ACCOUNTS_KEY_ACCOUNT_E164 = "P";
// For historical reasons, deleted-accounts PNI is stored as a string-format UUID rather than a
// compact byte array.
static final String DELETED_ACCOUNTS_KEY_ACCOUNT_PNI = "P";
static final String DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID = "U";
static final String DELETED_ACCOUNTS_ATTR_EXPIRES = "E";
static final String DELETED_ACCOUNTS_UUID_TO_E164_INDEX_NAME = "u_to_p";
static final String DELETED_ACCOUNTS_UUID_TO_PNI_INDEX_NAME = "u_to_p";
static final String USERNAME_LINK_TO_UUID_INDEX = "ul_to_u";
@@ -159,7 +162,8 @@ public class Accounts extends AbstractDynamoDbStore {
private final Clock clock;
private final DynamoDbAsyncClient asyncClient;
private final DynamoDbClient dynamoDbClient;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String phoneNumberConstraintTableName;
private final String phoneNumberIdentifierConstraintTableName;
@@ -168,11 +172,10 @@ public class Accounts extends AbstractDynamoDbStore {
private final String usedLinkDeviceTokenTableName;
private final String accountsTableName;
@VisibleForTesting
public Accounts(
final Clock clock,
final DynamoDbClient client,
final DynamoDbAsyncClient asyncClient,
final DynamoDbClient dynamoDbClient,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final String accountsTableName,
final String phoneNumberConstraintTableName,
final String phoneNumberIdentifierConstraintTableName,
@@ -180,9 +183,9 @@ public class Accounts extends AbstractDynamoDbStore {
final String deletedAccountsTableName,
final String usedLinkDeviceTokenTableName) {
super(client);
this.clock = clock;
this.asyncClient = asyncClient;
this.dynamoDbClient = dynamoDbClient;
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.phoneNumberConstraintTableName = phoneNumberConstraintTableName;
this.phoneNumberIdentifierConstraintTableName = phoneNumberIdentifierConstraintTableName;
this.accountsTableName = accountsTableName;
@@ -191,21 +194,6 @@ public class Accounts extends AbstractDynamoDbStore {
this.usedLinkDeviceTokenTableName = usedLinkDeviceTokenTableName;
}
public Accounts(
final DynamoDbClient client,
final DynamoDbAsyncClient asyncClient,
final String accountsTableName,
final String phoneNumberConstraintTableName,
final String phoneNumberIdentifierConstraintTableName,
final String usernamesConstraintTableName,
final String deletedAccountsTableName,
final String usedLinkDeviceTokenTableName) {
this(Clock.systemUTC(), client, asyncClient, accountsTableName,
phoneNumberConstraintTableName, phoneNumberIdentifierConstraintTableName, usernamesConstraintTableName,
deletedAccountsTableName, usedLinkDeviceTokenTableName);
}
static class UsernameTable {
// usernameHash; bytes.
static final String KEY_USERNAME_HASH = Accounts.ATTR_USERNAME_HASH;
@@ -239,7 +227,7 @@ public class Accounts extends AbstractDynamoDbStore {
// Clear any "recently deleted account" record for this number since, if it existed, we've used its old ACI for
// the newly-created account.
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getNumber());
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier());
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete));
@@ -251,7 +239,7 @@ public class Accounts extends AbstractDynamoDbStore {
.build();
try {
db().transactWriteItems(request);
dynamoDbClient.transactWriteItems(request);
} catch (final TransactionCanceledException e) {
final CancellationReason accountCancellationReason = e.cancellationReasons().get(2);
@@ -266,8 +254,9 @@ public class Accounts extends AbstractDynamoDbStore {
if (conditionalCheckFailed(phoneNumberConstraintCancellationReason)
|| conditionalCheckFailed(phoneNumberIdentifierConstraintCancellationReason)) {
// In theory, both reasons should trip in tandem and either should give us the information we need. Even so,
// we'll be cautious here and make sure we're choosing a condition check that really failed.
// Both reasons should trip in tandem and either should give us the information we need. However, phone number
// canonicalization can cause multiple e164s to have the same PNI, so we make sure we're choosing a condition
// check that really failed.
final CancellationReason reason = conditionalCheckFailed(phoneNumberConstraintCancellationReason)
? phoneNumberConstraintCancellationReason
: phoneNumberIdentifierConstraintCancellationReason;
@@ -379,7 +368,7 @@ public class Accounts extends AbstractDynamoDbStore {
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, accountToCreate).transactItem());
writeItems.addAll(additionalWriteItems);
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
.thenApply(response -> {
accountToCreate.setVersion(accountToCreate.getVersion() + 1);
return (Void) null;
@@ -435,9 +424,9 @@ public class Accounts extends AbstractDynamoDbStore {
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(number));
writeItems.add(buildRemoveDeletedAccount(phoneNumberIdentifier));
maybeDisplacedAccountIdentifier.ifPresent(displacedAccountIdentifier ->
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalNumber)));
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalPni)));
// The `catch (TransactionCanceledException) block needs to check whether the cancellation reason is the account
// update write item
@@ -473,7 +462,7 @@ public class Accounts extends AbstractDynamoDbStore {
.transactItems(writeItems)
.build();
db().transactWriteItems(request);
dynamoDbClient.transactWriteItems(request);
account.setVersion(account.getVersion() + 1);
succeeded = true;
@@ -598,7 +587,7 @@ public class Accounts extends AbstractDynamoDbStore {
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, updatedAccount).transactItem());
return asyncClient
return dynamoDbAsyncClient
.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
.thenRun(Util.NOOP)
.exceptionally(ExceptionUtils.exceptionallyHandler(TransactionCanceledException.class, e -> {
@@ -607,7 +596,7 @@ public class Accounts extends AbstractDynamoDbStore {
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
// The constraint table update failed the condition check. It could be because the username was taken,
// or because we need to retry with a longer TTL
final Map<String, AttributeValue> item = e.cancellationReasons().get(0).item();
final Map<String, AttributeValue> item = e.cancellationReasons().getFirst().item();
final UUID existingOwner = AttributeValues.getUUID(item, UsernameTable.ATTR_ACCOUNT_UUID, null);
final boolean confirmed = AttributeValues.getBool(item, UsernameTable.ATTR_CONFIRMED, false);
final long existingTtl = AttributeValues.getLong(item, UsernameTable.ATTR_TTL, 0L);
@@ -783,7 +772,7 @@ public class Accounts extends AbstractDynamoDbStore {
holdToRemove.ifPresent(oldHold ->
writeItems.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
.thenApply(ignored -> updatedAccount);
})
.thenApply(updatedAccount -> {
@@ -824,7 +813,7 @@ public class Accounts extends AbstractDynamoDbStore {
// Otherwise, there's an existing link handle. If this is the result of an account being re-registered, we should
// preserve the link handle.
return asyncClient.getItem(GetItemRequest.builder()
return dynamoDbAsyncClient.getItem(GetItemRequest.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(UsernameTable.KEY_USERNAME_HASH, AttributeValues.b(usernameHash)))
.projectionExpression(UsernameTable.ATTR_RECLAIMABLE).build())
@@ -873,7 +862,7 @@ public class Accounts extends AbstractDynamoDbStore {
// 2?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold -> items.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(items).build())
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(items).build())
.thenAccept(ignored -> {
account.setUsernameHash(null);
account.setUsernameLinkDetails(null, null);
@@ -1004,7 +993,7 @@ public class Accounts extends AbstractDynamoDbStore {
.forAccount(accountsTableName, account)
.updateItemRequest();
return asyncClient.updateItem(updateItemRequest)
return dynamoDbAsyncClient.updateItem(updateItemRequest)
.thenApply(response -> {
account.setVersion(AttributeValues.getInt(response.attributes(), "V", account.getVersion() + 1));
return (Void) null;
@@ -1054,7 +1043,7 @@ public class Accounts extends AbstractDynamoDbStore {
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, account).transactItem());
writeItems.addAll(additionalWriteItems);
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build())
.thenApply(response -> {
@@ -1065,7 +1054,7 @@ public class Accounts extends AbstractDynamoDbStore {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
if (unwrapped instanceof TransactionCanceledException transactionCanceledException) {
if (CONDITIONAL_CHECK_FAILED.equals(transactionCanceledException.cancellationReasons().get(0).code())) {
if (CONDITIONAL_CHECK_FAILED.equals(transactionCanceledException.cancellationReasons().getFirst().code())) {
throw new ContestedOptimisticLockException();
}
@@ -1153,23 +1142,23 @@ public class Accounts extends AbstractDynamoDbStore {
.map(Accounts::fromItem)));
}
private TransactWriteItem buildPutDeletedAccount(final UUID uuid, final String e164) {
private TransactWriteItem buildPutDeletedAccount(final UUID aci, final UUID pni) {
return TransactWriteItem.builder()
.put(Put.builder()
.tableName(deletedAccountsTableName)
.item(Map.of(
DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164),
DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(Instant.now().plus(DELETED_ACCOUNTS_TIME_TO_LIVE).getEpochSecond())))
DELETED_ACCOUNTS_KEY_ACCOUNT_PNI, AttributeValues.fromString(pni.toString()),
DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(aci),
DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(clock.instant().plus(DELETED_ACCOUNTS_TIME_TO_LIVE).getEpochSecond())))
.build())
.build();
}
private TransactWriteItem buildRemoveDeletedAccount(final String e164) {
private TransactWriteItem buildRemoveDeletedAccount(final UUID pni) {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(deletedAccountsTableName)
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164)))
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_PNI, AttributeValues.fromString(pni.toString())))
.build())
.build();
}
@@ -1181,35 +1170,35 @@ public class Accounts extends AbstractDynamoDbStore {
.toCompletableFuture();
}
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final String e164) {
final GetItemResponse response = db().getItem(GetItemRequest.builder()
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final UUID phoneNumberIdentifier) {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(deletedAccountsTableName)
.consistentRead(true)
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164)))
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.build());
return Optional.ofNullable(AttributeValues.getUUID(response.item(), DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, null));
}
public Optional<String> findRecentlyDeletedE164(final UUID uuid) {
final QueryResponse response = db().query(QueryRequest.builder()
public Optional<UUID> findRecentlyDeletedPhoneNumberIdentifier(final UUID uuid) {
final QueryResponse response = dynamoDbClient.query(QueryRequest.builder()
.tableName(deletedAccountsTableName)
.indexName(DELETED_ACCOUNTS_UUID_TO_E164_INDEX_NAME)
.indexName(DELETED_ACCOUNTS_UUID_TO_PNI_INDEX_NAME)
.keyConditionExpression("#uuid = :uuid")
.projectionExpression("#e164")
.projectionExpression("#pni")
.expressionAttributeNames(Map.of("#uuid", DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID,
"#e164", DELETED_ACCOUNTS_KEY_ACCOUNT_E164))
"#pni", DELETED_ACCOUNTS_KEY_ACCOUNT_PNI))
.expressionAttributeValues(Map.of(":uuid", AttributeValues.fromUUID(uuid))).build());
if (response.count() == 0) {
return Optional.empty();
}
if (response.count() > 1) {
throw new RuntimeException("Impossible result: more than one phone number returned for UUID: " + uuid);
}
return Optional.ofNullable(response.items().get(0).get(DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s());
return response.items().stream()
.map(item -> item.get(DELETED_ACCOUNTS_KEY_ACCOUNT_PNI).s())
.filter(e164OrPni -> !e164OrPni.startsWith("+"))
.findFirst()
.map(UUID::fromString);
}
public CompletableFuture<Void> delete(final UUID uuid, final List<TransactWriteItem> additionalWriteItems) {
@@ -1221,7 +1210,7 @@ public class Accounts extends AbstractDynamoDbStore {
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(accountsTableName, KEY_ACCOUNT_UUID, uuid),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getNumber())
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
@@ -1229,7 +1218,7 @@ public class Accounts extends AbstractDynamoDbStore {
transactWriteItems.addAll(additionalWriteItems);
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build())
.thenRun(Util.NOOP);
@@ -1246,7 +1235,7 @@ public class Accounts extends AbstractDynamoDbStore {
return Flux.range(0, segments)
.parallel()
.runOn(scheduler)
.flatMap(segment -> asyncClient.scanPaginator(ScanRequest.builder()
.flatMap(segment -> dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
.tableName(accountsTableName)
.consistentRead(true)
.segment(segment)
@@ -1311,7 +1300,7 @@ public class Accounts extends AbstractDynamoDbStore {
@Nonnull
private Optional<Map<String, AttributeValue>> itemByKey(final String table, final String keyName, final AttributeValue keyValue) {
final GetItemResponse response = db().getItem(GetItemRequest.builder()
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(table)
.key(Map.of(keyName, keyValue))
.consistentRead(true)
@@ -1321,7 +1310,7 @@ public class Accounts extends AbstractDynamoDbStore {
@Nonnull
private CompletableFuture<Optional<Map<String, AttributeValue>>> itemByKeyAsync(final String table, final String keyName, final AttributeValue keyValue) {
return asyncClient.getItem(GetItemRequest.builder()
return dynamoDbAsyncClient.getItem(GetItemRequest.builder()
.tableName(table)
.key(Map.of(keyName, keyValue))
.consistentRead(true)
@@ -1329,36 +1318,9 @@ public class Accounts extends AbstractDynamoDbStore {
.thenApply(response -> Optional.ofNullable(response.item()).filter(item -> !item.isEmpty()));
}
@Nonnull
private Optional<Map<String, AttributeValue>> itemByGsiKey(final String table, final String indexName, final String keyName, final AttributeValue keyValue) {
final QueryResponse response = db().query(QueryRequest.builder()
.tableName(table)
.indexName(indexName)
.keyConditionExpression("#gsiKey = :gsiValue")
.projectionExpression("#uuid")
.expressionAttributeNames(Map.of(
"#gsiKey", keyName,
"#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(
":gsiValue", keyValue))
.build());
if (response.count() == 0) {
return Optional.empty();
}
if (response.count() > 1) {
throw new IllegalStateException("More than one row located for GSI [%s], key-value pair [%s, %s]"
.formatted(indexName, keyName, keyValue));
}
final AttributeValue primaryKeyValue = response.items().get(0).get(KEY_ACCOUNT_UUID);
return itemByKey(table, KEY_ACCOUNT_UUID, primaryKeyValue);
}
@Nonnull
private CompletableFuture<Optional<Map<String, AttributeValue>>> itemByGsiKeyAsync(final String table, final String indexName, final String keyName, final AttributeValue keyValue) {
return asyncClient.query(QueryRequest.builder()
return dynamoDbAsyncClient.query(QueryRequest.builder()
.tableName(table)
.indexName(indexName)
.keyConditionExpression("#gsiKey = :gsiValue")
@@ -1380,7 +1342,7 @@ public class Accounts extends AbstractDynamoDbStore {
.formatted(indexName, keyName, keyValue)));
}
final AttributeValue primaryKeyValue = response.items().get(0).get(KEY_ACCOUNT_UUID);
final AttributeValue primaryKeyValue = response.items().getFirst().get(KEY_ACCOUNT_UUID);
return itemByKeyAsync(table, KEY_ACCOUNT_UUID, primaryKeyValue);
});
}
@@ -1407,9 +1369,9 @@ public class Accounts extends AbstractDynamoDbStore {
return TransactWriteItem.builder()
.put(Put.builder()
.conditionExpression("attribute_not_exists(#number) OR #number = :number")
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164))
.expressionAttributeValues(Map.of(":number", numberAttr))
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
.expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID))
.expressionAttributeValues(Map.of(":pni", pniUuidAttr))
.tableName(accountsTableName)
.item(item)
.build())
@@ -72,8 +72,8 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
@@ -82,6 +82,7 @@ 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.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -125,6 +126,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final ProfilesManager profilesManager;
private final SecureStorageClient secureStorageClient;
private final SecureValueRecovery2Client secureValueRecovery2Client;
private final SecureValueRecovery3Client secureValueRecovery3Client;
private final DisconnectionRequestManager disconnectionRequestManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final ClientPublicKeysManager clientPublicKeysManager;
@@ -140,7 +143,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final Map<String, CompletableFuture<Optional<DeviceInfo>>> waitForDeviceFuturesByTokenIdentifier =
new ConcurrentHashMap<>();
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<RemoteAttachment>>> waitForTransferArchiveFuturesByDeviceIdentifier =
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<Optional<RestoreAccountRequest>>> waitForRestoreAccountRequestFuturesByToken =
@@ -207,6 +210,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final ProfilesManager profilesManager,
final SecureStorageClient secureStorageClient,
final SecureValueRecovery2Client secureValueRecovery2Client,
final SecureValueRecovery3Client secureValueRecovery3Client,
final DisconnectionRequestManager disconnectionRequestManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final ClientPublicKeysManager clientPublicKeysManager,
@@ -225,6 +229,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.profilesManager = profilesManager;
this.secureStorageClient = secureStorageClient;
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.secureValueRecovery3Client = secureValueRecovery3Client;
this.disconnectionRequestManager = disconnectionRequestManager;
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
this.clientPublicKeysManager = clientPublicKeysManager;
@@ -271,16 +276,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
@Nullable final String userAgent) throws InterruptedException {
final Account account = new Account();
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
return createTimer.record(() -> {
accountLockManager.withLock(List.of(number), () -> {
accountLockManager.withLock(List.of(pni), () -> {
final Optional<UUID> maybeRecentlyDeletedAccountIdentifier =
accounts.findRecentlyDeletedAccountIdentifier(number);
accounts.findRecentlyDeletedAccountIdentifier(pni);
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is
// re-registering.
account.setNumber(number, phoneNumberIdentifiers.getPhoneNumberIdentifier(number));
account.setUuid(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
account.setNumber(number, pni);
account.setIdentityKey(aciIdentityKey);
account.setPhoneNumberIdentityKey(pniIdentityKey);
account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock));
@@ -324,10 +330,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
final UUID aci = e.getExistingAccount().getIdentifier(IdentityType.ACI);
final UUID pni = e.getExistingAccount().getIdentifier(IdentityType.PNI);
account.setUuid(aci);
account.setNumber(e.getExistingAccount().getNumber(), pni);
final List<TransactWriteItem> additionalWriteItems = Stream.concat(
keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI),
@@ -363,9 +366,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
// We exclude the primary device's repeated-use keys from deletion because new keys were provided as
// part of the account creation process, and we don't want to delete the keys that just got added.
return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci),
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci));
keysManager.deleteSingleUsePreKeys(pni),
messagesManager.clear(aci),
profilesManager.deleteAll(aci));
})
.join();
}
@@ -375,7 +378,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
Tag.of("hasPushToken", String.valueOf(
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId().isPresent())),
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId()
.isPresent())),
Tag.of("pushTokenType", pushTokenType));
if (StringUtils.isNotBlank(previousPushTokenType)) {
@@ -385,7 +389,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Metrics.counter(CREATE_COUNTER_NAME, tags).increment();
accountAttributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager.storeForCurrentNumber(account.getNumber(), registrationRecoveryPassword));
registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI),
registrationRecoveryPassword));
}, accountLockExecutor);
return account;
@@ -393,7 +398,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.getNumber()),
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -581,7 +586,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLockAsync(List.of(account.getNumber()),
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -634,10 +639,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
@Nullable final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
@Nullable final Map<Byte, Integer> pniRegistrationIds) throws InterruptedException, MismatchedDevicesException {
final String originalNumber = account.getNumber();
final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifier();
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
if (originalNumber.equals(targetNumber)) {
if (originalPhoneNumberIdentifier.equals(targetPhoneNumberIdentifier)) {
if (pniIdentityKey != null) {
throw new IllegalArgumentException("change number must supply a changed phone number; otherwise use updatePniKeys");
}
@@ -648,21 +653,21 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final AtomicReference<Account> updatedAccount = new AtomicReference<>();
accountLockManager.withLock(List.of(account.getNumber(), targetNumber), () -> {
accountLockManager.withLock(List.of(account.getPhoneNumberIdentifier(), targetPhoneNumberIdentifier), () -> {
redisDelete(account);
// There are three possible states for accounts associated with the target phone number:
//
// 1. An account exists with the target number; the caller has proved ownership of the number, so delete the
// account with the target number. This will leave a "deleted account" record for the deleted account mapping
// the UUID of the deleted account to the target phone number. We'll then overwrite that so it points to the
// original number to facilitate switching back and forth between numbers.
// 2. No account with the target number 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 phone number
// 1. 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
// 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 number exists at all, in which case no additional action is needed.
final Optional<UUID> recentlyDeletedAci = accounts.findRecentlyDeletedAccountIdentifier(targetNumber);
// 3. 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;
@@ -674,15 +679,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
final UUID uuid = account.getUuid();
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber);
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(phoneNumberIdentifier),
keysManager.deleteSingleUsePreKeys(targetPhoneNumberIdentifier),
keysManager.deleteSingleUsePreKeys(originalPhoneNumberIdentifier))
.join();
final Collection<TransactWriteItem> keyWriteItems =
buildPniKeyWriteItems(uuid, phoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
buildPniKeyWriteItems(uuid, targetPhoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
final Account numberChangedAccount = updateWithRetries(
account,
@@ -690,7 +694,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
setPniKeys(account, pniIdentityKey, pniRegistrationIds);
return true;
},
a -> accounts.changeNumber(a, targetNumber, phoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
a -> accounts.changeNumber(a, targetNumber, targetPhoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
AccountChangeValidator.NUMBER_CHANGE_VALIDATOR);
@@ -1202,15 +1206,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public UUID getPhoneNumberIdentifier(String e164) {
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164);
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164).join();
}
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final String e164) {
return accounts.findRecentlyDeletedAccountIdentifier(e164);
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final UUID phoneNumberIdentifier) {
return accounts.findRecentlyDeletedAccountIdentifier(phoneNumberIdentifier);
}
public Optional<String> findRecentlyDeletedE164(final UUID uuid) {
return accounts.findRecentlyDeletedE164(uuid);
public Optional<UUID> findRecentlyDeletedPhoneNumberIdentifier(final UUID accountIdentifier) {
return accounts.findRecentlyDeletedPhoneNumberIdentifier(accountIdentifier);
}
public Flux<Account> streamAllFromDynamo(final int segments, final Scheduler scheduler) {
@@ -1220,7 +1224,8 @@ 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.getNumber()), () -> delete(account), accountLockExecutor)
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()), () -> delete(account),
accountLockExecutor)
.whenComplete((ignored, throwable) -> {
sample.stop(deleteTimer);
@@ -1248,24 +1253,32 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
account.getIdentifier(IdentityType.ACI),
device.getId())))
.toList();
CompletableFuture<Void> deleteBackupFuture = secureValueRecovery2Client.deleteBackups(account.getUuid())
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("Failed to delete backup for account: " + account.getUuid(), exception);
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);
}));
final CompletableFuture<Void> svr3DeleteBackupFuture = secureValueRecovery3Client.deleteBackups(account.getUuid())
.exceptionally(exception -> {
// We don't care about errors from SVR3 because we're not currently using it
return null;
});
return CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
deleteBackupFuture,
svr2DeleteBackupFuture,
svr3DeleteBackupFuture,
keysManager.deleteSingleUsePreKeys(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
messagesManager.clear(account.getUuid()),
profilesManager.deleteAll(account.getUuid()),
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber()))
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
.thenCompose(ignored -> redisDeleteAsync(account))
.thenRun(() -> disconnectionRequestManager.requestDisconnection(account.getUuid()));
@@ -1548,7 +1561,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return LINKED_DEVICE_PREFIX + linkDeviceTokenIdentifier;
}
public CompletableFuture<Optional<RemoteAttachment>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
final TimestampedDeviceIdentifier deviceIdentifier =
new TimestampedDeviceIdentifier(account.getIdentifier(IdentityType.ACI),
device.getId(),
@@ -1564,14 +1577,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public CompletableFuture<Void> recordTransferArchiveUpload(final Account account,
final byte destinationDeviceId,
final Instant destinationDeviceCreationTimestamp,
final RemoteAttachment transferArchive) {
final TransferArchiveResult transferArchiveResult) {
final String key = getTransferArchiveKey(account.getIdentifier(IdentityType.ACI),
destinationDeviceId,
destinationDeviceCreationTimestamp);
try {
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchive);
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
return pubSubRedisClient.withConnection(connection ->
connection.async().set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL)))
@@ -1583,9 +1596,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private void handleTransferArchiveAdded(final CompletableFuture<Optional<RemoteAttachment>> future, final String transferArchiveJson) {
private void handleTransferArchiveAdded(final CompletableFuture<Optional<TransferArchiveResult>> future, final String transferArchiveJson) {
try {
future.complete(Optional.of(SystemMapper.jsonMapper().readValue(transferArchiveJson, RemoteAttachment.class)));
future.complete(Optional.of(SystemMapper.jsonMapper().readValue(transferArchiveJson, TransferArchiveResult.class)));
} catch (final JsonProcessingException e) {
logger.error("Could not parse transfer archive json", e);
future.completeExceptionally(e);
@@ -16,7 +16,6 @@ import org.apache.commons.lang3.ObjectUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
@@ -29,7 +28,8 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
public class ChangeNumberManager {
private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
private final MessageSender messageSender;
private final AccountsManager accountsManager;
@@ -41,7 +41,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.getNumber()),
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
() -> clientPublicKeys.setPublicKey(account.getIdentifier(IdentityType.ACI), deviceId, publicKey),
accountLockExecutor);
}
@@ -9,6 +9,7 @@ import static org.whispersystems.textsecuregcm.util.AttributeValues.b;
import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.core.Response.Status;
@@ -17,6 +18,8 @@ import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
@@ -27,6 +30,7 @@ import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
@@ -38,21 +42,25 @@ public class IssuedReceiptsManager {
public static final String KEY_PROCESSOR_ITEM_ID = "A"; // S (HashKey)
public static final String KEY_ISSUED_RECEIPT_TAG = "B"; // B
public static final String KEY_EXPIRATION = "E"; // N
public static final String KEY_ISSUED_RECEIPT_TAG_SET = "T"; // BS
private final String table;
private final Duration expiration;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final byte[] receiptTagGenerator;
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
public IssuedReceiptsManager(
@Nonnull String table,
@Nonnull Duration expiration,
@Nonnull DynamoDbAsyncClient dynamoDbAsyncClient,
@Nonnull byte[] receiptTagGenerator) {
@Nonnull byte[] receiptTagGenerator,
@Nonnull EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
this.table = Objects.requireNonNull(table);
this.expiration = Objects.requireNonNull(expiration);
this.dynamoDbAsyncClient = Objects.requireNonNull(dynamoDbAsyncClient);
this.receiptTagGenerator = Objects.requireNonNull(receiptTagGenerator);
this.maxIssuedReceiptsPerPaymentId = Objects.requireNonNull(maxIssuedReceiptsPerPaymentId);
}
/**
@@ -71,29 +79,27 @@ public class IssuedReceiptsManager {
ReceiptCredentialRequest request,
Instant now) {
final AttributeValue key;
if (processor == PaymentProvider.STRIPE) {
// As the first processor, Stripe’s IDs were not prefixed. Its item IDs have documented prefixes (`il_`, `pi_`)
// that will not collide with `SubscriptionProcessor` names
key = s(processorItemId);
} else {
key = s(processor.name() + "_" + processorItemId);
}
final AttributeValue key = dynamoDbKey(processor, processorItemId);
final byte[] tag = generateIssuedReceiptTag(request);
UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_PROCESSOR_ITEM_ID, key))
.conditionExpression("attribute_not_exists(#key) OR #tag = :tag")
.conditionExpression("attribute_not_exists(#key) OR contains(#tags, :tag) OR size(#tags) < :maxTags")
.returnValues(ReturnValue.NONE)
.updateExpression("SET "
+ "#tag = if_not_exists(#tag, :tag), "
+ "#exp = if_not_exists(#exp, :exp)")
+ "#exp = if_not_exists(#exp, :exp) "
+ "ADD #tags :singletonTag")
.expressionAttributeNames(Map.of(
"#key", KEY_PROCESSOR_ITEM_ID,
"#tag", KEY_ISSUED_RECEIPT_TAG,
"#tags", KEY_ISSUED_RECEIPT_TAG_SET,
"#exp", KEY_EXPIRATION))
.expressionAttributeValues(Map.of(
":tag", b(generateIssuedReceiptTag(request)),
":exp", n(now.plus(expiration).getEpochSecond())))
":tag", b(tag),
":singletonTag", AttributeValue.fromBs(List.of(SdkBytes.fromByteArray(tag))),
":exp", n(now.plus(expiration).getEpochSecond()),
":maxTags", n(maxIssuedReceiptsPerPaymentId.get(processor))))
.build();
return dynamoDbAsyncClient.updateItem(updateItemRequest).handle((updateItemResponse, throwable) -> {
if (throwable != null) {
@@ -108,7 +114,20 @@ public class IssuedReceiptsManager {
});
}
private byte[] generateIssuedReceiptTag(ReceiptCredentialRequest request) {
@VisibleForTesting
static AttributeValue dynamoDbKey(final PaymentProvider processor, String processorItemId) {
if (processor == PaymentProvider.STRIPE) {
// As the first processor, Stripe’s IDs were not prefixed. Its item IDs have documented prefixes (`il_`, `pi_`)
// that will not collide with `SubscriptionProcessor` names
return s(processorItemId);
} else {
return s(processor.name() + "_" + processorItemId);
}
}
@VisibleForTesting
byte[] generateIssuedReceiptTag(ReceiptCredentialRequest request) {
return generateHmac("issuedReceiptTag", mac -> mac.update(request.serialize()));
}
@@ -36,10 +36,7 @@ import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.ServiceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.Experiment;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -116,8 +113,6 @@ public class MessagesCache {
// messageDeletionExecutorService wrapped into a reactor Scheduler
private final Scheduler messageDeletionScheduler;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final MessagesCacheInsertScript insertScript;
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
@@ -137,10 +132,8 @@ public class MessagesCache {
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
name(MessagesCache.class, "staleEphemeralMessages"));
private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved"));
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = "mrmRetrievalError";
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = name(MessagesCache.class, "mrmRetrievalError");
private final String EPHEMERAL_TAG_NAME = "ephemeral";
private final Counter mrmPhaseTwoMissingContentCounter = Metrics.counter(
name(MessagesCache.class, "mrmPhaseTwoMissingContent"));
private final Counter skippedStaleEphemeralMrmCounter = Metrics.counter(
name(MessagesCache.class, "skippedStaleEphemeralMrm"));
private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter(
@@ -149,8 +142,6 @@ public class MessagesCache {
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
private static final String MRM_VIEWS_EXPERIMENT_NAME = "mrmViews";
@VisibleForTesting
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
@@ -164,8 +155,7 @@ public class MessagesCache {
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager)
final Clock clock)
throws IOException {
this(
@@ -173,7 +163,6 @@ public class MessagesCache {
messageDeliveryScheduler,
messageDeletionExecutorService,
clock,
dynamicConfigurationManager,
new MessagesCacheInsertScript(redisCluster),
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster),
new MessagesCacheGetItemsScript(redisCluster),
@@ -189,7 +178,6 @@ public class MessagesCache {
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService, final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final MessagesCacheInsertScript insertScript,
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
@@ -205,8 +193,6 @@ public class MessagesCache {
this.messageDeletionExecutorService = messageDeletionExecutorService;
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.insertScript = insertScript;
this.insertMrmScript = insertMrmScript;
this.removeByGuidScript = removeByGuidScript;
@@ -371,8 +357,6 @@ public class MessagesCache {
messageMono = Mono.just(message.toBuilder().clearSharedMrmKey().build());
skippedStaleEphemeralMrmCounter.increment();
} else {
// mrm views phase 3: fetch shared MRM data -- internally depends on dynamic config that
// enables using it (the stored messages still always have `content` set upstream)
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
}
@@ -393,27 +377,18 @@ public class MessagesCache {
/**
* Returns the given message with its shared MRM data.
*
* @see DynamicMessagesConfiguration#useSharedMrmData()
*/
private Mono<MessageProtos.Envelope> getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage,
final byte destinationDevice) {
assert mrmMessage.hasSharedMrmKey();
// mrm views phase 2: messages have content
if (!mrmMessage.hasContent()) {
mrmPhaseTwoMissingContentCounter.increment();
}
final Experiment experiment = new Experiment(MRM_VIEWS_EXPERIMENT_NAME);
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
// the message might be addressed to the account's PNI, so use the service ID from the envelope
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
final Mono<MessageProtos.Envelope> messageFromRedisMono = Mono.from(redisCluster.withBinaryClusterReactive(
return Mono.from(redisCluster.withBinaryClusterReactive(
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
.collectList()
.publishOn(messageDeliveryScheduler)))
@@ -444,18 +419,6 @@ public class MessagesCache {
return Mono.empty();
})
.share();
if (mrmMessage.hasContent()) {
experiment.compareMonoResult(mrmMessage.toBuilder().clearSharedMrmKey().build(), messageFromRedisMono);
}
if (dynamicConfigurationManager.getConfiguration().getMessagesConfiguration().useSharedMrmData()
|| !mrmMessage.hasContent()) {
return messageFromRedisMono;
}
// if fetching or using shared data is disabled, fallback to just() with the existing message
return Mono.just(mrmMessage.toBuilder().clearSharedMrmKey().build());
}
/**
@@ -529,8 +492,6 @@ public class MessagesCache {
.concatMap(message -> {
final Mono<MessageProtos.Envelope> messageMono;
if (message.hasSharedMrmKey()) {
// mrm views phase 2: fetch shared MRM data -- internally depends on dynamic config that
// enables fetching and using it (the stored messages still always have `content` set upstream)
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
} else {
messageMono = Mono.just(message);
@@ -10,18 +10,38 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
import software.amazon.awssdk.services.dynamodb.model.Update;
/**
* Manages a global, persistent mapping of phone numbers to phone number identifiers regardless of whether those
@@ -29,7 +49,7 @@ import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
*/
public class PhoneNumberIdentifiers {
private final DynamoDbClient dynamoDbClient;
private final DynamoDbAsyncClient dynamoDbClient;
private final String tableName;
@VisibleForTesting
@@ -39,81 +59,201 @@ public class PhoneNumberIdentifiers {
@VisibleForTesting
static final String ATTR_PHONE_NUMBER_IDENTIFIER = "PNI";
private static final String CONDITIONAL_CHECK_FAILED = "ConditionalCheckFailed";
private static final Timer GET_PNI_TIMER = Metrics.timer(name(PhoneNumberIdentifiers.class, "get"));
private static final Timer SET_PNI_TIMER = Metrics.timer(name(PhoneNumberIdentifiers.class, "set"));
private static final int MAX_RETRIES = 10;
public PhoneNumberIdentifiers(final DynamoDbClient dynamoDbClient, final String tableName) {
private static final Logger logger = LoggerFactory.getLogger(PhoneNumberIdentifiers.class);
public PhoneNumberIdentifiers(final DynamoDbAsyncClient dynamoDbClient, final String tableName) {
this.dynamoDbClient = dynamoDbClient;
this.tableName = tableName;
}
/**
* Returns the phone number identifier (PNI) associated with the given phone number.
* Returns the phone number identifier (PNI) associated with the given phone number. If one doesn't exist, it is
* created.
*
* @param phoneNumber the phone number for which to retrieve a phone number identifier
* @return the phone number identifier associated with the given phone number
*/
public UUID getPhoneNumberIdentifier(final String phoneNumber) {
final GetItemResponse response = GET_PNI_TIMER.record(() -> dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
.projectionExpression(ATTR_PHONE_NUMBER_IDENTIFIER)
.build()));
public CompletableFuture<UUID> getPhoneNumberIdentifier(final String phoneNumber) {
// Each e164 phone number string represents a potential equivalence class e164s that represent the same number. If
// this is a new phone number, we'll want to set all the numbers in the equivalence class to the same PNI
final List<String> allPhoneNumberForms = Util.getAlternateForms(phoneNumber);
final UUID phoneNumberIdentifier;
if (response.hasItem()) {
phoneNumberIdentifier = AttributeValues.getUUID(response.item(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
} else {
phoneNumberIdentifier = generatePhoneNumberIdentifierIfNotExists(phoneNumber);
}
if (phoneNumberIdentifier == null) {
throw new RuntimeException("Could not retrieve phone number identifier from stored item");
}
return phoneNumberIdentifier;
return retry(MAX_RETRIES, TransactionConflictException.class, () -> fetchPhoneNumbers(allPhoneNumberForms)
.thenCompose(mappings -> setPniIfRequired(phoneNumber, allPhoneNumberForms, mappings)));
}
public Optional<String> getPhoneNumber(final UUID phoneNumberIdentifier) {
final QueryResponse response = dynamoDbClient.query(QueryRequest.builder()
.tableName(tableName)
.indexName(INDEX_NAME)
.keyConditionExpression("#pni = :pni")
.projectionExpression("#phone_number")
.expressionAttributeNames(Map.of(
"#phone_number", KEY_E164,
"#pni", ATTR_PHONE_NUMBER_IDENTIFIER
))
.expressionAttributeValues(Map.of(
":pni", AttributeValues.fromUUID(phoneNumberIdentifier)
))
.build());
if (response.count() == 0) {
return Optional.empty();
}
if (response.count() > 1) {
throw new RuntimeException(
"Impossible result: more than one phone number returned for PNI: " + phoneNumberIdentifier);
}
return Optional.ofNullable(response.items().get(0).get(KEY_E164).s());
/**
* Returns the list of phone numbers associated with a given phone number identifier. If this
* UUID was not previously assigned as a PNI by {@link #getPhoneNumberIdentifier(String)}, the
* returned list will be empty.
*
* @param UUID a phone number identifier
* @return the list of all e164s associated with the given phone number identifier
*/
public CompletableFuture<List<String>> getPhoneNumber(final UUID phoneNumberIdentifier) {
return dynamoDbClient.query(QueryRequest.builder()
.tableName(tableName)
.indexName(INDEX_NAME)
.keyConditionExpression("#pni = :pni")
.projectionExpression("#phone_number")
.expressionAttributeNames(Map.of(
"#phone_number", KEY_E164,
"#pni", ATTR_PHONE_NUMBER_IDENTIFIER
))
.expressionAttributeValues(Map.of(
":pni", AttributeValues.fromUUID(phoneNumberIdentifier)
))
.build())
.thenApply(response -> {
return response.items().stream().map(item -> item.get(KEY_E164).s()).toList();
});
}
@VisibleForTesting
UUID generatePhoneNumberIdentifierIfNotExists(final String phoneNumber) {
final UpdateItemResponse response = SET_PNI_TIMER.record(() -> dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
.updateExpression("SET #pni = if_not_exists(#pni, :pni)")
.expressionAttributeNames(Map.of("#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
.expressionAttributeValues(Map.of(":pni", AttributeValues.fromUUID(UUID.randomUUID())))
.returnValues(ReturnValue.ALL_NEW)
.build()));
static <T, E extends Exception> CompletableFuture<T> retry(
final int numRetries, final Class<E> exceptionToRetry, final Supplier<CompletableFuture<T>> supplier) {
return supplier.get().exceptionallyCompose(ExceptionUtils.exceptionallyHandler(exceptionToRetry, e -> {
if (numRetries - 1 <= 0) {
throw ExceptionUtils.wrap(e);
}
return retry(numRetries - 1, exceptionToRetry, supplier);
}));
}
return AttributeValues.getUUID(response.attributes(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
/**
* Determine what PNI to set for the provided numbers, and set them if required
*
* @param phoneNumber The original e164 the operation is for
* @param allPhoneNumberForms The e164s to set. The first e164 in this list should be phoneNumber
* @param existingAssociations The current associations of allPhoneNumberForms in the table
* @return The PNI now associated with phoneNumber
*/
@VisibleForTesting
CompletableFuture<UUID> setPniIfRequired(
final String phoneNumber,
final List<String> allPhoneNumberForms,
Map<String, UUID> existingAssociations) {
if (!phoneNumber.equals(allPhoneNumberForms.getFirst())) {
throw new IllegalArgumentException("allPhoneNumberForms must start with the target phoneNumber");
}
if (existingAssociations.containsKey(phoneNumber)) {
// If the provided phone number already has an association, just return that
return CompletableFuture.completedFuture(existingAssociations.get(phoneNumber));
}
if (allPhoneNumberForms.size() == 1 || existingAssociations.isEmpty()) {
// Easy case, if we're the only phone number in our equivalence class or there are no existing associations,
// we can just make an association for a new PNI
return setPni(phoneNumber, allPhoneNumberForms, UUID.randomUUID());
}
// Otherwise, what members of the equivalence class have a PNI association?
final Map<UUID, List<String>> byPni = existingAssociations.entrySet().stream().collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
// Usually there should be only a single PNI associated with the equivalence class, but it's possible there's
// more. This could only happen if an equivalence class had more than two numbers, and had accumulated 2 unique
// PNI associations before they were merged into a single class. In this case we've picked one of those pnis
// arbitrarily (according to their ordering as returned by getAlternateForms)
final UUID existingPni = allPhoneNumberForms.stream()
.filter(existingAssociations::containsKey)
.findFirst()
.map(existingAssociations::get)
.orElseThrow(() -> new IllegalStateException("Previously checked that a mapping existed"));
if (byPni.size() > 1) {
logger.warn("More than one PNI existed in the PNI table for the numbers that map to {}. " +
"Arbitrarily picking {} to be the representative PNI for the numbers without PNI associations",
phoneNumber, existingPni);
}
// Find all the unmapped phoneNumbers and set them to the PNI we chose from another member of the equivalence class
final List<String> unmappedNumbers = allPhoneNumberForms.stream()
.filter(number -> !existingAssociations.containsKey(number))
.toList();
return setPni(phoneNumber, unmappedNumbers, existingPni);
}
/**
* Attempt to associate phoneNumbers with the provided pni. If any of the phoneNumbers have an existing association
* that is not the target pni, no update will occur. If the first phoneNumber in phoneNumbers has an existing
* association, it will be returned, otherwise an exception will be thrown.
*
* @param originalPhoneNumber The original e164 the operation is for
* @param allPhoneNumberForms The e164s to set. The first e164 in this list should be originalPhoneNumber
* @param pni The PNI to set
* @return The provided PNI if the update occurred, or the existing PNI associated with originalPhoneNumber
*/
@VisibleForTesting
CompletableFuture<UUID> setPni(final String originalPhoneNumber, final List<String> allPhoneNumberForms,
final UUID pni) {
if (!originalPhoneNumber.equals(allPhoneNumberForms.getFirst())) {
throw new IllegalArgumentException("allPhoneNumberForms must start with the target phoneNumber");
}
final Timer.Sample sample = Timer.start();
final List<TransactWriteItem> transactWriteItems = allPhoneNumberForms
.stream()
.map(phoneNumber -> TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
.updateExpression("SET #pni = :pni")
// It's possible we're racing with someone else to update, but both of us selected the same PNI because
// an equivalent number already had it. That's fine, as long as the association happens.
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
.expressionAttributeNames(Map.of("#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
.expressionAttributeValues(Map.of(":pni", AttributeValues.fromUUID(pni)))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build()).build())
.toList();
return dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build())
.thenApply(ignored -> pni)
.exceptionally(ExceptionUtils.exceptionallyHandler(TransactionCanceledException.class, e -> {
if (e.hasCancellationReasons()) {
// Get the cancellation reason for the number that we were primarily trying to associate with a PNI
final CancellationReason cancelReason = e.cancellationReasons().getFirst();
if (CONDITIONAL_CHECK_FAILED.equals(cancelReason.code())) {
// Someone else beat us to the update, use the PNI they set.
return AttributeValues.getUUID(cancelReason.item(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
}
}
throw e;
}))
.whenComplete((ignored, throwable) -> sample.stop(SET_PNI_TIMER));
}
@VisibleForTesting
CompletableFuture<Map<String, UUID>> fetchPhoneNumbers(List<String> phoneNumbers) {
final Timer.Sample sample = Timer.start();
return dynamoDbClient.batchGetItem(
BatchGetItemRequest.builder().requestItems(Map.of(tableName, KeysAndAttributes.builder()
// If we have a stale value, the subsequent conditional update will fail
.consistentRead(false)
.projectionExpression("#number,#pni")
.expressionAttributeNames(Map.of("#number", KEY_E164, "#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
.keys(phoneNumbers.stream()
.map(number -> Map.of(KEY_E164, AttributeValues.fromString(number)))
.toArray(Map[]::new))
.build()))
.build())
.thenApply(batchResponse -> batchResponse.responses().get(tableName).stream().collect(Collectors.toMap(
item -> AttributeValues.getString(item, KEY_E164, null),
item -> AttributeValues.getUUID(item, ATTR_PHONE_NUMBER_IDENTIFIER, null))))
.whenComplete((ignored, throwable) -> sample.stop(GET_PNI_TIMER));
}
}
@@ -7,24 +7,26 @@ package org.whispersystems.textsecuregcm.storage;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
public class RegistrationRecoveryPasswords extends AbstractDynamoDbStore {
public class RegistrationRecoveryPasswords {
static final String KEY_E164 = "P";
// For historical reasons, we record the PNI as a UUID string rather than a compact byte array
static final String KEY_PNI = "P";
static final String ATTR_EXP = "E";
static final String ATTR_SALT = "S";
static final String ATTR_HASH = "H";
@@ -40,62 +42,54 @@ public class RegistrationRecoveryPasswords extends AbstractDynamoDbStore {
public RegistrationRecoveryPasswords(
final String tableName,
final Duration expiration,
final DynamoDbClient dynamoDbClient,
final DynamoDbAsyncClient asyncClient) {
this(tableName, expiration, dynamoDbClient, asyncClient, Clock.systemUTC());
}
RegistrationRecoveryPasswords(
final String tableName,
final Duration expiration,
final DynamoDbClient dynamoDbClient,
final DynamoDbAsyncClient asyncClient,
final Clock clock) {
super(dynamoDbClient);
this.tableName = requireNonNull(tableName);
this.expiration = requireNonNull(expiration);
this.asyncClient = requireNonNull(asyncClient);
this.clock = requireNonNull(clock);
}
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final String number) {
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final UUID phoneNumberIdentifier) {
return asyncClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.consistentRead(true)
.build())
.thenApply(getItemResponse -> {
final Map<String, AttributeValue> item = getItemResponse.item();
if (item == null || !item.containsKey(ATTR_SALT) || !item.containsKey(ATTR_HASH)) {
return Optional.empty();
}
final String salt = item.get(ATTR_SALT).s();
final String hash = item.get(ATTR_HASH).s();
return Optional.of(new SaltedTokenHash(hash, salt));
});
.build())
.thenApply(getItemResponse -> Optional.ofNullable(getItemResponse.item())
.filter(item -> item.containsKey(ATTR_SALT))
.filter(item -> item.containsKey(ATTR_HASH))
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem));
}
public CompletableFuture<Void> addOrReplace(final String number, final SaltedTokenHash data) {
public CompletableFuture<Void> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
final long expirationSeconds = expirationSeconds();
return asyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(
KEY_E164, AttributeValues.fromString(number),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds()),
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
ATTR_SALT, AttributeValues.fromString(data.salt()),
ATTR_HASH, AttributeValues.fromString(data.hash())))
.build())
.thenRun(Util.NOOP);
}
public CompletableFuture<Void> removeEntry(final String number) {
public CompletableFuture<Void> removeEntry(final UUID phoneNumberIdentifier) {
return asyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.build())
.thenRun(Util.NOOP);
}
private long expirationSeconds() {
@VisibleForTesting
long expirationSeconds() {
return clock.instant().plus(expiration).getEpochSecond();
}
private static SaltedTokenHash saltedTokenHashFromItem(final Map<String, AttributeValue> item) {
return new SaltedTokenHash(item.get(ATTR_HASH).s(), item.get(ATTR_SALT).s());
}
}
@@ -10,6 +10,7 @@ import static java.util.Objects.requireNonNull;
import java.lang.invoke.MethodHandles;
import java.util.HexFormat;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -22,13 +23,12 @@ public class RegistrationRecoveryPasswordsManager {
private final RegistrationRecoveryPasswords registrationRecoveryPasswords;
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords) {
this.registrationRecoveryPasswords = requireNonNull(registrationRecoveryPasswords);
}
public CompletableFuture<Boolean> verify(final String number, final byte[] password) {
return registrationRecoveryPasswords.lookup(number)
public CompletableFuture<Boolean> verify(final UUID phoneNumberIdentifier, final byte[] password) {
return registrationRecoveryPasswords.lookup(phoneNumberIdentifier)
.thenApply(maybeHash -> maybeHash.filter(hash -> hash.verify(bytesToString(password))))
.whenComplete((result, error) -> {
if (error != null) {
@@ -38,10 +38,11 @@ public class RegistrationRecoveryPasswordsManager {
.thenApply(Optional::isPresent);
}
public CompletableFuture<Void> storeForCurrentNumber(final String number, final byte[] password) {
public CompletableFuture<Void> store(final UUID phoneNumberIdentifier, final byte[] password) {
final String token = bytesToString(password);
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
return registrationRecoveryPasswords.addOrReplace(number, tokenHash)
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash)
.whenComplete((result, error) -> {
if (error != null) {
logger.warn("Failed to store Registration Recovery Password", error);
@@ -49,10 +50,8 @@ public class RegistrationRecoveryPasswordsManager {
});
}
public CompletableFuture<Void> removeForNumber(final String number) {
// remove is a "fire-and-forget" operation,
// there is no action to be taken on its completion
return registrationRecoveryPasswords.removeEntry(number)
public CompletableFuture<Void> remove(final UUID phoneNumberIdentifier) {
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier)
.whenComplete((ignored, error) -> {
if (error instanceof ResourceNotFoundException) {
// These will naturally happen if a recovery password is already deleted. Since we can remove
@@ -81,7 +81,7 @@ public class SubscriptionManager {
.orElseGet(() -> CompletableFuture.completedFuture(null));
})
.thenCompose(unused ->
subscriptions.canceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()));
subscriptions.setCanceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()));
}
/**
@@ -195,7 +195,7 @@ public class Subscriptions {
throw new IllegalStateException(
"expected invariant of 1-1 subscriber-customer violated for customer " + processorCustomer);
} else {
Map<String, AttributeValue> result = queryResponse.items().get(0);
Map<String, AttributeValue> result = queryResponse.items().getFirst();
return result.get(KEY_USER).b().asByteArray();
}
});
@@ -370,15 +370,16 @@ public class Subscriptions {
+ "#subscription_id = :subscription_id, "
+ "#subscription_level = :subscription_level, "
+ "#subscription_created_at = if_not_exists(#subscription_created_at, :subscription_created_at), "
+ "#subscription_level_changed_at = :subscription_level_changed_at"
)
+ "#subscription_level_changed_at = :subscription_level_changed_at "
+ "REMOVE #canceled_at")
.expressionAttributeNames(Map.of(
"#processor_customer_id", KEY_PROCESSOR_ID_CUSTOMER_ID,
"#accessed_at", KEY_ACCESSED_AT,
"#subscription_id", KEY_SUBSCRIPTION_ID,
"#subscription_level", KEY_SUBSCRIPTION_LEVEL,
"#subscription_created_at", KEY_SUBSCRIPTION_CREATED_AT,
"#subscription_level_changed_at", KEY_SUBSCRIPTION_LEVEL_CHANGED_AT))
"#subscription_level_changed_at", KEY_SUBSCRIPTION_LEVEL_CHANGED_AT,
"#canceled_at", KEY_CANCELED_AT))
.expressionAttributeValues(Map.of(
":accessed_at", n(updatedAt.getEpochSecond()),
":processor_customer_id", b(processorCustomer.toDynamoBytes()),
@@ -414,7 +415,7 @@ public class Subscriptions {
return client.updateItem(request).thenApply(updateItemResponse -> null);
}
public CompletableFuture<Void> canceledAt(byte[] user, Instant canceledAt) {
public CompletableFuture<Void> setCanceledAt(byte[] user, Instant canceledAt) {
checkUserLength(user);
UpdateItemRequest request = UpdateItemRequest.builder()
@@ -449,13 +450,15 @@ public class Subscriptions {
+ "#subscription_id = :subscription_id, "
+ "#subscription_created_at = :subscription_created_at, "
+ "#subscription_level = :subscription_level, "
+ "#subscription_level_changed_at = :subscription_level_changed_at")
+ "#subscription_level_changed_at = :subscription_level_changed_at "
+ "REMOVE #canceled_at")
.expressionAttributeNames(Map.of(
"#accessed_at", KEY_ACCESSED_AT,
"#subscription_id", KEY_SUBSCRIPTION_ID,
"#subscription_created_at", KEY_SUBSCRIPTION_CREATED_AT,
"#subscription_level", KEY_SUBSCRIPTION_LEVEL,
"#subscription_level_changed_at", KEY_SUBSCRIPTION_LEVEL_CHANGED_AT))
"#subscription_level_changed_at", KEY_SUBSCRIPTION_LEVEL_CHANGED_AT,
"#canceled_at", KEY_CANCELED_AT))
.expressionAttributeValues(Map.of(
":accessed_at", n(subscriptionCreatedAt.getEpochSecond()),
":subscription_id", s(subscriptionId),
@@ -478,12 +481,14 @@ public class Subscriptions {
+ "#accessed_at = :accessed_at, "
+ "#subscription_id = :subscription_id, "
+ "#subscription_level = :subscription_level, "
+ "#subscription_level_changed_at = :subscription_level_changed_at")
+ "#subscription_level_changed_at = :subscription_level_changed_at "
+ "REMOVE #canceled_at")
.expressionAttributeNames(Map.of(
"#accessed_at", KEY_ACCESSED_AT,
"#subscription_id", KEY_SUBSCRIPTION_ID,
"#subscription_level", KEY_SUBSCRIPTION_LEVEL,
"#subscription_level_changed_at", KEY_SUBSCRIPTION_LEVEL_CHANGED_AT))
"#subscription_level_changed_at", KEY_SUBSCRIPTION_LEVEL_CHANGED_AT,
"#canceled_at", KEY_CANCELED_AT))
.expressionAttributeValues(Map.of(
":accessed_at", n(subscriptionLevelChangedAt.getEpochSecond()),
":subscription_id", s(subscriptionId),
@@ -0,0 +1,265 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
import com.google.common.annotations.VisibleForTesting;
import com.webauthn4j.appattest.DeviceCheckManager;
import com.webauthn4j.appattest.authenticator.DCAppleDevice;
import com.webauthn4j.appattest.authenticator.DCAppleDeviceImpl;
import com.webauthn4j.appattest.data.DCAssertionParameters;
import com.webauthn4j.appattest.data.DCAssertionRequest;
import com.webauthn4j.appattest.data.DCAttestationData;
import com.webauthn4j.appattest.data.DCAttestationParameters;
import com.webauthn4j.appattest.data.DCAttestationRequest;
import com.webauthn4j.appattest.server.DCServerProperty;
import com.webauthn4j.data.attestation.AttestationObject;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.verifier.exception.MaliciousCounterValueException;
import com.webauthn4j.verifier.exception.VerificationException;
import io.lettuce.core.RedisException;
import io.lettuce.core.SetArgs;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.storage.Account;
/**
* Register Apple DeviceCheck App Attestations and verify the corresponding assertions.
*
* @see <a href="https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity">...</a>
* @see <a
* href="https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server">...</a>
*/
public class AppleDeviceCheckManager {
private static final Logger logger = LoggerFactory.getLogger(AppleDeviceCheckManager.class);
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final int CHALLENGE_LENGTH = 16;
// How long issued challenges last in redis
@VisibleForTesting
static final Duration CHALLENGE_TTL = Duration.ofHours(1);
// How many distinct device keys we're willing to accept for a single Account
@VisibleForTesting
static final int MAX_DEVICE_KEYS = 100;
private final AppleDeviceChecks appleDeviceChecks;
private final FaultTolerantRedisClusterClient redisClient;
private final DeviceCheckManager deviceCheckManager;
private final String teamId;
private final String bundleId;
public AppleDeviceCheckManager(
AppleDeviceChecks appleDeviceChecks,
FaultTolerantRedisClusterClient redisClient,
DeviceCheckManager deviceCheckManager,
String teamId,
String bundleId) {
this.appleDeviceChecks = appleDeviceChecks;
this.redisClient = redisClient;
this.deviceCheckManager = deviceCheckManager;
this.teamId = teamId;
this.bundleId = bundleId;
}
/**
* Attestations and assertions have independent challenges.
* <p>
* Challenges are tied to their purpose to mitigate replay attacks
*/
public enum ChallengeType {
ATTEST,
ASSERT_BACKUP_REDEMPTION
}
/**
* Register a key and attestation data for an account
*
* @param account The account this keyId should be associated with
* @param keyId The device's keyId
* @param attestBlob The device's attestation
* @throws ChallengeNotFoundException No issued challenge found for the account
* @throws DeviceCheckVerificationFailedException The provided attestation could not be verified
* @throws TooManyKeysException The account has registered too many unique keyIds
* @throws DuplicatePublicKeyException The keyId has already been used with another account
*/
public void registerAttestation(final Account account, final byte[] keyId, final byte[] attestBlob)
throws TooManyKeysException, ChallengeNotFoundException, DeviceCheckVerificationFailedException, DuplicatePublicKeyException {
final List<byte[]> existingKeys = appleDeviceChecks.keyIds(account);
if (existingKeys.stream().anyMatch(x -> MessageDigest.isEqual(x, keyId))) {
// We already have the key, so no need to continue
return;
}
if (existingKeys.size() >= MAX_DEVICE_KEYS) {
// This is best-effort, since we don't check the number of keys transactionally. We just don't want to allow
// the keys for an account to grow arbitrarily large
throw new TooManyKeysException();
}
final String redisChallengeKey = challengeKey(ChallengeType.ATTEST, account.getUuid());
final String challenge = redisClient.withCluster(cluster -> cluster.sync().get(redisChallengeKey));
if (challenge == null) {
throw new ChallengeNotFoundException();
}
final byte[] clientDataHash = sha256(challenge.getBytes(StandardCharsets.UTF_8));
final DCAttestationRequest dcAttestationRequest = new DCAttestationRequest(keyId, attestBlob, clientDataHash);
final DCAttestationData dcAttestationData;
try {
dcAttestationData = deviceCheckManager.validate(dcAttestationRequest,
new DCAttestationParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(challenge))));
} catch (VerificationException e) {
logger.info("Failed to verify attestation", e);
throw new DeviceCheckVerificationFailedException(e);
}
appleDeviceChecks.storeAttestation(account, keyId, createDcAppleDevice(dcAttestationData));
removeChallenge(redisChallengeKey);
}
private static DCAppleDeviceImpl createDcAppleDevice(final DCAttestationData dcAttestationData) {
final AttestationObject attestationObject = dcAttestationData.getAttestationObject();
if (attestationObject == null || attestationObject.getAuthenticatorData().getAttestedCredentialData() == null) {
throw new IllegalArgumentException("Signed and validated attestation missing expected data");
}
return new DCAppleDeviceImpl(
attestationObject.getAuthenticatorData().getAttestedCredentialData(),
attestationObject.getAttestationStatement(),
attestationObject.getAuthenticatorData().getSignCount(),
attestationObject.getAuthenticatorData().getExtensions());
}
/**
* Validate that a request came from an Apple device signed with a key already registered to the account
*
* @param account The requesting account
* @param keyId The key used to generate the assertion
* @param challengeType The {@link ChallengeType} of the assertion, which must match the challenge returned by
* {@link AppleDeviceCheckManager#createChallenge}
* @param challenge A challenge that was embedded in the supplied request
* @param request The request that the client asserted
* @param assertion The assertion from the client
* @throws DeviceCheckKeyIdNotFoundException The provided keyId was never registered with the account
* @throws ChallengeNotFoundException No issued challenge found for the account
* @throws DeviceCheckVerificationFailedException The provided assertion could not be verified
* @throws RequestReuseException The signed counter on the assertion was lower than a previously
* received assertion
*/
public void validateAssert(
final Account account,
final byte[] keyId,
final ChallengeType challengeType,
final String challenge,
final byte[] request,
final byte[] assertion)
throws ChallengeNotFoundException, DeviceCheckVerificationFailedException, DeviceCheckKeyIdNotFoundException, RequestReuseException {
final String redisChallengeKey = challengeKey(challengeType, account.getUuid());
final String storedChallenge = redisClient.withCluster(cluster -> cluster.sync().get(redisChallengeKey));
if (storedChallenge == null) {
throw new ChallengeNotFoundException();
}
if (!MessageDigest.isEqual(
storedChallenge.getBytes(StandardCharsets.UTF_8),
challenge.getBytes(StandardCharsets.UTF_8))) {
throw new DeviceCheckVerificationFailedException("Provided challenge did not match stored challenge");
}
final DCAppleDevice appleDevice = appleDeviceChecks.lookup(account, keyId)
.orElseThrow(DeviceCheckKeyIdNotFoundException::new);
final DCAssertionRequest dcAssertionRequest = new DCAssertionRequest(keyId, assertion, sha256(request));
final DCAssertionParameters dcAssertionParameters =
new DCAssertionParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(request)), appleDevice);
try {
deviceCheckManager.validate(dcAssertionRequest, dcAssertionParameters);
} catch (MaliciousCounterValueException e) {
// We will only accept assertions that have a sign count greater than the last assertion we saw. Step 5 here:
// https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Verify-the-assertion
throw new RequestReuseException("Sign count from request less than stored sign count");
} catch (VerificationException e) {
logger.info("Failed to validate DeviceCheck assert", e);
throw new DeviceCheckVerificationFailedException(e);
}
// Store the updated sign count, so we can check the next assertion (step 6)
appleDeviceChecks.updateCounter(account, keyId, appleDevice.getCounter());
removeChallenge(redisChallengeKey);
}
/**
* Create a challenge that can be used in an attestation or assertion
*
* @param challengeType The type of the challenge
* @param account The account that will use the challenge
* @return The challenge to be included as part of an attestation or assertion
*/
public String createChallenge(final ChallengeType challengeType, final Account account)
throws RateLimitExceededException {
final UUID accountIdentifier = account.getUuid();
final String challengeKey = challengeKey(challengeType, accountIdentifier);
return redisClient.withCluster(cluster -> {
final RedisAdvancedClusterCommands<String, String> commands = cluster.sync();
// Sets the new challenge if and only if there isn't already one stored for the challenge key; returns the existing
// challenge if present or null if no challenge was previously set.
final String proposedChallenge = generateChallenge();
@Nullable final String existingChallenge =
commands.setGet(challengeKey, proposedChallenge, SetArgs.Builder.nx().ex(CHALLENGE_TTL));
if (existingChallenge != null) {
// If the key was already set, make sure we extend the TTL. This is racy because the key could disappear or have
// been updated since the get returned, but it's fine. In the former case, this is a noop. In the latter
// case we may slightly extend the TTL from after it was set, but that's also no big deal.
commands.expire(challengeKey, CHALLENGE_TTL);
}
return existingChallenge != null ? existingChallenge : proposedChallenge;
});
}
private void removeChallenge(final String challengeKey) {
try {
redisClient.useCluster(cluster -> cluster.sync().del(challengeKey));
} catch (RedisException e) {
logger.debug("failed to remove attest challenge from redis, will let it expire via TTL");
}
}
@VisibleForTesting
static String challengeKey(final ChallengeType challengeType, final UUID accountIdentifier) {
return "device_check::" + challengeType.name() + "::" + accountIdentifier.toString();
}
private static String generateChallenge() {
final byte[] challenge = new byte[CHALLENGE_LENGTH];
SECURE_RANDOM.nextBytes(challenge);
return Base64.getUrlEncoder().withoutPadding().encodeToString(challenge);
}
private static byte[] sha256(byte[] bytes) {
try {
return MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError("All Java implementations are required to support SHA-256", e);
}
}
}
@@ -0,0 +1,57 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
import com.webauthn4j.anchor.TrustAnchorRepository;
import com.webauthn4j.data.attestation.authenticator.AAGUID;
import com.webauthn4j.util.CertificateUtil;
import com.webauthn4j.verifier.attestation.trustworthiness.certpath.DefaultCertPathTrustworthinessVerifier;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Set;
/**
* A {@link com.webauthn4j.verifier.attestation.trustworthiness.certpath.CertPathTrustworthinessVerifier} for validating
* x5 certificate chains, pinned with apple's well known static device check root certificate.
*/
public class AppleDeviceCheckTrustAnchor extends DefaultCertPathTrustworthinessVerifier {
// The location of a PEM encoded certificate for Apple's DeviceCheck root certificate
// https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem
private static String APPLE_DEVICE_CHECK_ROOT_CERT_RESOURCE_NAME = "apple_device_check.pem";
public AppleDeviceCheckTrustAnchor() {
super(new StaticTrustAnchorRepository(loadDeviceCheckRootCert()));
}
private record StaticTrustAnchorRepository(X509Certificate rootCert) implements TrustAnchorRepository {
@Override
public Set<TrustAnchor> find(final AAGUID aaguid) {
return Collections.singleton(new TrustAnchor(rootCert, null));
}
@Override
public Set<TrustAnchor> find(final byte[] attestationCertificateKeyIdentifier) {
return Collections.singleton(new TrustAnchor(rootCert, null));
}
}
private static X509Certificate loadDeviceCheckRootCert() {
try (InputStream stream = AppleDeviceCheckTrustAnchor.class.getResourceAsStream(
APPLE_DEVICE_CHECK_ROOT_CERT_RESOURCE_NAME)) {
if (stream == null) {
throw new IllegalArgumentException("Resource not found: " + APPLE_DEVICE_CHECK_ROOT_CERT_RESOURCE_NAME);
}
return CertificateUtil.generateX509Certificate(stream);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,304 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.webauthn4j.appattest.authenticator.DCAppleDevice;
import com.webauthn4j.appattest.authenticator.DCAppleDeviceImpl;
import com.webauthn4j.appattest.data.attestation.statement.AppleAppAttestAttestationStatement;
import com.webauthn4j.converter.AttestedCredentialDataConverter;
import com.webauthn4j.converter.util.ObjectConverter;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
import com.webauthn4j.data.attestation.statement.AttestationStatement;
import com.webauthn4j.data.extension.authenticator.AuthenticationExtensionsAuthenticatorOutputs;
import com.webauthn4j.data.extension.authenticator.RegistrationExtensionAuthenticatorOutput;
import java.security.PublicKey;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.Put;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
/**
* Store DeviceCheck attestations along with accounts, so they can be retrieved later to validate assertions.
* <p>
* Callers associate a keyId and attestation with an account, and then use the corresponding key to make potentially
* many attested requests (assertions). Each assertion increments the counter associated with the key.
* <p>
* Callers can associate more than one keyId/attestation with an account (for example, they may get a new device).
* However, each keyId must only be registered for a single account.
*
* @implNote We use a second table keyed on the public key to enforce uniqueness.
*/
public class AppleDeviceChecks {
// B: uuid, primary key
public static final String KEY_ACCOUNT_UUID = "U";
// B: key id, sort key. The key id is the SHA256 of the X9.62 uncompressed point format of the public key
public static final String KEY_PUBLIC_KEY_ID = "KID";
// N: counter, the number of asserts signed by the public key (updates on every assert)
private static final String ATTR_COUNTER = "C";
// B: attestedCredentialData
private static final String ATTR_CRED_DATA = "CD";
// B: attestationStatement, CBOR
private static final String ATTR_STATEMENT = "S";
// B: authenticatorExtensions, CBOR
private static final String ATTR_AUTHENTICATOR_EXTENSIONS = "AE";
// B: public key bytes, primary key for the public key table
public static final String KEY_PUBLIC_KEY = "PK";
private static final String CONDITIONAL_CHECK_FAILED = "ConditionalCheckFailed";
private final DynamoDbClient dynamoDbClient;
private final String deviceCheckTableName;
private final String publicKeyConstraintTableName;
private final ObjectConverter objectConverter;
public AppleDeviceChecks(
final DynamoDbClient dynamoDbClient,
final ObjectConverter objectConverter,
final String deviceCheckTableName,
final String publicKeyConstraintTableName) {
this.dynamoDbClient = dynamoDbClient;
this.objectConverter = objectConverter;
this.deviceCheckTableName = deviceCheckTableName;
this.publicKeyConstraintTableName = publicKeyConstraintTableName;
}
/**
* Retrieve DeviceCheck keyIds
*
* @param account The account to fetch keyIds for
* @return A list of keyIds currently associated with the account
*/
public List<byte[]> keyIds(final Account account) {
return dynamoDbClient.queryPaginator(QueryRequest.builder()
.tableName(deviceCheckTableName)
.keyConditionExpression("#aci = :aci")
.expressionAttributeNames(Map.of("#aci", KEY_ACCOUNT_UUID, "#kid", KEY_PUBLIC_KEY_ID))
.expressionAttributeValues(Map.of(":aci", AttributeValues.fromUUID(account.getUuid())))
.projectionExpression("#kid")
.build())
.items()
.stream()
.flatMap(item -> getByteArray(item, KEY_PUBLIC_KEY_ID).stream())
.toList();
}
/**
* Register an attestation for a keyId with an account. The attestation can later be retrieved via {@link #lookup}. If
* the provided keyId is already registered with the account and is more up to date, no update will occur and this
* method will return false.
*
* @param account The account to store the registration
* @param keyId The keyId to associate with the account
* @param appleDevice Attestation information to store
* @return true if the attestation was stored, false if the keyId already had an attestation
* @throws DuplicatePublicKeyException If a different account has already registered this public key
*/
public boolean storeAttestation(final Account account, final byte[] keyId, final DCAppleDevice appleDevice)
throws DuplicatePublicKeyException {
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(
// Register the public key and associated data with the account
TransactWriteItem.builder().put(Put.builder()
.tableName(deviceCheckTableName)
.item(toItem(account, keyId, appleDevice))
// The caller should have done a non-transactional read to verify we didn't already have this keyId, but a
// race is possible. It's fine to wipe out an existing key (should be identical), as long as we don't
// lower the signed count associated with the key.
.conditionExpression("attribute_not_exists(#counter) OR #counter <= :counter")
.expressionAttributeNames(Map.of("#counter", ATTR_COUNTER))
.expressionAttributeValues(Map.of(":counter", AttributeValues.n(appleDevice.getCounter())))
.build()).build(),
// Enforce uniqueness on the supplied public key
TransactWriteItem.builder().put(Put.builder()
.tableName(publicKeyConstraintTableName)
.item(Map.of(
KEY_PUBLIC_KEY, AttributeValues.fromByteArray(extractPublicKey(appleDevice).getEncoded()),
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())
))
// Enforces public key uniqueness, as described in https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Store-the-public-key-and-receipt
.conditionExpression("attribute_not_exists(#pk) or #aci = :aci")
.expressionAttributeNames(Map.of("#aci", KEY_ACCOUNT_UUID, "#pk", KEY_PUBLIC_KEY))
.expressionAttributeValues(Map.of(":aci", AttributeValues.fromUUID(account.getUuid())))
.build()).build()).build());
return true;
} catch (TransactionCanceledException e) {
final CancellationReason updateCancelReason = e.cancellationReasons().get(0);
if (conditionalCheckFailed(updateCancelReason)) {
// The provided attestation is older than the one we already have stored
return false;
}
final CancellationReason publicKeyCancelReason = e.cancellationReasons().get(1);
if (conditionalCheckFailed(publicKeyCancelReason)) {
throw new DuplicatePublicKeyException();
}
throw e;
}
}
/**
* Retrieve the device attestation information previous registered with the account
*
* @param account The account that registered the keyId
* @param keyId The keyId that was registered
* @return Device attestation information that can be used to validate an assertion
*/
public Optional<DCAppleDevice> lookup(final Account account, final byte[] keyId) {
final GetItemResponse item = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(deviceCheckTableName)
.key(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
KEY_PUBLIC_KEY_ID, AttributeValues.fromByteArray(keyId))).build());
return item.hasItem() ? Optional.of(fromItem(item.item())) : Optional.empty();
}
/**
* Attempt to increase the signed counter to the newCounter value. This method enforces that the counter increases
* monotonically, if the new value is less than the existing counter, no update occurs and the method returns false.
*
* @param account The account the keyId is registered to
* @param keyId The keyId to update
* @param newCounter The new counter value
* @return true if the counter was updated, false if the stored counter was larger than newCounter
*/
public boolean updateCounter(final Account account, final byte[] keyId, final long newCounter) {
try {
dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(deviceCheckTableName)
.key(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
KEY_PUBLIC_KEY_ID, AttributeValues.fromByteArray(keyId)))
.expressionAttributeNames(Map.of("#counter", ATTR_COUNTER))
.expressionAttributeValues(Map.of(":counter", AttributeValues.n(newCounter)))
.updateExpression("SET #counter = :counter")
// someone could possibly race with us to update the counter. No big deal, but we shouldn't decrease the
// current counter
.conditionExpression("#counter <= :counter").build());
return true;
} catch (ConditionalCheckFailedException e) {
// We failed to increment the counter because it has already moved forward
return false;
}
}
private Map<String, AttributeValue> toItem(final Account account, final byte[] keyId, DCAppleDevice appleDevice) {
// Serialize the various data members, see: https://webauthn4j.github.io/webauthn4j/en/#deep-dive
final AttestedCredentialDataConverter attestedCredentialDataConverter =
new AttestedCredentialDataConverter(objectConverter);
final byte[] attestedCredentialData =
attestedCredentialDataConverter.convert(appleDevice.getAttestedCredentialData());
final byte[] attestationStatement = objectConverter.getCborConverter()
.writeValueAsBytes(new AttestationStatementEnvelope(appleDevice.getAttestationStatement()));
final long counter = appleDevice.getCounter();
final byte[] authenticatorExtensions = objectConverter.getCborConverter()
.writeValueAsBytes(appleDevice.getAuthenticatorExtensions());
return Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
KEY_PUBLIC_KEY_ID, AttributeValues.fromByteArray(keyId),
ATTR_CRED_DATA, AttributeValues.fromByteArray(attestedCredentialData),
ATTR_STATEMENT, AttributeValues.fromByteArray(attestationStatement),
ATTR_AUTHENTICATOR_EXTENSIONS, AttributeValues.fromByteArray(authenticatorExtensions),
ATTR_COUNTER, AttributeValues.n(counter));
}
private DCAppleDevice fromItem(final Map<String, AttributeValue> item) {
// Deserialize the fields stored in dynamodb, see: https://webauthn4j.github.io/webauthn4j/en/#deep-dive
final AttestedCredentialDataConverter attestedCredentialDataConverter =
new AttestedCredentialDataConverter(objectConverter);
final AttestedCredentialData credData = attestedCredentialDataConverter.convert(getByteArray(item, ATTR_CRED_DATA)
.orElseThrow(() -> new IllegalStateException("Stored device check key missing attestation credential data")));
// The attestationStatement is an interface, so we also need to encode enough type information (the format)
// so we know how to deserialize the statement. See https://webauthn4j.github.io/webauthn4j/en/#attestationstatement
final byte[] serializedStatementEnvelope = getByteArray(item, ATTR_STATEMENT)
.orElseThrow(() -> new IllegalStateException("Stored device check key missing attestation statement"));
final AttestationStatement statement = Optional.ofNullable(objectConverter.getCborConverter()
.readValue(serializedStatementEnvelope, AttestationStatementEnvelope.class))
.orElseThrow(() -> new IllegalStateException("Stored device check key missing attestation statement"))
.getAttestationStatement();
final long counter = AttributeValues.getLong(item, ATTR_COUNTER, 0);
final byte[] serializedExtensions = getByteArray(item, ATTR_AUTHENTICATOR_EXTENSIONS)
.orElseThrow(() -> new IllegalStateException("Stored device check key missing attestation extensions"));
@SuppressWarnings("unchecked") final AuthenticationExtensionsAuthenticatorOutputs<RegistrationExtensionAuthenticatorOutput> extensions = objectConverter.getCborConverter()
.readValue(serializedExtensions, AuthenticationExtensionsAuthenticatorOutputs.class);
return new DCAppleDeviceImpl(credData, statement, counter, extensions);
}
private static PublicKey extractPublicKey(DCAppleDevice appleDevice) {
// This is the leaf public key as described here:
// https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Verify-the-attestation
// We know the sha256 of the public key matches the keyId, the apple webauthn verifier validates that. Step 5 here:
// https://developer.apple.com/documentation/devicecheck/attestation-object-validation-guide#Walking-through-the-validation-steps
final AppleAppAttestAttestationStatement attestationStatement = ((AppleAppAttestAttestationStatement) appleDevice.getAttestationStatement());
Objects.requireNonNull(attestationStatement);
return attestationStatement.getX5c().getEndEntityAttestationCertificate().getCertificate().getPublicKey();
}
private static boolean conditionalCheckFailed(final CancellationReason reason) {
return CONDITIONAL_CHECK_FAILED.equals(reason.code());
}
private static Optional<byte[]> getByteArray(Map<String, AttributeValue> item, String key) {
return AttributeValues.get(item, key).map(av -> av.b().asByteArray());
}
/**
* Wrapper that provides type information when deserializing attestation statements
*/
private static class AttestationStatementEnvelope {
@JsonProperty("attStmt")
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "fmt"
)
private AttestationStatement attestationStatement;
@JsonCreator
public AttestationStatementEnvelope(@JsonProperty("attStmt") AttestationStatement attestationStatement) {
this.attestationStatement = attestationStatement;
}
@JsonProperty("fmt")
public String getFormat() {
return attestationStatement.getFormat();
}
public AttestationStatement getAttestationStatement() {
return attestationStatement;
}
}
}
@@ -0,0 +1,7 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
public class ChallengeNotFoundException extends Exception {}
@@ -0,0 +1,7 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
public class DeviceCheckKeyIdNotFoundException extends Exception {}
@@ -0,0 +1,16 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
public class DeviceCheckVerificationFailedException extends Exception {
public DeviceCheckVerificationFailedException(Exception cause) {
super(cause);
}
public DeviceCheckVerificationFailedException(String s) {
super(s);
}
}
@@ -0,0 +1,7 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
public class DuplicatePublicKeyException extends Exception {}
@@ -0,0 +1,12 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
public class RequestReuseException extends Exception {
public RequestReuseException(String s) {
super(s);
}
}
@@ -0,0 +1,7 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
public class TooManyKeysException extends Exception {}
@@ -453,7 +453,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
// not prorated. Braintree subscriptions cannot change their next billing date,
// so we must end the existing one and create a new one
return cancelSubscriptionAtEndOfCurrentPeriod(subscription)
return endSubscription(subscription)
.thenCompose(ignored -> {
final Transaction transaction = getLatestTransactionForSubscription(subscription)
@@ -504,19 +504,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
final Instant anchor = subscription.getFirstBillingDate().toInstant();
final Instant endOfCurrentPeriod = subscription.getBillingPeriodEndDate().toInstant();
boolean paymentProcessing = false;
ChargeFailure chargeFailure = null;
final Optional<Transaction> latestTransaction = getLatestTransactionForSubscription(subscription);
boolean latestTransactionFailed = false;
if (latestTransaction.isPresent()){
paymentProcessing = isPaymentProcessing(latestTransaction.get().getStatus());
if (getPaymentStatus(latestTransaction.get().getStatus()) != PaymentStatus.SUCCEEDED) {
latestTransactionFailed = true;
chargeFailure = createChargeFailure(latestTransaction.get());
}
}
final TransactionInfo latestTransactionInfo = getLatestTransactionForSubscription(subscription)
.map(this::getTransactionInfo)
.orElse(new TransactionInfo(PaymentMethod.PAYPAL, false, false, null));
return new SubscriptionInformation(
new SubscriptionPrice(plan.getCurrencyIsoCode().toUpperCase(Locale.ROOT),
@@ -526,16 +516,31 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
endOfCurrentPeriod,
Subscription.Status.ACTIVE == subscription.getStatus(),
!subscription.neverExpires(),
getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed),
getSubscriptionStatus(subscription.getStatus(), latestTransactionInfo.transactionFailed()),
PaymentProvider.BRAINTREE,
latestTransaction.map(this::getPaymentMethodFromTransaction).orElse(PaymentMethod.PAYPAL),
paymentProcessing,
chargeFailure
latestTransactionInfo.paymentMethod(),
latestTransactionInfo.paymentProcessing(),
latestTransactionInfo.chargeFailure()
);
}, executor);
}
private record TransactionInfo(
PaymentMethod paymentMethod,
boolean paymentProcessing,
boolean transactionFailed,
@Nullable ChargeFailure chargeFailure) {}
private TransactionInfo getTransactionInfo(final Transaction transaction) {
final boolean paymentProcessing = isPaymentProcessing(transaction.getStatus());
final PaymentMethod paymentMethod = getPaymentMethodFromTransaction(transaction);
if (getPaymentStatus(transaction.getStatus()) != PaymentStatus.SUCCEEDED) {
return new TransactionInfo(paymentMethod, paymentProcessing, true, createChargeFailure(transaction));
}
return new TransactionInfo(paymentMethod, paymentProcessing, false, null);
}
private PaymentMethod getPaymentMethodFromTransaction(Transaction transaction) {
if (transaction.getPayPalDetails() != null) {
return PaymentMethod.PAYPAL;
@@ -583,19 +588,37 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
.map(com.braintreegateway.PaymentMethod::getSubscriptions)
.orElse(Collections.emptyList())
.stream()
.map(this::cancelSubscriptionAtEndOfCurrentPeriod)
.map(this::endSubscription)
.toList();
return CompletableFuture.allOf(subscriptionCancelFutures.toArray(new CompletableFuture[0]));
});
}
private CompletableFuture<Void> endSubscription(Subscription subscription) {
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
.map(this::getTransactionInfo)
.map(TransactionInfo::transactionFailed)
.orElse(false);
return switch (getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed)) {
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
// going through.
case INCOMPLETE, PAST_DUE, UNPAID -> cancelSubscriptionImmediately(subscription);
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
// continue to be used until the end of the period.
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
};
}
private CompletableFuture<Void> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
return CompletableFuture.supplyAsync(() -> {
braintreeGateway.subscription().update(subscription.getId(),
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
return null;
}, executor);
return CompletableFuture.runAsync(() -> braintreeGateway
.subscription()
.update(subscription.getId(),
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle())), executor);
}
private CompletableFuture<Void> cancelSubscriptionImmediately(Subscription subscription) {
return CompletableFuture.runAsync(() -> braintreeGateway.subscription().cancel(subscription.getId()), executor);
}
@@ -9,6 +9,7 @@ import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.stripe.StripeClient;
import com.stripe.exception.CardException;
import com.stripe.exception.IdempotencyException;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
import com.stripe.model.Customer;
@@ -292,14 +293,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
// create a subscription, we want to ensure only one gets created.
return stripeClient.subscriptions()
.create(params, commonOptions(generateIdempotencyKeyForCreateSubscription(
customerId, lastSubscriptionCreatedAt)));
customerId, lastSubscriptionCreatedAt)));
} catch (IdempotencyException e) {
throw ExceptionUtils.wrap(new SubscriptionException.InvalidArguments(e.getStripeError().getMessage()));
} catch (CardException e) {
throw new CompletionException(
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e)));
} catch (StripeException e) {
if (e instanceof CardException ce) {
throw new CompletionException(
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e, ce)));
}
throw new CompletionException(e);
}
}, executor)
@@ -347,15 +347,14 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
return stripeClient.subscriptions().update(subscription.getId(), params,
commonOptions(
generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
} catch (IdempotencyException e) {
throw ExceptionUtils.wrap(new SubscriptionException.InvalidArguments(e.getStripeError().getMessage()));
} catch (CardException e) {
throw ExceptionUtils.wrap(
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e)));
} catch (StripeException e) {
if (e instanceof CardException ce) {
throw ExceptionUtils.wrap(
new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e, ce)));
}
throw ExceptionUtils.wrap(e);
}
}, executor)
.thenApply(subscription1 -> new SubscriptionId(subscription1.getId()));
}
@@ -385,7 +384,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}).thenCompose(subscriptions -> {
@SuppressWarnings("unchecked")
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
.map(this::cancelSubscriptionAtEndOfCurrentPeriod).toArray(CompletableFuture[]::new);
.map(this::endSubscription).toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures);
});
}
@@ -404,7 +403,19 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}, executor);
}
public CompletableFuture<Subscription> cancelSubscriptionImmediately(Subscription subscription) {
private CompletableFuture<Subscription> endSubscription(Subscription subscription) {
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
return switch (status) {
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
// going through.
case UNPAID, PAST_DUE, INCOMPLETE -> cancelSubscriptionImmediately(subscription);
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
// continue to be used until the end of the period.
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
};
}
private CompletableFuture<Subscription> cancelSubscriptionImmediately(Subscription subscription) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
try {
@@ -415,7 +426,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}, executor);
}
public CompletableFuture<Subscription> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
private CompletableFuture<Subscription> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.setCancelAtPeriodEnd(true)
@@ -522,9 +533,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
outcome != null ? outcome.getType() : null);
}
private static ChargeFailure createChargeFailureFromCardException(StripeException e, CardException ce) {
private static ChargeFailure createChargeFailureFromCardException(CardException e) {
return new ChargeFailure(
StringUtils.defaultIfBlank(ce.getDeclineCode(), ce.getCode()),
StringUtils.defaultIfBlank(e.getDeclineCode(), e.getCode()),
e.getStripeError().getMessage(),
null,
null,
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.util;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -21,4 +22,13 @@ public class EnumMapUtil {
},
() -> new EnumMap<>(enumClass)));
}
public static <E extends Enum<E>, V> EnumMap<E, V> toCompleteEnumMap(final Class<E> enumClass, final Map<E, V> map) {
for (E e : enumClass.getEnumConstants()) {
if (!map.containsKey(e)) {
throw new IllegalArgumentException("Missing enum key: " + e);
}
}
return new EnumMap<>(map);
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.util;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import jakarta.ws.rs.core.Response;
import java.time.Clock;
@@ -14,6 +15,7 @@ import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
@@ -24,15 +26,13 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.random.RandomGenerator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
public class Util {
private static final RandomGenerator rng = new Random();
private static final Pattern COUNTRY_CODE_PATTERN = Pattern.compile("^\\+([17]|2[07]|3[0123469]|4[013456789]|5[12345678]|6[0123456]|8[1246]|9[0123458]|\\d{3})");
private static final RandomGenerator RANDOM_GENERATOR = new Random();
private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();
@@ -89,10 +89,11 @@ public class Util {
}
public static String getCountryCode(String number) {
Matcher matcher = COUNTRY_CODE_PATTERN.matcher(number);
if (matcher.find()) return matcher.group(1);
else return "0";
try {
return String.valueOf(PHONE_NUMBER_UTIL.parse(number, null).getCountryCode());
} catch (final NumberParseException e) {
return "0";
}
}
public static String getRegion(final String number) {
@@ -104,12 +105,143 @@ public class Util {
}
}
public static String getNumberPrefix(String number) {
String countryCode = getCountryCode(number);
int remaining = number.length() - (1 + countryCode.length());
int prefixLength = Math.min(4, remaining);
/**
* Returns a list of equivalent phone numbers to the given phone number. This is useful in cases where a numbering
* authority has changed the numbering format for a region or in cases where multiple formats of a number may be valid
* in different circumstances. Numbers are considered equivalent if a call/message sent to each number will generally
* arrive at the same device.
*
* @apiNote This method is intended to support number format transitions in cases where we do not already have
* multiple accounts registered with different forms of the same number. As a result, this method does not cover all
* possible cases of equivalent formats, but instead focuses on the cases where we can and choose to prevent multiple
* accounts from using different formats of the same number.
*
* @param number the e164-formatted phone number for which to find equivalent forms
*
* @return a list of phone numbers equivalent to the given phone number, including the given number. The given number
* will always be the first element of the list.
*/
public static List<String> getAlternateForms(final String number) {
try {
final PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(number, null);
return number.substring(0, 1 + countryCode.length() + prefixLength);
// Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024
if ("BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber))) {
final String nationalSignificantNumber = PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
final String alternateE164;
if (nationalSignificantNumber.length() == 10) {
// This is a new-format number; we can get the old-format version by stripping the leading "01" from the
// national number
alternateE164 = "+229" + StringUtils.removeStart(nationalSignificantNumber, "01");
} else {
// This is an old-format number; we can get the new-format version by adding a "01" prefix to the national
// number
alternateE164 = "+22901" + nationalSignificantNumber;
}
return List.of(number, alternateE164);
}
return List.of(number);
} catch (final NumberParseException e) {
return List.of(number);
}
}
/**
* Returns the preferred form of an e164 from a list of equivalents. Only use this when there is no other reason (such
* as the form specifically provided by a user) to prefer a particular form and we want to reduce nondeterminism.
*
* @apiNote This method is intended to support number format transitions in cases where we do not already have
* multiple accounts registered with different forms of the same number. As a result, this method does not cover all
* possible cases of equivalent formats, but instead focuses on the cases where we can and choose to prevent multiple
* accounts from using different formats of the same number.
*
* @param e164s a list of equivalent forms of a single phone number
*
* @return a single preferred canonical form for the number
*/
public static Optional<String> getCanonicalNumber(List<String> e164s) {
if (e164s.size() <= 1) {
return e164s.stream().findFirst();
}
try {
final List<PhoneNumber> phoneNumbers = new ArrayList<>(e164s.size());
for (String e164 : e164s) {
phoneNumbers.add(PHONE_NUMBER_UTIL.parse(e164, null));
}
final Set<String> regions = phoneNumbers.stream().map(PHONE_NUMBER_UTIL::getRegionCodeForNumber).collect(Collectors.toSet());
if (regions.size() != 1) {
throw new IllegalArgumentException("Numbers from different countries cannot be equivalent alternate forms");
}
if (regions.contains("BJ")) {
// Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024
// We prefer the longest form for long-term stability
return e164s.stream().sorted(Comparator.comparingInt(String::length).reversed()).findFirst();
}
// No matching country; fall back to something that's at least stable
return e164s.stream().sorted().findFirst();
} catch (final NumberParseException e) {
return e164s.stream().sorted().findFirst();
}
}
/**
* Tests whether the decimal form of the given number (without leading zeroes) begins with the decimal form of the
* given prefix (without leading zeroes).
*
* @param number the number to check for the given prefix
* @param prefix the prefix
*
* @return {@code true} if the given number starts with the given prefix or {@code false} otherwise
*
* @throws IllegalArgumentException if {@code number} is negative or if {@code prefix} is zero or negative
*/
public static boolean startsWithDecimal(final long number, final long prefix) {
if (number < 0) {
throw new IllegalArgumentException("Number must be non-negative");
}
if (prefix <= 0) {
throw new IllegalArgumentException("Prefix must be positive");
}
long workingCopy = number;
while (workingCopy > prefix) {
workingCopy /= 10;
}
return workingCopy == prefix;
}
/**
* Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024.
*
* @param phoneNumber the phone number to check.
* @return whether the provided phone number is an old-format Benin phone number
*/
public static boolean isOldFormatBeninPhoneNumber(final Phonenumber.PhoneNumber phoneNumber) {
return "BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber)) &&
PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber).length() == 8;
}
/**
* If applicable, return the canonical form of the provided phone number.
* This is relevant in cases where a numbering authority has changed the numbering format for a region.
*
* @param phoneNumber the phone number to canonicalize.
* @return the canonical phone number if applicable, otherwise the original phone number.
*/
public static Phonenumber.PhoneNumber canonicalizePhoneNumber(final Phonenumber.PhoneNumber phoneNumber)
throws NumberParseException {
if (isOldFormatBeninPhoneNumber(phoneNumber)) {
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024.
final String newFormatNumber = "+22901" + PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
return PhoneNumberUtil.getInstance().parse(newFormatNumber, null);
}
return phoneNumber;
}
public static byte[] truncate(byte[] element, int length) {
@@ -122,7 +254,8 @@ public class Util {
public static void sleep(long i) {
try {
Thread.sleep(i);
} catch (InterruptedException ie) {}
} catch (final InterruptedException ignored) {
}
}
public static long todayInMillis() {
@@ -196,8 +329,8 @@ public class Util {
return values;
}
Set<Integer> indices = new HashSet<>(rng.ints(0, values.size()).distinct().limit(n).boxed().toList());
List<E> result = new ArrayList<E>(n);
Set<Integer> indices = new HashSet<>(RANDOM_GENERATOR.ints(0, values.size()).distinct().limit(n).boxed().toList());
List<E> result = new ArrayList<>(n);
for(int i = 0; i < values.size() && result.size() < n; i++) {
if(indices.contains(i)) {
result.add(values.get(i));
@@ -32,6 +32,7 @@ import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery3Controller;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
@@ -44,12 +45,14 @@ 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.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeys;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesCache;
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
@@ -78,6 +81,7 @@ record CommandDependencies(
MessagesCache messagesCache,
MessagesManager messagesManager,
KeysManager keysManager,
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
APNSender apnSender,
FcmSender fcmSender,
PushNotificationManager pushNotificationManager,
@@ -86,8 +90,10 @@ record CommandDependencies(
FaultTolerantRedisClusterClient pushSchedulerCluster,
ClientResources.Builder redisClusterClientResourcesBuilder,
BackupManager backupManager,
IssuedReceiptsManager issuedReceiptsManager,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
DynamoDbAsyncClient dynamoDbAsyncClient) {
DynamoDbAsyncClient dynamoDbAsyncClient,
PhoneNumberIdentifiers phoneNumberIdentifiers) {
static CommandDependencies build(
final String name,
@@ -151,8 +157,10 @@ record CommandDependencies(
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
configuration.getSecureStorageServiceConfiguration());
ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
ExternalServiceCredentialsGenerator secureValueRecovery2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
configuration.getSvr2Configuration());
ExternalServiceCredentialsGenerator secureValueRecovery3CredentialsGenerator = SecureValueRecovery3Controller.credentialsGenerator(
configuration.getSvr3Configuration());
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
.virtualExecutorService(MetricRegistry.name(CommandDependencies.class, "awsSdkMetrics-%d"));
@@ -166,17 +174,14 @@ record CommandDependencies(
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
dynamoDbClient,
dynamoDbAsyncClient
);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
registrationRecoveryPasswords);
dynamoDbAsyncClient,
clock);
ClientPublicKeys clientPublicKeys =
new ClientPublicKeys(dynamoDbAsyncClient, configuration.getDynamoDbTables().getClientPublicKeys().getTableName());
Accounts accounts = new Accounts(
clock,
dynamoDbClient,
dynamoDbAsyncClient,
configuration.getDynamoDbTables().getAccounts().getTableName(),
@@ -185,7 +190,7 @@ record CommandDependencies(
configuration.getDynamoDbTables().getAccounts().getUsernamesTableName(),
configuration.getDynamoDbTables().getDeletedAccounts().getTableName(),
configuration.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfiles().getTableName());
@@ -205,14 +210,18 @@ record CommandDependencies(
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
redisClientResourcesBuilder);
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
secureValueRecoveryCredentialsGenerator, secureValueRecoveryServiceExecutor,
secureValueRecovery2CredentialsGenerator, secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
configuration.getSvr2Configuration());
SecureValueRecovery3Client secureValueRecovery3Client = new SecureValueRecovery3Client(
secureValueRecovery3CredentialsGenerator, secureValueRecoveryServiceExecutor,
secureValueRecoveryServiceRetryExecutor,
configuration.getSvr3Configuration());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
configuration.getDynamoDbTables().getReportMessage().getTableName(),
@@ -225,9 +234,11 @@ record CommandDependencies(
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
ClientPublicKeysManager clientPublicKeysManager =
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
secureStorageClient, secureValueRecovery2Client, secureValueRecovery3Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
RateLimiters rateLimiters = RateLimiters.createAndValidate(configuration.getLimitsConfiguration(),
@@ -252,6 +263,14 @@ record CommandDependencies(
remoteStorageRetryExecutor,
configuration.getCdn3StorageManagerConfiguration()),
clock);
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
configuration.getDynamoDbTables().getIssuedReceipts().getExpiration(),
dynamoDbAsyncClient,
configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(),
configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
APNSender apnSender = new APNSender(apnSenderExecutor, configuration.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, configuration.getFcmConfiguration().credentials().value());
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
@@ -278,6 +297,7 @@ record CommandDependencies(
messagesCache,
messagesManager,
keys,
registrationRecoveryPasswordsManager,
apnSender,
fcmSender,
pushNotificationManager,
@@ -286,8 +306,10 @@ record CommandDependencies(
pushSchedulerCluster,
redisClientResourcesBuilder,
backupManager,
issuedReceiptsManager,
dynamicConfigurationManager,
dynamoDbAsyncClient
dynamoDbAsyncClient,
phoneNumberIdentifiers
);
}
@@ -0,0 +1,14 @@
-----BEGIN CERTIFICATE-----
MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYw
JAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwK
QXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNa
Fw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlv
biBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9y
bmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdh
NbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9au
Yen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/
MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYw
CgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn
53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijV
oyFraWVIyd/dganmrduC1bmTBGwD
-----END CERTIFICATE-----
@@ -31,11 +31,11 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -53,7 +53,7 @@ class RegistrationLockVerificationManagerTest {
ExternalServiceCredentialsGenerator.class);
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
RegistrationRecoveryPasswordsManager.class);
private static PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
private final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
private final RateLimiters rateLimiters = mock(RateLimiters.class);
private final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator,
@@ -103,14 +103,15 @@ class RegistrationLockVerificationManagerTest {
if (e instanceof WebApplicationException wae) {
assertEquals(RegistrationLockVerificationManager.FAILURE_HTTP_STATUS, wae.getResponse().getStatus());
if (!verificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
verify(registrationRecoveryPasswordsManager).removeForNumber(account.getNumber());
verify(registrationRecoveryPasswordsManager).remove(account.getIdentifier(IdentityType.PNI));
} else {
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
verify(registrationRecoveryPasswordsManager, never()).remove(any());
}
verify(disconnectionRequestManager).requestDisconnection(account.getUuid(), List.of(Device.PRIMARY_ID));
try {
verify(pushNotificationManager).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
} catch (NotPushRegisteredException npre) {}
} catch (final NotPushRegisteredException ignored) {
}
if (alreadyLocked) {
verify(account, never()).lockAuthTokenHash();
} else {
@@ -126,10 +127,13 @@ class RegistrationLockVerificationManagerTest {
doThrow(RateLimitExceededException.class).when(pinLimiter).validate(anyString());
yield new Pair<>(RateLimitExceededException.class, ignored -> {
verify(account, never()).lockAuthTokenHash();
try {
verify(pushNotificationManager, never()).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
} catch (NotPushRegisteredException npre) {}
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
} catch (final NotPushRegisteredException ignored2) {
}
verify(registrationRecoveryPasswordsManager, never()).remove(any());
verify(disconnectionRequestManager, never()).requestDisconnection(any(), any());
});
}
@@ -167,7 +171,7 @@ class RegistrationLockVerificationManagerTest {
PhoneVerificationRequest.VerificationType.SESSION));
verify(account, never()).lockAuthTokenHash();
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
verify(registrationRecoveryPasswordsManager, never()).remove(any());
verify(disconnectionRequestManager, never()).requestDisconnection(any(), any());
}
@@ -786,7 +786,7 @@ class AccountControllerTest {
.withRecoveryPassword(recoveryPassword)))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(registrationRecoveryPasswordsManager).storeForCurrentNumber(eq(AuthHelper.UNDISCOVERABLE_NUMBER), eq(recoveryPassword));
verify(registrationRecoveryPasswordsManager).store(AuthHelper.UNDISCOVERABLE_PNI, recoveryPassword);
}
}
@@ -86,6 +86,7 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
@@ -105,6 +106,7 @@ class AccountControllerV2Test {
private final AccountsManager accountsManager = mock(AccountsManager.class);
private final ChangeNumberManager changeNumberManager = mock(ChangeNumberManager.class);
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
RegistrationRecoveryPasswordsManager.class);
@@ -125,8 +127,8 @@ class AccountControllerV2Test {
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
new AccountControllerV2(accountsManager, changeNumberManager,
new PhoneVerificationTokenManager(registrationServiceClient, registrationRecoveryPasswordsManager,
registrationRecoveryChecker),
new PhoneVerificationTokenManager(phoneNumberIdentifiers, registrationServiceClient,
registrationRecoveryPasswordsManager, registrationRecoveryChecker),
registrationLockVerificationManager, rateLimiters))
.build();
@@ -217,6 +219,24 @@ class AccountControllerV2Test {
assertEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
}
@Test
void changeNumberNonNormalizedNumber() throws Exception {
try (Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.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()),
Collections.emptyList(),
Collections.emptyMap(), null, Collections.emptyMap()),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(422, response.getStatus());
}
}
@Test
void unprocessableRequestJson() {
final Invocation.Builder request = resources.getJerseyTest()
@@ -383,6 +403,8 @@ class AccountControllerV2Test {
@Test
void recoveryPasswordManagerVerificationTrue() throws Exception {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any()))
@@ -425,6 +447,8 @@ class AccountControllerV2Test {
@Test
void registrationRecoveryCheckerAllowsAttempt() {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
@@ -0,0 +1,225 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
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.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.ChallengeNotFoundException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckKeyIdNotFoundException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckVerificationFailedException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DuplicatePublicKeyException;
import org.whispersystems.textsecuregcm.storage.devicecheck.RequestReuseException;
import org.whispersystems.textsecuregcm.storage.devicecheck.TooManyKeysException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
class DeviceCheckControllerTest {
private final static Duration REDEMPTION_DURATION = Duration.ofDays(5);
private final static long REDEMPTION_LEVEL = 201L;
private final static BackupAuthManager backupAuthManager = mock(BackupAuthManager.class);
private final static AppleDeviceCheckManager appleDeviceCheckManager = mock(AppleDeviceCheckManager.class);
private final static RateLimiters rateLimiters = mock(RateLimiters.class);
private final static Clock clock = TestClock.pinned(Instant.EPOCH);
private static final ResourceExtension resources = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.addProvider(new CompletionExceptionMapper())
.addResource(new GrpcStatusRuntimeExceptionMapper())
.addProvider(new RateLimitExceededExceptionMapper())
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new DeviceCheckController(clock, backupAuthManager, appleDeviceCheckManager, rateLimiters,
REDEMPTION_LEVEL, REDEMPTION_DURATION))
.build();
@BeforeEach
public void setUp() {
reset(backupAuthManager);
reset(appleDeviceCheckManager);
reset(rateLimiters);
when(rateLimiters.forDescriptor(any())).thenReturn(mock(RateLimiter.class));
}
@ParameterizedTest
@EnumSource(AppleDeviceCheckManager.ChallengeType.class)
public void createChallenge(AppleDeviceCheckManager.ChallengeType challengeType) throws RateLimitExceededException {
when(appleDeviceCheckManager.createChallenge(eq(challengeType), any()))
.thenReturn("TestChallenge");
WebTarget target = resources.getJerseyTest()
.target("v1/devicecheck/%s".formatted(switch (challengeType) {
case ATTEST -> "attest";
case ASSERT_BACKUP_REDEMPTION -> "assert";
}));
if (challengeType == AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION) {
target = target.queryParam("action", "backup");
}
final DeviceCheckController.ChallengeResponse challenge = target
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(DeviceCheckController.ChallengeResponse.class);
assertThat(challenge.challenge()).isEqualTo("TestChallenge");
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void createChallengeRateLimited(boolean create) throws RateLimitExceededException {
final RateLimiter rateLimiter = mock(RateLimiter.class);
when(rateLimiters.forDescriptor(RateLimiters.For.DEVICE_CHECK_CHALLENGE)).thenReturn(rateLimiter);
doThrow(new RateLimitExceededException(Duration.ofSeconds(1L))).when(rateLimiter).validate(any(UUID.class));
final String path = "v1/devicecheck/%s".formatted(create ? "assert" : "attest");
final Response response = resources.getJerseyTest()
.target(path)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get();
assertThat(response.getStatus()).isEqualTo(429);
}
@Test
public void failedAttestValidation()
throws DeviceCheckVerificationFailedException, ChallengeNotFoundException, TooManyKeysException, DuplicatePublicKeyException {
final String errorMessage = "a test error message";
final byte[] keyId = TestRandomUtil.nextBytes(16);
final byte[] attestation = TestRandomUtil.nextBytes(32);
doThrow(new DeviceCheckVerificationFailedException(errorMessage)).when(appleDeviceCheckManager)
.registerAttestation(any(), eq(keyId), eq(attestation));
final Response response = resources.getJerseyTest()
.target("v1/devicecheck/attest")
.queryParam("keyId", Base64.getUrlEncoder().encodeToString(keyId))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(attestation, MediaType.APPLICATION_OCTET_STREAM));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getMediaType()).isEqualTo(MediaType.APPLICATION_JSON_TYPE);
assertThat(response.readEntity(Map.class).get("message")).isEqualTo(errorMessage);
}
@Test
public void failedAssertValidation()
throws DeviceCheckVerificationFailedException, ChallengeNotFoundException, DeviceCheckKeyIdNotFoundException, RequestReuseException {
final String errorMessage = "a test error message";
final byte[] keyId = TestRandomUtil.nextBytes(16);
final byte[] assertion = TestRandomUtil.nextBytes(32);
final String challenge = "embeddedChallenge";
final String request = """
{"action": "backup", "challenge": "embeddedChallenge"}
""";
doThrow(new DeviceCheckVerificationFailedException(errorMessage)).when(appleDeviceCheckManager)
.validateAssert(any(), eq(keyId), eq(AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION), eq(challenge), eq(request.getBytes()), eq(assertion));
final Response response = resources.getJerseyTest()
.target("v1/devicecheck/assert")
.queryParam("keyId", Base64.getUrlEncoder().encodeToString(keyId))
.queryParam("request", Base64.getUrlEncoder().encodeToString(request.getBytes(StandardCharsets.UTF_8)))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.post(Entity.entity(assertion, MediaType.APPLICATION_OCTET_STREAM));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getMediaType()).isEqualTo(MediaType.APPLICATION_JSON_TYPE);
assertThat(response.readEntity(Map.class).get("message")).isEqualTo(errorMessage);
}
@Test
public void registerKey()
throws DeviceCheckVerificationFailedException, ChallengeNotFoundException, TooManyKeysException, DuplicatePublicKeyException {
final byte[] keyId = TestRandomUtil.nextBytes(16);
final byte[] attestation = TestRandomUtil.nextBytes(32);
final Response response = resources.getJerseyTest()
.target("v1/devicecheck/attest")
.queryParam("keyId", Base64.getUrlEncoder().encodeToString(keyId))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(attestation, MediaType.APPLICATION_OCTET_STREAM));
assertThat(response.getStatus()).isEqualTo(204);
verify(appleDeviceCheckManager, times(1))
.registerAttestation(any(), eq(keyId), eq(attestation));
}
@Test
public void checkAssertion()
throws DeviceCheckKeyIdNotFoundException, DeviceCheckVerificationFailedException, ChallengeNotFoundException, RequestReuseException {
final byte[] keyId = TestRandomUtil.nextBytes(16);
final byte[] assertion = TestRandomUtil.nextBytes(32);
final String challenge = "embeddedChallenge";
final String request = """
{"action": "backup", "challenge": "embeddedChallenge"}
""";
when(backupAuthManager.extendBackupVoucher(any(), eq(new Account.BackupVoucher(
REDEMPTION_LEVEL,
clock.instant().plus(REDEMPTION_DURATION)))))
.thenReturn(CompletableFuture.completedFuture(null));
final Response response = resources.getJerseyTest()
.target("v1/devicecheck/assert")
.queryParam("keyId", Base64.getUrlEncoder().encodeToString(keyId))
.queryParam("request", Base64.getUrlEncoder().encodeToString(request.getBytes(StandardCharsets.UTF_8)))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.post(Entity.entity(assertion, MediaType.APPLICATION_OCTET_STREAM));
assertThat(response.getStatus()).isEqualTo(204);
verify(appleDeviceCheckManager, times(1)).validateAssert(
any(),
eq(keyId),
eq(AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION),
eq(challenge),
eq(request.getBytes(StandardCharsets.UTF_8)),
eq(assertion));
}
}
@@ -66,12 +66,14 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
@@ -80,7 +82,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
@@ -112,7 +113,6 @@ class DeviceControllerTest {
private static final Account maxedAccount = mock(Account.class);
private static final Device primaryDevice = mock(Device.class);
private static final DisconnectionRequestManager disconnectionRequestManager = mock(DisconnectionRequestManager.class);
private static final WebSocketConnectionEventManager webSocketConnectionEventManager = mock(WebSocketConnectionEventManager.class);
private static final Map<String, Integer> deviceConfiguration = new HashMap<>();
private static final TestClock testClock = TestClock.now();
@@ -179,6 +179,37 @@ class DeviceControllerTest {
testClock.unpin();
}
@Test
void getDevices() {
final byte deviceId = Device.PRIMARY_ID;
final byte[] deviceName = "refreshed-device-name".getBytes(StandardCharsets.UTF_8);
final long deviceCreated = System.currentTimeMillis();
final long deviceLastSeen = deviceCreated + 1;
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);
final Account refreshedAccount = mock(Account.class);
when(refreshedAccount.getDevices()).thenReturn(List.of(refreshedDevice));
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(refreshedAccount));
final DeviceInfoList deviceInfoList = resources.getJerseyTest()
.target("/v1/devices")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(DeviceInfoList.class);
assertEquals(1, deviceInfoList.devices().size());
assertEquals(deviceId, deviceInfoList.devices().getFirst().id());
assertArrayEquals(deviceName, deviceInfoList.devices().getFirst().name());
assertEquals(deviceCreated, deviceInfoList.devices().getFirst().created());
assertEquals(deviceLastSeen, deviceInfoList.devices().getFirst().lastSeen());
}
@ParameterizedTest
@MethodSource
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@@ -1050,6 +1081,30 @@ class DeviceControllerTest {
}
}
@Test
void recordTransferArchiveFailed() {
final byte deviceId = Device.PRIMARY_ID + 1;
final Instant deviceCreated = Instant.now().truncatedTo(ChronoUnit.MILLIS);
final RemoteAttachmentError transferFailure = new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.recordTransferArchiveUpload(AuthHelper.VALID_ACCOUNT, deviceId, deviceCreated, transferFailure))
.thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/transfer_archive")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.toEpochMilli(), transferFailure),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(204, response.getStatus());
verify(accountsManager)
.recordTransferArchiveUpload(AuthHelper.VALID_ACCOUNT, deviceId, deviceCreated, transferFailure);
}
}
@ParameterizedTest
@MethodSource
void recordTransferArchiveUploadedBadRequest(final TransferArchiveUploadedRequest request) {
@@ -1130,6 +1185,26 @@ class DeviceControllerTest {
}
}
@Test
void waitForTransferArchiveUploadFailed() {
final RemoteAttachment transferArchive =
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
when(rateLimiter.validateAsync(anyString())).thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.waitForTransferArchive(eq(AuthHelper.VALID_ACCOUNT), eq(AuthHelper.VALID_DEVICE), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(transferArchive)));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/transfer_archive/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get()) {
assertEquals(200, response.getStatus());
assertEquals(transferArchive, response.readEntity(RemoteAttachment.class));
}
}
@Test
void waitForTransferArchiveNoArchiveUploaded() {
when(rateLimiter.validateAsync(anyString())).thenReturn(CompletableFuture.completedFuture(null));
@@ -121,6 +121,7 @@ import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RemovedMessage;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
@@ -182,6 +183,7 @@ class MessageControllerTest {
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
private static final CardinalityEstimator cardinalityEstimator = mock(CardinalityEstimator.class);
private static final RateLimiter rateLimiter = mock(RateLimiter.class);
private static final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
private static final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
private static final PushNotificationScheduler pushNotificationScheduler = mock(PushNotificationScheduler.class);
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
@@ -205,9 +207,9 @@ class MessageControllerTest {
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager,
messagesManager, pushNotificationManager, pushNotificationScheduler, reportMessageManager, multiRecipientMessageExecutor,
messageDeliveryScheduler, mock(ClientReleaseManager.class), dynamicConfigurationManager,
serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, multiRecipientMessageExecutor, messageDeliveryScheduler, mock(ClientReleaseManager.class),
dynamicConfigurationManager, serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
clock))
.build();
@@ -286,6 +288,7 @@ class MessageControllerTest {
rateLimiters,
rateLimiter,
cardinalityEstimator,
phoneNumberIdentifiers,
pushNotificationManager,
reportMessageManager
);
@@ -807,7 +810,6 @@ class MessageControllerTest {
@Test
void testReportMessageByE164() {
final String senderNumber = "+12125550001";
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
@@ -820,8 +822,6 @@ class MessageControllerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
when(accountsManager.getByE164(senderNumber)).thenReturn(Optional.of(account));
when(accountsManager.findRecentlyDeletedAccountIdentifier(senderNumber)).thenReturn(Optional.of(senderAci));
when(accountsManager.getPhoneNumberIdentifier(senderNumber)).thenReturn(senderPni);
try (final Response response =
resources.getJerseyTest()
@@ -835,12 +835,27 @@ class MessageControllerTest {
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent);
verify(accountsManager, never()).findRecentlyDeletedE164(any(UUID.class));
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
verify(accountsManager, never()).findRecentlyDeletedPhoneNumberIdentifier(any(UUID.class));
verify(phoneNumberIdentifiers, never()).getPhoneNumber(any());
}
}
@Test
void testReportMesageByE164DeletedAccount() {
final String senderNumber = "+12125550001";
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
final String userAgent = "user-agent";
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
when(accountsManager.getByE164(senderNumber)).thenReturn(Optional.empty());
messageGuid = UUID.randomUUID();
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(senderNumber)).thenReturn(CompletableFuture.completedFuture(senderPni));
when(accountsManager.findRecentlyDeletedAccountIdentifier(senderPni)).thenReturn(Optional.of(senderAci));
try (final Response response =
resources.getJerseyTest()
@@ -859,7 +874,6 @@ class MessageControllerTest {
@Test
void testReportMessageByAci() {
final String senderNumber = "+12125550001";
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
@@ -872,8 +886,7 @@ class MessageControllerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
when(accountsManager.findRecentlyDeletedE164(senderAci)).thenReturn(Optional.of(senderNumber));
when(accountsManager.getPhoneNumberIdentifier(senderNumber)).thenReturn(senderPni);
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
try (final Response response =
resources.getJerseyTest()
@@ -887,11 +900,27 @@ class MessageControllerTest {
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent);
verify(accountsManager, never()).findRecentlyDeletedE164(any(UUID.class));
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
verify(accountsManager, never()).findRecentlyDeletedPhoneNumberIdentifier(any(UUID.class));
verify(phoneNumberIdentifiers, never()).getPhoneNumber(any());
}
}
@Test
void testReportMessageByAciDeletedAccount() {
final String senderNumber = "+12125550001";
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
final String userAgent = "user-agent";
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.empty());
when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni));
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
messageGuid = UUID.randomUUID();
@@ -924,8 +953,8 @@ class MessageControllerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
when(accountsManager.findRecentlyDeletedE164(senderAci)).thenReturn(Optional.of(senderNumber));
when(accountsManager.getPhoneNumberIdentifier(senderNumber)).thenReturn(senderPni);
when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni));
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
Entity<SpamReport> entity = Entity.entity(new SpamReport(new byte[3]), "application/json");
@@ -944,8 +973,8 @@ class MessageControllerTest {
eq(AuthHelper.VALID_UUID),
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[3])).orElse(false)),
any());
verify(accountsManager, never()).findRecentlyDeletedE164(any(UUID.class));
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
verify(accountsManager, never()).findRecentlyDeletedPhoneNumberIdentifier(any(UUID.class));
verify(phoneNumberIdentifiers, never()).getPhoneNumber(any());
}
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.empty());
@@ -987,8 +1016,8 @@ class MessageControllerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
when(accountsManager.findRecentlyDeletedE164(senderAci)).thenReturn(Optional.of(senderNumber));
when(accountsManager.getPhoneNumberIdentifier(senderNumber)).thenReturn(senderPni);
when(accountsManager.findRecentlyDeletedPhoneNumberIdentifier(senderAci)).thenReturn(Optional.of(senderPni));
when(phoneNumberIdentifiers.getPhoneNumber(senderPni)).thenReturn(CompletableFuture.completedFuture(List.of(senderNumber)));
try (final Response response =
resources.getJerseyTest()
@@ -7,6 +7,7 @@ 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;
@@ -77,6 +78,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
@@ -94,6 +96,7 @@ class RegistrationControllerTest {
private static final String PASSWORD = "password";
private final AccountsManager accountsManager = mock(AccountsManager.class);
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
private final RegistrationLockVerificationManager registrationLockVerificationManager = mock(
RegistrationLockVerificationManager.class);
@@ -113,8 +116,8 @@ class RegistrationControllerTest {
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
new RegistrationController(accountsManager,
new PhoneVerificationTokenManager(registrationServiceClient, registrationRecoveryPasswordsManager,
registrationRecoveryChecker),
new PhoneVerificationTokenManager(phoneNumberIdentifiers, registrationServiceClient,
registrationRecoveryPasswordsManager, registrationRecoveryChecker),
registrationLockVerificationManager, rateLimiters))
.build();
@@ -243,6 +246,8 @@ class RegistrationControllerTest {
@Test
void recoveryPasswordManagerVerificationFailureOrTimeout() {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
@@ -289,6 +294,8 @@ class RegistrationControllerTest {
@Test
void recoveryPasswordManagerVerificationTrue() throws InterruptedException {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
@@ -325,6 +332,8 @@ class RegistrationControllerTest {
@Test
void registrationRecoveryCheckerAllowsAttempt() throws InterruptedException {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
when(registrationRecoveryPasswordsManager.verify(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
@@ -55,6 +55,8 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class SecureValueRecovery3ControllerTest extends SecureValueRecoveryControllerBaseTest {
private static final SecureValueRecovery3Configuration CFG = new SecureValueRecovery3Configuration(
"",
"",
"",
randomSecretBytes(32),
randomSecretBytes(32),
@@ -23,6 +23,7 @@ import static org.mockito.Mockito.when;
import com.google.common.net.HttpHeaders;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import io.grpc.Status;
@@ -39,6 +40,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Stream;
@@ -77,6 +79,7 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -87,14 +90,18 @@ class VerificationControllerTest {
private static final long SESSION_EXPIRATION_SECONDS = Duration.ofMinutes(10).toSeconds();
private static final byte[] SESSION_ID = "session".getBytes(StandardCharsets.UTF_8);
private static final String NUMBER = "+18005551212";
private static final String NUMBER = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"),
PhoneNumberUtil.PhoneNumberFormat.E164);
private static final UUID PNI = UUID.randomUUID();
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
private final VerificationSessionManager verificationSessionManager = mock(VerificationSessionManager.class);
private final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
private final RegistrationCaptchaManager registrationCaptchaManager = mock(RegistrationCaptchaManager.class);
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
RegistrationRecoveryPasswordsManager.class);
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
private final RateLimiters rateLimiters = mock(RateLimiters.class);
private final AccountsManager accountsManager = mock(AccountsManager.class);
private final Clock clock = Clock.systemUTC();
@@ -115,7 +122,7 @@ class VerificationControllerTest {
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
new VerificationController(registrationServiceClient, verificationSessionManager, pushNotificationManager,
registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters, accountsManager,
registrationCaptchaManager, registrationRecoveryPasswordsManager, phoneNumberIdentifiers, rateLimiters, accountsManager,
RegistrationFraudChecker.noop(), dynamicConfigurationManager, clock))
.build();
@@ -131,6 +138,8 @@ class VerificationControllerTest {
.thenReturn(new DynamicRegistrationConfiguration(false));
when(dynamicConfigurationManager.getConfiguration())
.thenReturn(dynamicConfiguration);
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(NUMBER))
.thenReturn(CompletableFuture.completedFuture(PNI));
}
@ParameterizedTest
@@ -205,6 +214,45 @@ class VerificationControllerTest {
}
}
@ParameterizedTest
@MethodSource
void createBeninSessionSuccess(final String requestedNumber, final String expectedNumber) {
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.insert(any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
.request()
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
try (Response response = request.post(Entity.json(createSessionJson(requestedNumber, "token", "fcm")))) {
assertEquals(HttpStatus.SC_OK, response.getStatus());
final ArgumentCaptor<Phonenumber.PhoneNumber> phoneNumberArgumentCaptor = ArgumentCaptor.forClass(
Phonenumber.PhoneNumber.class);
verify(registrationServiceClient).createRegistrationSession(phoneNumberArgumentCaptor.capture(), anyBoolean(), any());
final Phonenumber.PhoneNumber phoneNumber = phoneNumberArgumentCaptor.getValue();
assertEquals(expectedNumber, PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164));
}
}
private static Stream<Arguments> createBeninSessionSuccess() {
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
return Stream.of(
Arguments.of(oldFormatBeninE164, newFormatBeninE164),
Arguments.of(newFormatBeninE164, newFormatBeninE164),
Arguments.of(NUMBER, NUMBER)
);
}
@ParameterizedTest
@MethodSource
void createSessionSuccess(final String pushToken, final String pushTokenType,
@@ -573,7 +621,7 @@ class VerificationControllerTest {
assertTrue(verificationSessionResponse.verified());
assertTrue(verificationSessionResponse.requestedInformation().isEmpty());
verify(registrationRecoveryPasswordsManager).removeForNumber(registrationServiceSession.number());
verify(registrationRecoveryPasswordsManager).remove(PNI);
}
}
@@ -870,7 +918,7 @@ class VerificationControllerTest {
try (Response response = request.get()) {
assertEquals(HttpStatus.SC_OK, response.getStatus());
verify(registrationRecoveryPasswordsManager).removeForNumber(registrationServiceSession.number());
verify(registrationRecoveryPasswordsManager).remove(PNI);
}
}
@@ -1195,7 +1243,7 @@ class VerificationControllerTest {
VerificationSessionResponse.class);
assertTrue(verificationSessionResponse.verified());
verify(registrationRecoveryPasswordsManager).removeForNumber(registrationServiceSession.number());
verify(registrationRecoveryPasswordsManager).remove(PNI);
}
}
@@ -1327,7 +1375,7 @@ class VerificationControllerTest {
assertTrue(verificationSessionResponse.verified());
verify(registrationRecoveryPasswordsManager).removeForNumber(verifiedSession.number());
verify(registrationRecoveryPasswordsManager).remove(PNI);
}
}
@@ -65,6 +65,7 @@ import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -113,7 +114,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(rateLimiter.validateReactive(any(UUID.class))).thenReturn(Mono.empty());
when(rateLimiter.validateReactive(anyString())).thenReturn(Mono.empty());
when(registrationRecoveryPasswordsManager.storeForCurrentNumber(anyString(), any()))
when(registrationRecoveryPasswordsManager.store(any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
return new AccountsGrpcService(accountsManager,
@@ -261,7 +262,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final List<byte[]> usernameHashes = invocation.getArgument(1);
return CompletableFuture.completedFuture(
new AccountsManager.UsernameReservation(invocation.getArgument(0), usernameHashes.get(0)));
new AccountsManager.UsernameReservation(invocation.getArgument(0), usernameHashes.getFirst()));
});
final ReserveUsernameHashResponse expectedResponse = ReserveUsernameHashResponse.newBuilder()
@@ -684,12 +685,10 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void setRegistrationRecoveryPassword() {
final String phoneNumber =
PhoneNumberUtil.getInstance().format(PhoneNumberUtil.getInstance().getExampleNumber("US"),
PhoneNumberUtil.PhoneNumberFormat.E164);
final UUID phoneNumberIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getNumber()).thenReturn(phoneNumber);
when(account.getIdentifier(IdentityType.PNI)).thenReturn(phoneNumberIdentifier);
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
@@ -701,7 +700,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.setRegistrationRecoveryPassword(ByteString.copyFrom(registrationRecoveryPassword))
.build()));
verify(registrationRecoveryPasswordsManager).storeForCurrentNumber(phoneNumber, registrationRecoveryPassword);
verify(registrationRecoveryPasswordsManager).store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword);
}
@Test
@@ -0,0 +1,196 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.securevaluerecovery;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import java.security.cert.CertificateException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
class SecureValueRecovery3ClientTest {
private UUID accountUuid;
private ExternalServiceCredentialsGenerator credentialsGenerator;
private ExecutorService httpExecutor;
private ScheduledExecutorService retryExecutor;
private SecureValueRecovery3Client secureValueRecovery3Client;
@RegisterExtension
private static final WireMockExtension backend1WireMock = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.build();
@RegisterExtension
private static final WireMockExtension backend2WireMock = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.build();
@RegisterExtension
private static final WireMockExtension backend3WireMock = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.build();
@BeforeEach
void setUp() throws CertificateException {
accountUuid = UUID.randomUUID();
credentialsGenerator = mock(ExternalServiceCredentialsGenerator.class);
httpExecutor = Executors.newSingleThreadExecutor();
retryExecutor = Executors.newSingleThreadScheduledExecutor();
final SecureValueRecovery3Configuration config = new SecureValueRecovery3Configuration(
"http://localhost:" + backend1WireMock.getPort(),
"http://localhost:" + backend2WireMock.getPort(),
"http://localhost:" + backend3WireMock.getPort(),
randomSecretBytes(32),
randomSecretBytes(32),
// This is a randomly-generated, throwaway certificate that's not actually connected to anything
List.of("""
-----BEGIN CERTIFICATE-----
MIICZDCCAc2gAwIBAgIBADANBgkqhkiG9w0BAQ0FADBPMQswCQYDVQQGEwJ1czEL
MAkGA1UECAwCVVMxHjAcBgNVBAoMFVNpZ25hbCBNZXNzZW5nZXIsIExMQzETMBEG
A1UEAwwKc2lnbmFsLm9yZzAeFw0yMDEyMjMyMjQ3NTlaFw0zMDEyMjEyMjQ3NTla
ME8xCzAJBgNVBAYTAnVzMQswCQYDVQQIDAJVUzEeMBwGA1UECgwVU2lnbmFsIE1l
c3NlbmdlciwgTExDMRMwEQYDVQQDDApzaWduYWwub3JnMIGfMA0GCSqGSIb3DQEB
AQUAA4GNADCBiQKBgQCfSLcZNHYqbxSsgWp4JvbPRHjQTrlsrKrgD2q7f/OY6O3Y
/X0QNcNSOJpliN8rmzwslfsrXHO3q1diGRw4xHogUJZ/7NQrHiP/zhN0VTDh49pD
ZpjXVyUbayLS/6qM5arKxBspzEFBb5v8cF6bPr76SO/rpGXiI0j6yJKX6fRiKwID
AQABo1AwTjAdBgNVHQ4EFgQU6Jrs/Fmj0z4dA3wvdq/WqA4P49IwHwYDVR0jBBgw
FoAU6Jrs/Fmj0z4dA3wvdq/WqA4P49IwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
AQ0FAAOBgQB+5d5+NtzLILfrc9QmJdIO1YeDP64JmFwTER0kEUouRsb9UwknVWZa
y7MTM4NoBV1k0zb5LAk89SIDPr/maW5AsLtEomzjnEiomjoMBUdNe3YCgQReoLnr
R/QaUNbrCjTGYfBsjGbIzmkWPUyTec2ZdRyJ8JiVl386+6CZkxnndQ==
-----END CERTIFICATE-----
""", """
-----BEGIN CERTIFICATE-----
MIIEpDCCAowCCQC43PUTWSADVjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls
b2NhbGhvc3QwHhcNMjIxMDE3MjA0NTM0WhcNMjMxMDE3MjA0NTM0WjAUMRIwEAYD
VQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDV
x1cdEd2ffQTlTXWRiCHGcrlYf4RJnctt9sw/BuHWTLXBu5LhyJSGn5LRszO/NCXK
Z/cmGR7pLj366RtiwL+Qo3nhvDCK7T9xZeNIusM6XMcMK9D/DGCYPqtjQz8NXd9V
ajBBe6nwTDTa+oqX8Mt89foWNkg5Il/lY62u9Dr18LRZ2W9zzYi3Q9/K0CbIX6pM
yVlPIO5rITOR2IsbeyqsO9jufgX5lP4ZKLLBAP1b7usjC4YdvWacjQg/rK5aay1x
jC2HCDgo/4N30QVXzSA9nFfSe6AE/xkStK4819JqOkY5JsJCbef1P3hOOdSLEjbp
xq3MjOs6G6dOgteaAGs10vx7dHxDWETTIiD7BIZ9zRYgOF5bkCaIUO+JfySE1MHD
KBAFLoRuvmRev5Ln5R0MCHpUMSmMNgJqz+RWZV3g/gpYbuWiHgJOwL1393eK50Bg
W7SXQ8EjJj2yXZSH+1gPzN0DRoJZiaBoTPnCL2qUgvwFpW1PJsM5FDyUJFUoK5kK
HLBBSKAPt6ZlSrUe2nBgJv7EF1GK+fTU08LXgW33OpLceGPa0zTShkukQUMtUtZ8
GqhO12ohMzEupIu5Xurthq4VVUrzHUdj1ZZRMhAbfLU36sd03MMyL/xBqTN6dzCa
GDGIPGpYjAllZ5xMRt2kZdv+Kr6oo3u2nLUIsqI7KQIDAQABMA0GCSqGSIb3DQEB
CwUAA4ICAQCB5s43YF35ssf5YONW5iAaifGpi1o0866xfeOybtohFGvQ7V2W34i9
TYBCt8+0hgatMcvZ08f0vqig1i7nrvYcE1hnhL7JNkU8qm0s9ytHZt6j62nB0kd/
uqE2hOEQalTf/2TGPV0CCgiqLyd8lEUQvQeA38wktwUeZpVnErlzHeMR2CvV3K8R
u4vV6SnBcf+TAt56RKYZkPyvZj5llQPo14Glyoo8qZES7Ky1SHmM0GL+baPRBjRW
3KgSt98Wyu4yr9qu21JpnbAnLhBfzfSKjSeCRgFElUE1GIaFGRZ7ypA74dUKeLnb
/VUWrszmUhGaEjV9dpI6x6B/kSpQMtIQqBaKRY2ALUeEujS/rURi4iMDwSU+GkSH
cyEvZKS97OA/dWeXfLXdo4beDBRG93bI4rQnDg5+VdlBOkQSLueb8x6/VThMoC5d
vZiotFQHseljQAdTkNa6tBu6c4XDYPCKB3CfkMYOlCfTS7Acn5G6dxTPKBtLGBnL
nQfYyzuwYkN09+2PVzt6auBHr3To7uoclkxX+hxyvPIwIZ0N6b4tQR1FCAkvg29Q
WIOjZOKGW690ESKCKOnFjUHVO0HpuWnT81URTuY62FXsYdVc2wE4v0E04mEbqQ0P
lY6ZKNA81Lm3YADYtObmK1IUrOPo9BeIaPy0UM08SmN880Vunqa91Q==
-----END CERTIFICATE-----
"""),
null, null);
secureValueRecovery3Client = new SecureValueRecovery3Client(credentialsGenerator, httpExecutor, retryExecutor,
config);
}
@AfterEach
void tearDown() throws InterruptedException {
httpExecutor.shutdown();
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
retryExecutor.shutdown();
retryExecutor.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
void deleteStoredData() {
final String username = RandomStringUtils.secure().nextAlphabetic(16);
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
new ExternalServiceCredentials(username, password));
backend1WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
.withBasicAuth(username, password)
.willReturn(aResponse().withStatus(202)));
backend2WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
.withBasicAuth(username, password)
.willReturn(aResponse().withStatus(202)));
backend3WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
.withBasicAuth(username, password)
.willReturn(aResponse().withStatus(202)));
assertDoesNotThrow(() -> secureValueRecovery3Client.deleteBackups(accountUuid).join());
}
@ParameterizedTest
@MethodSource
void deleteStoredDataFailure(final int backend1Status, final int backend2Status, final int backend3Status) {
final String username = RandomStringUtils.secure().nextAlphabetic(16);
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
new ExternalServiceCredentials(username, password));
backend1WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
.withBasicAuth(username, password)
.willReturn(aResponse().withStatus(backend1Status)));
backend2WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
.withBasicAuth(username, password)
.willReturn(aResponse().withStatus(backend2Status)));
backend3WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
.withBasicAuth(username, password)
.willReturn(aResponse().withStatus(backend3Status)));
final CompletionException completionException = assertThrows(CompletionException.class,
() -> secureValueRecovery3Client.deleteBackups(accountUuid).join());
assertInstanceOf(SecureValueRecoveryException.class, completionException.getCause());
}
private static Stream<Arguments> deleteStoredDataFailure() {
return Stream.of(
Arguments.of(400, 202, 202),
Arguments.of(202, 400, 202),
Arguments.of(202, 202, 400)
);
}
}
@@ -49,6 +49,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
public class AccountCreationDeletionIntegrationTest {
@@ -102,6 +103,7 @@ public class AccountCreationDeletionIntegrationTest {
DynamoDbExtensionSchema.Tables.CLIENT_PUBLIC_KEYS.tableName());
final Accounts accounts = new Accounts(
CLOCK,
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.ACCOUNTS.tableName(),
@@ -124,8 +126,11 @@ public class AccountCreationDeletionIntegrationTest {
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final SecureValueRecovery3Client svr3Client = mock(SecureValueRecovery3Client.class);
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.PNI.tableName());
final MessagesManager messagesManager = mock(MessagesManager.class);
@@ -137,7 +142,7 @@ public class AccountCreationDeletionIntegrationTest {
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
mock(RegistrationRecoveryPasswordsManager.class);
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
when(registrationRecoveryPasswordsManager.remove(any()))
.thenReturn(CompletableFuture.completedFuture(null));
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
@@ -154,6 +159,7 @@ public class AccountCreationDeletionIntegrationTest {
profilesManager,
secureStorageClient,
svr2Client,
svr3Client,
disconnectionRequestManager,
registrationRecoveryPasswordsManager,
clientPublicKeysManager,
@@ -9,9 +9,9 @@ import static org.mockito.Mockito.verify;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClient;
import com.amazonaws.services.dynamodbv2.ReleaseLockOptions;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -27,11 +27,8 @@ class AccountLockManagerTest {
private AccountLockManager accountLockManager;
private static final String FIRST_NUMBER = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
private static final String SECOND_NUMBER = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("JP"), PhoneNumberUtil.PhoneNumberFormat.E164);
private static final UUID FIRST_PNI = UUID.randomUUID();
private static final UUID SECOND_PNI = UUID.randomUUID();
@BeforeEach
void setUp() {
@@ -51,7 +48,8 @@ class AccountLockManagerTest {
@Test
void withLock() throws InterruptedException {
accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), () -> {}, executor);
accountLockManager.withLock(List.of(FIRST_PNI, SECOND_PNI), () -> {
}, executor);
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
@@ -59,8 +57,8 @@ class AccountLockManagerTest {
@Test
void withLockTaskThrowsException() throws InterruptedException {
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), () -> {
throw new RuntimeException();
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(List.of(FIRST_PNI, SECOND_PNI), () -> {
throw new RuntimeException();
}, executor));
verify(lockClient, times(2)).acquireLock(any());
@@ -71,14 +69,16 @@ class AccountLockManagerTest {
void withLockEmptyList() {
final Runnable task = mock(Runnable.class);
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptyList(), () -> {}, executor));
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptyList(), () -> {
},
executor));
verify(task, never()).run();
}
@Test
void withLockAsync() throws InterruptedException {
accountLockManager.withLockAsync(List.of(FIRST_NUMBER, SECOND_NUMBER),
() -> CompletableFuture.completedFuture(null), executor).join();
accountLockManager.withLockAsync(
List.of(FIRST_PNI, SECOND_PNI), () -> CompletableFuture.completedFuture(null), executor).join();
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
@@ -87,8 +87,9 @@ class AccountLockManagerTest {
@Test
void withLockAsyncTaskThrowsException() throws InterruptedException {
assertThrows(RuntimeException.class,
() -> accountLockManager.withLockAsync(List.of(FIRST_NUMBER, SECOND_NUMBER),
() -> CompletableFuture.failedFuture(new RuntimeException()), executor).join());
() -> accountLockManager.withLockAsync(
List.of(FIRST_PNI, SECOND_PNI), () -> CompletableFuture.failedFuture(new RuntimeException()), executor)
.join());
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
@@ -99,8 +100,8 @@ class AccountLockManagerTest {
final Runnable task = mock(Runnable.class);
assertThrows(IllegalArgumentException.class,
() -> accountLockManager.withLockAsync(Collections.emptyList(),
() -> CompletableFuture.completedFuture(null), executor));
() -> accountLockManager.withLockAsync(Collections.emptyList(), () -> CompletableFuture.completedFuture(null),
executor));
verify(task, never()).run();
}
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
@@ -93,6 +94,7 @@ class AccountsManagerChangeNumberIntegrationTest {
DynamoDbExtensionSchema.Tables.CLIENT_PUBLIC_KEYS.tableName());
final Accounts accounts = new Accounts(
Clock.systemUTC(),
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
Tables.ACCOUNTS.tableName(),
@@ -116,10 +118,13 @@ class AccountsManagerChangeNumberIntegrationTest {
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final SecureValueRecovery3Client svr3Client = mock(SecureValueRecovery3Client.class);
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(), Tables.PNI.tableName());
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
final MessagesManager messagesManager = mock(MessagesManager.class);
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
@@ -130,7 +135,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
mock(RegistrationRecoveryPasswordsManager.class);
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
when(registrationRecoveryPasswordsManager.remove(any()))
.thenReturn(CompletableFuture.completedFuture(null));
accountsManager = new AccountsManager(
@@ -144,6 +149,7 @@ class AccountsManagerChangeNumberIntegrationTest {
profilesManager,
secureStorageClient,
svr2Client,
svr3Client,
disconnectionRequestManager,
registrationRecoveryPasswordsManager,
clientPublicKeysManager,
@@ -176,14 +182,13 @@ class AccountsManagerChangeNumberIntegrationTest {
assertTrue(accountsManager.getByE164(originalNumber).isEmpty());
assertTrue(accountsManager.getByE164(secondNumber).isPresent());
assertEquals(originalUuid, accountsManager.getByE164(secondNumber).map(Account::getUuid).orElseThrow());
assertNotEquals(originalPni, accountsManager.getByE164(secondNumber).map(Account::getPhoneNumberIdentifier).orElseThrow());
final Account updatedAccount = accountsManager.getByE164(secondNumber).orElseThrow();
assertEquals(originalUuid, updatedAccount.getUuid());
assertEquals(secondNumber, updatedAccount.getNumber());
assertNotEquals(originalPni, updatedAccount.getPhoneNumberIdentifier());
assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).map(Account::getNumber).orElseThrow());
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(updatedAccount.getPhoneNumberIdentifier()));
}
@Test
@@ -207,17 +212,19 @@ class AccountsManagerChangeNumberIntegrationTest {
final Map<Byte, Integer> registrationIds = Map.of(Device.PRIMARY_ID, rotatedPniRegistrationId);
final Account updatedAccount = accountsManager.changeNumber(account, secondNumber, pniIdentityKey, preKeys, null, registrationIds);
final UUID secondPni = updatedAccount.getPhoneNumberIdentifier();
assertTrue(accountsManager.getByE164(originalNumber).isEmpty());
assertTrue(accountsManager.getByE164(secondNumber).isPresent());
assertEquals(originalUuid, accountsManager.getByE164(secondNumber).map(Account::getUuid).orElseThrow());
assertNotEquals(originalPni, accountsManager.getByE164(secondNumber).map(Account::getPhoneNumberIdentifier).orElseThrow());
assertNotEquals(originalPni, secondPni);
assertEquals(secondPni, accountsManager.getByE164(secondNumber).map(Account::getPhoneNumberIdentifier).orElseThrow());
assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).map(Account::getNumber).orElseThrow());
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni));
assertEquals(pniIdentityKey, updatedAccount.getIdentityKey(IdentityType.PNI));
@@ -239,6 +246,7 @@ class AccountsManagerChangeNumberIntegrationTest {
final UUID originalPni = account.getPhoneNumberIdentifier();
account = accountsManager.changeNumber(account, secondNumber, null, null, null, null);
final UUID secondPni = account.getPhoneNumberIdentifier();
accountsManager.changeNumber(account, originalNumber, null, null, null, null);
assertTrue(accountsManager.getByE164(originalNumber).isPresent());
@@ -249,8 +257,8 @@ class AccountsManagerChangeNumberIntegrationTest {
assertEquals(originalNumber, accountsManager.getByAccountIdentifier(originalUuid).map(Account::getNumber).orElseThrow());
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni));
}
@Test
@@ -261,12 +269,14 @@ class AccountsManagerChangeNumberIntegrationTest {
final Account account = AccountsHelper.createAccount(accountsManager, originalNumber);
final UUID originalUuid = account.getUuid();
final UUID originalPni = account.getPhoneNumberIdentifier();
final Account existingAccount = AccountsHelper.createAccount(accountsManager, secondNumber);
final UUID existingAccountUuid = existingAccount.getUuid();
accountsManager.changeNumber(account, secondNumber, null, null, null, null);
final UUID secondPni = accountsManager.getByE164(secondNumber).get().getPhoneNumberIdentifier();
assertTrue(accountsManager.getByE164(originalNumber).isEmpty());
@@ -277,8 +287,8 @@ class AccountsManagerChangeNumberIntegrationTest {
verify(disconnectionRequestManager).requestDisconnection(existingAccountUuid);
assertEquals(Optional.of(existingAccountUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondNumber));
assertEquals(Optional.of(existingAccountUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni));
accountsManager.changeNumber(accountsManager.getByAccountIdentifier(originalUuid).orElseThrow(), originalNumber, null, null, null, null);
@@ -309,13 +319,13 @@ class AccountsManagerChangeNumberIntegrationTest {
assertEquals(existingAccountUuid, reRegisteredAccount.getUuid());
assertEquals(originalPni, reRegisteredAccount.getPhoneNumberIdentifier());
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni));
final Account changedNumberReRegisteredAccount = accountsManager.changeNumber(reRegisteredAccount, secondNumber, null, null, null, null);
assertEquals(Optional.of(originalUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondNumber));
assertEquals(Optional.of(originalUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalPni));
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondPni));
assertEquals(secondPni, changedNumberReRegisteredAccount.getPhoneNumberIdentifier());
}
}
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeast;
@@ -50,10 +51,10 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
import org.whispersystems.textsecuregcm.tests.util.JsonHelpers;
@@ -91,6 +92,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
accounts = new Accounts(
Clock.systemUTC(),
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
Tables.ACCOUNTS.tableName(),
@@ -111,9 +113,9 @@ class AccountsManagerConcurrentModificationIntegrationTest {
task.run();
return null;
}).when(accountLockManager).withLock(any(), any(), any());
}).when(accountLockManager).withLock(anyList(), any(), any());
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
when(accountLockManager.withLockAsync(anyList(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
taskSupplier.get().join();
@@ -122,7 +124,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString()))
.thenAnswer((Answer<UUID>) invocation -> UUID.randomUUID());
.thenAnswer((Answer<CompletableFuture<UUID>>) invocation -> CompletableFuture.completedFuture(UUID.randomUUID()));
accountsManager = new AccountsManager(
accounts,
@@ -135,6 +137,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
mock(ProfilesManager.class),
mock(SecureStorageClient.class),
mock(SecureValueRecovery2Client.class),
mock(SecureValueRecovery3Client.class),
mock(DisconnectionRequestManager.class),
mock(RegistrationRecoveryPasswordsManager.class),
mock(ClientPublicKeysManager.class),
@@ -12,14 +12,16 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
@@ -64,6 +66,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
mock(ProfilesManager.class),
mock(SecureStorageClient.class),
mock(SecureValueRecovery2Client.class),
mock(SecureValueRecovery3Client.class),
mock(DisconnectionRequestManager.class),
mock(RegistrationRecoveryPasswordsManager.class),
mock(ClientPublicKeysManager.class),
@@ -97,10 +100,10 @@ public class AccountsManagerDeviceTransferIntegrationTest {
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
final CompletableFuture<Optional<RemoteAttachment>> displacedFuture =
final CompletableFuture<Optional<TransferArchiveResult>> displacedFuture =
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5));
final CompletableFuture<Optional<RemoteAttachment>> activeFuture =
final CompletableFuture<Optional<TransferArchiveResult>> activeFuture =
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5));
assertEquals(Optional.empty(), displacedFuture.join());
@@ -132,6 +135,30 @@ public class AccountsManagerDeviceTransferIntegrationTest {
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
}
@Test
void waitForErrorTransferArchive() {
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = Device.PRIMARY_ID;
final long deviceCreated = System.currentTimeMillis();
final RemoteAttachmentError transferArchiveError =
new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
when(device.getCreated()).thenReturn(deviceCreated);
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
accountsManager
.recordTransferArchiveUpload(account, deviceId, Instant.ofEpochMilli(deviceCreated), transferArchiveError)
.join();
assertEquals(Optional.of(transferArchiveError),
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
}
@Test
void waitForTransferArchiveTimeout() {
final UUID accountIdentifier = UUID.randomUUID();
@@ -15,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -65,6 +66,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.stubbing.Answer;
@@ -85,6 +87,7 @@ 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.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
import org.whispersystems.textsecuregcm.storage.AccountsManager.UsernameReservation;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
@@ -128,6 +131,7 @@ class AccountsManagerTest {
private RedisAdvancedClusterAsyncCommands<String, String> asyncClusterCommands;
private AccountsManager accountsManager;
private SecureValueRecovery2Client svr2Client;
private SecureValueRecovery3Client svr3Client;
private DynamicConfiguration dynamicConfiguration;
private static final Answer<?> ACCOUNT_UPDATE_ANSWER = (answer) -> {
@@ -191,12 +195,15 @@ class AccountsManagerTest {
svr2Client = mock(SecureValueRecovery2Client.class);
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
svr3Client = mock(SecureValueRecovery3Client.class);
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
phoneNumberIdentifiersByE164 = new HashMap<>();
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<UUID>) invocation -> {
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<CompletableFuture<UUID>>) invocation -> {
final String number = invocation.getArgument(0, String.class);
return phoneNumberIdentifiersByE164.computeIfAbsent(number, n -> UUID.randomUUID());
return CompletableFuture.completedFuture(phoneNumberIdentifiersByE164.computeIfAbsent(number, n -> UUID.randomUUID()));
});
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
@@ -212,9 +219,9 @@ class AccountsManagerTest {
task.run();
return null;
}).when(accountLockManager).withLock(any(), any(), any());
}).when(accountLockManager).withLock(anyList(), any(), any());
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
when(accountLockManager.withLockAsync(anyList(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
return taskSupplier.get();
});
@@ -222,7 +229,7 @@ class AccountsManagerTest {
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
mock(RegistrationRecoveryPasswordsManager.class);
when(registrationRecoveryPasswordsManager.removeForNumber(anyString())).thenReturn(CompletableFuture.completedFuture(null));
when(registrationRecoveryPasswordsManager.remove(any())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.deleteSingleUsePreKeys(any())).thenReturn(CompletableFuture.completedFuture(null));
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
@@ -252,6 +259,7 @@ class AccountsManagerTest {
profilesManager,
storageClient,
svr2Client,
svr3Client,
disconnectionRequestManager,
registrationRecoveryPasswordsManager,
clientPublicKeysManager,
@@ -264,7 +272,7 @@ class AccountsManagerTest {
@ParameterizedTest
@MethodSource
void testDeleteWithSvrErrorStatusCodes(final String statusCode, final boolean expectError) throws InterruptedException {
void testDeleteWithSvr2ErrorStatusCodes(final String statusCode, final boolean expectError) throws InterruptedException {
when(svr2Client.deleteBackups(any())).thenReturn(
CompletableFuture.failedFuture(new SecureValueRecoveryException("Failed to delete backup", statusCode)));
when(dynamicConfiguration.getSvrStatusCodesToIgnoreForAccountDeletion()).thenReturn(List.of("500"));
@@ -280,13 +288,26 @@ class AccountsManagerTest {
}
}
private static Stream<Arguments> testDeleteWithSvrErrorStatusCodes() {
private static Stream<Arguments> testDeleteWithSvr2ErrorStatusCodes() {
return Stream.of(
Arguments.of("500", false),
Arguments.of("429", true)
);
}
@ParameterizedTest
@ValueSource(strings = {"500", "429"})
void testDeleteWithSvr3ErrorStatusCodes(final String statusCode) throws InterruptedException {
when(svr3Client.deleteBackups(any())).thenReturn(
CompletableFuture.failedFuture(new SecureValueRecoveryException("Failed to delete backup", statusCode)));
final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null);
final Account createdAccount = createAccount("+18005550123", attributes);
assertDoesNotThrow(() -> accountsManager.delete(createdAccount, AccountsManager.DeletionReason.USER_REQUEST).toCompletableFuture().join());
}
@Test
void testGetByServiceIdentifier() {
final UUID aci = UUID.randomUUID();
@@ -836,11 +857,17 @@ class AccountsManagerTest {
verifyNoInteractions(profilesManager);
}
@Test
void testReregisterAccount() throws InterruptedException, AccountAlreadyExistsException {
@ParameterizedTest
@CsvSource({
"+18005550123, +18005550123",
// the canonical form of numbers may change over time, so an existing account might have not-identical e164 that
// maps to the same PNI, and the number used by the caller must be present on the re-registered account
"+2290123456789, +22923456789"
})
void testReregisterAccount(final String e164, final String existingAccountE164)
throws InterruptedException, AccountAlreadyExistsException {
final UUID existingUuid = UUID.randomUUID();
final String e164 = "+18005550123";
final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null);
when(accounts.create(any(), any()))
@@ -850,7 +877,7 @@ class AccountsManagerTest {
final Account existingAccount = mock(Account.class);
when(existingAccount.getUuid()).thenReturn(existingUuid);
when(existingAccount.getIdentifier(IdentityType.ACI)).thenReturn(existingUuid);
when(existingAccount.getNumber()).thenReturn(e164);
when(existingAccount.getNumber()).thenReturn(existingAccountE164);
when(existingAccount.getPhoneNumberIdentifier()).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI));
when(existingAccount.getIdentifier(IdentityType.PNI)).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI));
when(existingAccount.getPrimaryDevice()).thenReturn(mock(Device.class));
@@ -863,6 +890,7 @@ class AccountsManagerTest {
final Account reregisteredAccount = createAccount(e164, attributes);
assertTrue(phoneNumberIdentifiersByE164.containsKey(e164));
assertEquals(e164, reregisteredAccount.getNumber());
verify(accounts)
.create(argThat(account -> e164.equals(account.getNumber()) && existingUuid.equals(account.getUuid())), any());
@@ -887,7 +915,7 @@ class AccountsManagerTest {
void testCreateAccountRecentlyDeleted() throws InterruptedException, AccountAlreadyExistsException {
final UUID recentlyDeletedUuid = UUID.randomUUID();
when(accounts.findRecentlyDeletedAccountIdentifier(anyString())).thenReturn(Optional.of(recentlyDeletedUuid));
when(accounts.findRecentlyDeletedAccountIdentifier(any())).thenReturn(Optional.of(recentlyDeletedUuid));
when(accounts.create(any(), any())).thenReturn(true);
final String e164 = "+18005550123";
@@ -1053,17 +1081,35 @@ class AccountsManagerTest {
final String number = "+14152222222";
Account account = AccountsHelper.generateTestAccount(number, UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
phoneNumberIdentifiersByE164.put(number, account.getPhoneNumberIdentifier());
account = accountsManager.changeNumber(account, number, null, null, null, null);
assertEquals(number, account.getNumber());
verify(keysManager, never()).deleteSingleUsePreKeys(any());
}
@Test
void testChangePhoneNumberDifferentNumberSamePni() throws InterruptedException, MismatchedDevicesException {
final String originalNumber = "+22923456789";
// the canonical form of numbers may change over time, so we use PNIs as stable identifiers
final String newNumber = "+2290123456789";
Account account = AccountsHelper.generateTestAccount(originalNumber, UUID.randomUUID(), UUID.randomUUID(),
new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
phoneNumberIdentifiersByE164.put(originalNumber, account.getPhoneNumberIdentifier());
phoneNumberIdentifiersByE164.put(newNumber, account.getPhoneNumberIdentifier());
account = accountsManager.changeNumber(account, newNumber, null, null, null, null);
assertEquals(originalNumber, account.getNumber());
verify(keysManager, never()).deleteSingleUsePreKeys(any());
}
@Test
void testChangePhoneNumberSameNumberWithPniData() {
final String number = "+14152222222";
Account account = AccountsHelper.generateTestAccount(number, UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
phoneNumberIdentifiersByE164.put(number, account.getPhoneNumberIdentifier());
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
assertThrows(IllegalArgumentException.class,
() -> accountsManager.changeNumber(
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -40,6 +41,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.AttributeValues;
@@ -101,6 +103,7 @@ class AccountsManagerUsernameIntegrationTest {
);
accounts = Mockito.spy(new Accounts(
Clock.systemUTC(),
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
Tables.ACCOUNTS.tableName(),
@@ -117,9 +120,9 @@ class AccountsManagerUsernameIntegrationTest {
task.run();
return null;
}).when(accountLockManager).withLock(any(), any(), any());
}).when(accountLockManager).withLock(anyList(), any(), any());
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
when(accountLockManager.withLockAsync(anyList(), any(), any())).thenAnswer(invocation -> {
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
taskSupplier.get().join();
@@ -127,7 +130,7 @@ class AccountsManagerUsernameIntegrationTest {
});
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(), Tables.PNI.tableName());
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
final MessagesManager messageManager = mock(MessagesManager.class);
final ProfilesManager profileManager = mock(ProfilesManager.class);
@@ -148,6 +151,7 @@ class AccountsManagerUsernameIntegrationTest {
profileManager,
mock(SecureStorageClient.class),
mock(SecureValueRecovery2Client.class),
mock(SecureValueRecovery3Client.class),
disconnectionRequestManager,
mock(RegistrationRecoveryPasswordsManager.class),
mock(ClientPublicKeysManager.class),
@@ -210,7 +210,7 @@ class AccountsTest {
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
accounts.delete(originalUuid, Collections.emptyList()).join();
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getNumber())).hasValue(originalUuid);
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier())).hasValue(originalUuid);
freshUser = createAccount(account);
assertThat(freshUser).isTrue();
@@ -219,7 +219,7 @@ class AccountsTest {
assertPhoneNumberConstraintExists("+14151112222", account.getUuid());
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getNumber())).isEmpty();
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier())).isEmpty();
}
@Test
@@ -235,6 +235,45 @@ class AccountsTest {
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
}
@Test
void testStoreAciCollisionFails() {
Device device = generateDevice(DEVICE_ID_1);
Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device));
boolean freshUser = createAccount(account);
assertThat(freshUser).isTrue();
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
assertPhoneNumberConstraintExists("+14151112222", account.getUuid());
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
account.setNumber("+14153334444", UUID.randomUUID());
assertThrows(IllegalArgumentException.class, () -> createAccount(account),
"Reusing ACI with different PNI should fail");
}
@Test
void testStorePniCollisionFails() {
Device device1 = generateDevice(DEVICE_ID_1);
Account account1 = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device1));
boolean freshUser = createAccount(account1);
assertThat(freshUser).isTrue();
verifyStoredState("+14151112222", account1.getUuid(), account1.getPhoneNumberIdentifier(), null, account1, true);
assertPhoneNumberConstraintExists("+14151112222", account1.getUuid());
assertPhoneNumberIdentifierConstraintExists(account1.getPhoneNumberIdentifier(), account1.getUuid());
Device device2 = generateDevice(DEVICE_ID_1);
Account account2 = generateAccount("+14151112222", UUID.randomUUID(), account1.getPhoneNumberIdentifier(),
List.of(device2));
assertThrows(AccountAlreadyExistsException.class, () -> accounts.create(account2, Collections.emptyList()),
"New ACI with same PNI should fail");
}
@Test
void testRetrieve() {
final List<Device> devicesFirst = List.of(generateDevice(DEVICE_ID_1), generateDevice(DEVICE_ID_2));
@@ -560,7 +599,9 @@ class AccountsTest {
void testUpdateWithMockTransactionConflictException(boolean wrapException) {
final DynamoDbAsyncClient dynamoDbAsyncClient = mock(DynamoDbAsyncClient.class);
accounts = new Accounts(mock(DynamoDbClient.class),
accounts = new Accounts(
clock,
mock(DynamoDbClient.class),
dynamoDbAsyncClient,
Tables.ACCOUNTS.tableName(),
Tables.NUMBERS.tableName(),
@@ -649,7 +690,9 @@ class AccountsTest {
void testUpdateTransactionallyWithMockTransactionConflictException() {
final DynamoDbAsyncClient dynamoDbAsyncClient = mock(DynamoDbAsyncClient.class);
accounts = new Accounts(mock(DynamoDbClient.class),
accounts = new Accounts(
clock,
mock(DynamoDbClient.class),
dynamoDbAsyncClient,
Tables.ACCOUNTS.tableName(),
Tables.NUMBERS.tableName(),
@@ -702,7 +745,7 @@ class AccountsTest {
createAccount(deletedAccount);
createAccount(retainedAccount);
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getNumber())).isEmpty();
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier())).isEmpty();
assertPhoneNumberConstraintExists("+14151112222", deletedAccount.getUuid());
assertPhoneNumberIdentifierConstraintExists(deletedAccount.getPhoneNumberIdentifier(), deletedAccount.getUuid());
@@ -715,7 +758,7 @@ class AccountsTest {
accounts.delete(deletedAccount.getUuid(), Collections.emptyList()).join();
assertThat(accounts.getByAccountIdentifier(deletedAccount.getUuid())).isNotPresent();
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getNumber())).hasValue(deletedAccount.getUuid());
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier())).hasValue(deletedAccount.getUuid());
assertPhoneNumberConstraintDoesNotExist(deletedAccount.getNumber());
assertPhoneNumberIdentifierConstraintDoesNotExist(deletedAccount.getPhoneNumberIdentifier());
@@ -725,7 +768,7 @@ class AccountsTest {
{
final Account recreatedAccount = generateAccount(deletedAccount.getNumber(), UUID.randomUUID(),
UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
deletedAccount.getPhoneNumberIdentifier(), List.of(generateDevice(DEVICE_ID_1)));
final boolean freshUser = createAccount(recreatedAccount);
@@ -853,7 +896,7 @@ class AccountsTest {
assertThat(accounts.getByPhoneNumberIdentifier(targetPni)).isPresent();
}
assertThat(accounts.findRecentlyDeletedAccountIdentifier(originalNumber)).isEqualTo(maybeDisplacedAccountIdentifier);
assertThat(accounts.findRecentlyDeletedAccountIdentifier(originalPni)).isEqualTo(maybeDisplacedAccountIdentifier);
}
private static Stream<Arguments> testChangeNumber() {
@@ -1041,7 +1084,9 @@ class AccountsTest {
final Class<Exception> expectedException) {
final DynamoDbAsyncClient dbAsyncClient = mock(DynamoDbAsyncClient.class);
accounts = new Accounts(mock(DynamoDbClient.class),
accounts = new Accounts(
clock,
mock(DynamoDbClient.class),
dbAsyncClient,
Tables.ACCOUNTS.tableName(),
Tables.NUMBERS.tableName(),
@@ -1084,7 +1129,9 @@ class AccountsTest {
final Class<Exception> expectedException) {
final DynamoDbAsyncClient dbAsyncClient = mock(DynamoDbAsyncClient.class);
accounts = new Accounts(mock(DynamoDbClient.class),
accounts = new Accounts(
clock,
mock(DynamoDbClient.class),
dbAsyncClient,
Tables.ACCOUNTS.tableName(),
Tables.NUMBERS.tableName(),
@@ -1185,7 +1232,9 @@ class AccountsTest {
final Optional<String> accountsCancellationString) {
final DynamoDbAsyncClient dbAsyncClient = mock(DynamoDbAsyncClient.class);
accounts = new Accounts(mock(DynamoDbClient.class),
accounts = new Accounts(
clock,
mock(DynamoDbClient.class),
dbAsyncClient,
Tables.ACCOUNTS.tableName(),
Tables.NUMBERS.tableName(),
@@ -1658,8 +1707,6 @@ class AccountsTest {
assertInstanceOf(DeviceIdDeserializer.DeviceIdDeserializationException.class, cause);
}
private static Device generateDevice(byte id) {
return DevicesHelper.createDevice(id);
}
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.Pair;
@@ -101,6 +102,7 @@ public class AddRemoveDeviceIntegrationTest {
DynamoDbExtensionSchema.Tables.CLIENT_PUBLIC_KEYS.tableName());
final Accounts accounts = new Accounts(
clock,
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.ACCOUNTS.tableName(),
@@ -124,8 +126,11 @@ public class AddRemoveDeviceIntegrationTest {
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final SecureValueRecovery3Client svr3Client = mock(SecureValueRecovery3Client.class);
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.PNI.tableName());
messagesManager = mock(MessagesManager.class);
@@ -137,7 +142,7 @@ public class AddRemoveDeviceIntegrationTest {
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
mock(RegistrationRecoveryPasswordsManager.class);
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
when(registrationRecoveryPasswordsManager.remove(any()))
.thenReturn(CompletableFuture.completedFuture(null));
PUBSUB_SERVER_EXTENSION.getRedisClient().useConnection(connection -> {
@@ -156,6 +161,7 @@ public class AddRemoveDeviceIntegrationTest {
profilesManager,
secureStorageClient,
svr2Client,
svr3Client,
mock(DisconnectionRequestManager.class),
mock(RegistrationRecoveryPasswordsManager.class),
clientPublicKeysManager,
@@ -10,6 +10,7 @@ import java.util.List;
import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
@@ -75,11 +76,11 @@ public final class DynamoDbExtensionSchema {
List.of()),
DELETED_ACCOUNTS("deleted_accounts_test",
Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_E164,
Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_PNI,
null,
List.of(
AttributeDefinition.builder()
.attributeName(Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_E164)
.attributeName(Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_PNI)
.attributeType(ScalarAttributeType.S).build(),
AttributeDefinition.builder()
.attributeName(Accounts.DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID)
@@ -87,7 +88,7 @@ public final class DynamoDbExtensionSchema {
.build()),
List.of(
GlobalSecondaryIndex.builder()
.indexName(Accounts.DELETED_ACCOUNTS_UUID_TO_E164_INDEX_NAME)
.indexName(Accounts.DELETED_ACCOUNTS_UUID_TO_PNI_INDEX_NAME)
.keySchema(
KeySchemaElement.builder().attributeName(Accounts.DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID).keyType(KeyType.HASH).build()
)
@@ -98,10 +99,10 @@ public final class DynamoDbExtensionSchema {
),
DELETED_ACCOUNTS_LOCK("deleted_accounts_lock_test",
AccountLockManager.KEY_ACCOUNT_E164,
AccountLockManager.KEY_ACCOUNT_PNI,
null,
List.of(AttributeDefinition.builder()
.attributeName(AccountLockManager.KEY_ACCOUNT_E164)
.attributeName(AccountLockManager.KEY_ACCOUNT_PNI)
.attributeType(ScalarAttributeType.S).build()),
List.of(), List.of()),
@@ -288,10 +289,10 @@ public final class DynamoDbExtensionSchema {
List.of(), List.of()),
REGISTRATION_RECOVERY_PASSWORDS("registration_recovery_passwords_test",
RegistrationRecoveryPasswords.KEY_E164,
RegistrationRecoveryPasswords.KEY_PNI,
null,
List.of(AttributeDefinition.builder()
.attributeName(RegistrationRecoveryPasswords.KEY_E164)
.attributeName(RegistrationRecoveryPasswords.KEY_PNI)
.attributeType(ScalarAttributeType.S)
.build()),
List.of(), List.of()),
@@ -398,6 +399,28 @@ public final class DynamoDbExtensionSchema {
.attributeName(VerificationSessions.KEY_KEY)
.attributeType(ScalarAttributeType.S)
.build()),
List.of(), List.of()),
APPLE_DEVICE_CHECKS("apple_device_check",
AppleDeviceChecks.KEY_ACCOUNT_UUID,
AppleDeviceChecks.KEY_PUBLIC_KEY_ID,
List.of(AttributeDefinition.builder()
.attributeName(AppleDeviceChecks.KEY_ACCOUNT_UUID)
.attributeType(ScalarAttributeType.B)
.build(),
AttributeDefinition.builder()
.attributeName(AppleDeviceChecks.KEY_PUBLIC_KEY_ID)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(), List.of()),
APPLE_DEVICE_CHECKS_KEY_CONSTRAINT("apple_device_check_key_constraint",
AppleDeviceChecks.KEY_PUBLIC_KEY,
null,
List.of(AttributeDefinition.builder()
.attributeName(AppleDeviceChecks.KEY_PUBLIC_KEY)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(), List.of());
private final String tableName;
@@ -12,15 +12,28 @@ import static org.mockito.Mockito.when;
import jakarta.ws.rs.ClientErrorException;
import java.time.Duration;
import java.time.Instant;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
class IssuedReceiptsManagerTest {
@@ -29,28 +42,39 @@ class IssuedReceiptsManagerTest {
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.ISSUED_RECEIPTS);
ReceiptCredentialRequest receiptCredentialRequest;
IssuedReceiptsManager issuedReceiptsManager;
private static EnumMap<PaymentProvider, Integer> MAX_TAGS_MAP = new EnumMap<>(Map.of(
PaymentProvider.STRIPE, 1,
PaymentProvider.BRAINTREE, 2,
PaymentProvider.GOOGLE_PLAY_BILLING, 3,
PaymentProvider.APPLE_APP_STORE, 4));
private IssuedReceiptsManager issuedReceiptsManager;
@BeforeEach
void beforeEach() {
receiptCredentialRequest = mock(ReceiptCredentialRequest.class);
issuedReceiptsManager = new IssuedReceiptsManager(
Tables.ISSUED_RECEIPTS.tableName(),
Duration.ofDays(90),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
TestRandomUtil.nextBytes(16));
TestRandomUtil.nextBytes(16),
MAX_TAGS_MAP);
}
@Test
void testRecordIssuance() {
Instant now = Instant.ofEpochSecond(NOW_EPOCH_SECONDS);
byte[] request1 = TestRandomUtil.nextBytes(20);
when(receiptCredentialRequest.serialize()).thenReturn(request1);
final ReceiptCredentialRequest receiptCredentialRequest = randomReceiptCredentialRequest();
CompletableFuture<Void> future = issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE,
receiptCredentialRequest, now);
assertThat(future).succeedsWithin(Duration.ofSeconds(3));
final Map<String, AttributeValue> item = getItem(PaymentProvider.STRIPE, "item-1").item();
final Set<byte[]> tagSet = item.get(IssuedReceiptsManager.KEY_ISSUED_RECEIPT_TAG_SET).bs()
.stream()
.map(SdkBytes::asByteArray)
.collect(Collectors.toSet());
assertThat(tagSet).containsExactly(item.get(IssuedReceiptsManager.KEY_ISSUED_RECEIPT_TAG).b().asByteArray());
// same request should succeed
future = issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE, receiptCredentialRequest,
now);
@@ -74,4 +98,59 @@ class IssuedReceiptsManagerTest {
now);
assertThat(future).succeedsWithin(Duration.ofSeconds(3));
}
@ParameterizedTest
@EnumSource(PaymentProvider.class)
void testIssueMax(PaymentProvider processor) {
final Instant now = Instant.ofEpochSecond(NOW_EPOCH_SECONDS);
final int maxTags = MAX_TAGS_MAP.get(processor);
final List<ReceiptCredentialRequest> requests = IntStream.range(0, maxTags)
.mapToObj(i -> randomReceiptCredentialRequest())
.toList();
for (int i = 0; i < maxTags; i++) {
// Should be allowed to insert up to maxTags
assertThat(issuedReceiptsManager.recordIssuance("item-1", processor, requests.get(i), now))
.succeedsWithin(Duration.ofSeconds(3));
for (int j = 0; j < i; j++) {
// Also should be allowed to repeat any previous tag
assertThat(issuedReceiptsManager.recordIssuance("item-1", processor, requests.get(j), now))
.succeedsWithin(Duration.ofSeconds(3));
}
}
assertThat(getItem(processor, "item-1").item().get(IssuedReceiptsManager.KEY_ISSUED_RECEIPT_TAG_SET).bs()
.stream()
.map(SdkBytes::asByteArray)
.collect(Collectors.toSet()))
.containsExactlyInAnyOrder(requests.stream()
.map(issuedReceiptsManager::generateIssuedReceiptTag)
.toArray(byte[][]::new));
// Should not be allowed to insert past maxTags
assertThat(issuedReceiptsManager.recordIssuance("item-1", processor, randomReceiptCredentialRequest(), now))
.failsWithin(Duration.ofSeconds(3))
.withThrowableOfType(Throwable.class)
.havingCause()
.isExactlyInstanceOf(ClientErrorException.class)
.has(new Condition<>(
e -> e instanceof ClientErrorException && ((ClientErrorException) e).getResponse().getStatus() == 409,
"status 409"));
}
private GetItemResponse getItem(final PaymentProvider processor, final String itemId) {
final DynamoDbClient client = DYNAMO_DB_EXTENSION.getDynamoDbClient();
return client.getItem(GetItemRequest.builder()
.tableName(Tables.ISSUED_RECEIPTS.tableName())
.key(Map.of(IssuedReceiptsManager.KEY_PROCESSOR_ITEM_ID, IssuedReceiptsManager.dynamoDbKey(processor, itemId)))
.build());
}
private static ReceiptCredentialRequest randomReceiptCredentialRequest() {
final ReceiptCredentialRequest request = mock(ReceiptCredentialRequest.class);
final byte[] bytes = TestRandomUtil.nextBytes(20);
when(request.serialize()).thenReturn(bytes);
return request;
}
}
@@ -81,7 +81,7 @@ class MessagePersisterIntegrationTest {
final AccountsManager accountsManager = mock(AccountsManager.class);
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
messageDeletionExecutorService);
@@ -99,7 +99,7 @@ class MessagePersisterTest {
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
dynamicConfigurationManager, PERSIST_DELAY, 1);
@@ -64,12 +64,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.ServiceId;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
@@ -98,26 +94,17 @@ class MessagesCacheTest {
private Scheduler messageDeliveryScheduler;
private MessagesCache messagesCache;
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private DynamicConfiguration dynamicConfiguration;
private static final UUID DESTINATION_UUID = UUID.randomUUID();
private static final byte DESTINATION_DEVICE_ID = 7;
@BeforeEach
void setUp() throws Exception {
dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(
new DynamicMessagesConfiguration(true));
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
sharedExecutorService = Executors.newSingleThreadExecutor();
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
}
@AfterEach
@@ -321,7 +308,7 @@ class MessagesCacheTest {
}
final MessagesCache messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, cacheClock, dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, cacheClock);
final List<MessageProtos.Envelope> actualMessages = Flux.from(
messagesCache.get(DESTINATION_UUID, DESTINATION_DEVICE_ID))
@@ -429,12 +416,9 @@ class MessagesCacheTest {
assertEquals(DESTINATION_DEVICE_ID, MessagesCache.getDeviceIdFromQueueName(queues.getFirst()));
}
@CartesianTest
void testMultiRecipientMessage(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
when(dynamicConfiguration.getMessagesConfiguration())
.thenReturn(new DynamicMessagesConfiguration(useSharedMrmData));
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testMultiRecipientMessage(final boolean sharedMrmKeyPresent) {
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = 1;
@@ -453,10 +437,8 @@ class MessagesCacheTest {
.toBuilder()
// clear some things added by the helper
.clearServerGuid()
// mrm views phase 2: messages have content
.setContent(
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.clearContent()
.build();
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
@@ -464,7 +446,7 @@ class MessagesCacheTest {
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
if (useSharedMrmData && !sharedMrmKeyPresent) {
if (!sharedMrmKeyPresent) {
assertTrue(messages.isEmpty());
} else {
@@ -495,65 +477,7 @@ class MessagesCacheTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testMultiRecipientMessagePhase2MissingContentSafeguard(final boolean useSharedMrmData) {
when(dynamicConfiguration.getMessagesConfiguration())
.thenReturn(new DynamicMessagesConfiguration(useSharedMrmData));
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = 1;
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
final byte[] sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
final UUID guid = UUID.randomUUID();
final MessageProtos.Envelope message = generateRandomMessage(guid, destinationServiceId, true)
.toBuilder()
// clear some things added by the helper
.clearServerGuid()
// mrm views phase 2: there is a safeguard against missing content, even if the dynamic configuration
// is to not fetch or use shared MRM data
.clearContent()
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.build();
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
assertEquals(1, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
assertEquals(1, messages.size());
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
assertFalse(messages.getFirst().hasSharedMrmKey());
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
.get(destinationServiceId.toLibsignal());
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid)
.join();
assertTrue(removedMessage.isPresent());
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
assertTrue(get(destinationServiceId.uuid(), deviceId, 1).isEmpty());
// updating the shared MRM data is purely async, so we just wait for it
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
boolean exists;
do {
exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster()
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey));
} while (exists);
}, "Shared MRM data should be deleted asynchronously");
}
@CartesianTest
void testGetMessagesToPersist(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
when(dynamicConfiguration.getMessagesConfiguration())
.thenReturn(new DynamicMessagesConfiguration(useSharedMrmData));
void testGetMessagesToPersist(final boolean sharedMrmKeyPresent) {
final UUID destinationUuid = UUID.randomUUID();
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(destinationUuid);
@@ -578,24 +502,22 @@ class MessagesCacheTest {
final MessageProtos.Envelope mrmMessage = generateRandomMessage(mrmMessageGuid, destinationServiceId, true)
.toBuilder()
// clear some things added by the helper
.clearServerGuid()
// mrm views phase 2: messages have content
.setContent(
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(new ServiceId.Aci(destinationUuid)))))
.clearContent()
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
.build();
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage);
final List<MessageProtos.Envelope> messages = messagesCache.getMessagesToPersist(destinationUuid, deviceId, 100);
if (useSharedMrmData && !sharedMrmKeyPresent) {
if (!sharedMrmKeyPresent) {
assertEquals(1, messages.size());
} else {
assertEquals(2, messages.size());
assertEquals(mrmMessage.toBuilder().
clearSharedMrmKey().
setServerGuid(mrmMessageGuid.toString())
assertEquals(mrmMessage.toBuilder()
.clearSharedMrmKey()
.setContent(ByteString.copyFrom(
mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
.build(),
messages.getLast());
}
@@ -636,7 +558,7 @@ class MessagesCacheTest {
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
messagesCache = new MessagesCache(mockCluster, messageDeliveryScheduler,
Executors.newSingleThreadExecutor(), Clock.systemUTC(), mock(DynamicConfigurationManager.class));
Executors.newSingleThreadExecutor(), Clock.systemUTC());
}
@AfterEach
@@ -822,8 +744,7 @@ class MessagesCacheTest {
}
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid,
final ServiceIdentifier destinationServiceId, final boolean sealedSender,
final long timestamp) {
final ServiceIdentifier destinationServiceId, final boolean sealedSender, final long timestamp) {
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
.setClientTimestamp(timestamp)
.setServerTimestamp(timestamp)
@@ -6,15 +6,24 @@
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Optional;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
class PhoneNumberIdentifiersTest {
@@ -25,7 +34,7 @@ class PhoneNumberIdentifiersTest {
@BeforeEach
void setUp() {
phoneNumberIdentifiers = new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
phoneNumberIdentifiers = new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
Tables.PNI.tableName());
}
@@ -34,28 +43,161 @@ class PhoneNumberIdentifiersTest {
final String number = "+18005551234";
final String differentNumber = "+18005556789";
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
assertEquals(firstPni, secondPni);
assertNotEquals(firstPni, phoneNumberIdentifiers.getPhoneNumberIdentifier(differentNumber));
assertNotEquals(firstPni, phoneNumberIdentifiers.getPhoneNumberIdentifier(differentNumber).join());
}
@Test
void generatePhoneNumberIdentifierIfNotExists() {
final String number = "+18005551234";
void generatePhoneNumberIdentifier() {
final List<String> numbers = List.of("+18005551234", "+18005556789");
// Should set both PNIs to a new random PNI
final UUID pni = phoneNumberIdentifiers.setPniIfRequired(numbers.getFirst(), numbers, Collections.emptyMap()).join();
assertEquals(phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number),
phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number));
assertEquals(pni, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getFirst()).join());
assertEquals(pni, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getLast()).join());
}
@Test
void generatePhoneNumberIdentifierOneFormExists() {
final String firstNumber = "+18005551234";
final String secondNumber = "+18005556789";
final String thirdNumber = "+1800555456";
final List<String> allNumbers = List.of(firstNumber, secondNumber, thirdNumber);
// Set one member of the "same" numbers to a new PNI
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(secondNumber).join();
final Map<String, UUID> existingAssociations = phoneNumberIdentifiers.fetchPhoneNumbers(allNumbers).join();
assertEquals(Map.of(secondNumber, pni), existingAssociations);
assertEquals(pni, phoneNumberIdentifiers.setPniIfRequired(firstNumber, allNumbers, existingAssociations).join());
for (String number : allNumbers) {
assertEquals(pni, phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join());
}
}
@Test
void getPhoneNumberIdentifierExistingMapping() {
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
final UUID oldFormatPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(oldFormatBeninE164).join();
final UUID newFormatPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(newFormatBeninE164).join();
assertEquals(oldFormatPni, newFormatPni);
}
@Test
void conflictingExistingPnis() {
final String firstNumber = "+18005551234";
final String secondNumber = "+18005556789";
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(firstNumber).join();
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(secondNumber).join();
assertNotEquals(firstPni, secondPni);
assertEquals(
firstPni,
phoneNumberIdentifiers.setPniIfRequired(
firstNumber, List.of(firstNumber, secondNumber),
phoneNumberIdentifiers.fetchPhoneNumbers(List.of(firstNumber, secondNumber)).join()).join());
assertEquals(
secondPni,
phoneNumberIdentifiers.setPniIfRequired(
secondNumber, List.of(secondNumber, firstNumber),
phoneNumberIdentifiers.fetchPhoneNumbers(List.of(firstNumber, secondNumber)).join()).join());
}
@Test
void conflictOnOriginalNumber() {
final List<String> numbers = List.of("+18005551234", "+18005556789");
// Stale view of database where both numbers have no PNI
final Map<String, UUID> existingAssociations = Collections.emptyMap();
// Both numbers have different PNIs
final UUID pni1 = phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getFirst()).join();
final UUID pni2 = phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getLast()).join();
assertNotEquals(pni1, pni2);
// Should conflict and find that we now have a PNI
assertEquals(pni1, phoneNumberIdentifiers.setPniIfRequired(numbers.getFirst(), numbers, existingAssociations).join());
}
@Test
void conflictOnAlternateNumber() {
final List<String> numbers = List.of("+18005551234", "+18005556789");
// Stale view of database where both numbers have no PNI
final Map<String, UUID> existingAssociations = Collections.emptyMap();
// the alternate number has a PNI added
phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getLast()).join();
// Should conflict and fail
CompletableFutureTestUtil.assertFailsWithCause(
TransactionCanceledException.class,
phoneNumberIdentifiers.setPniIfRequired(numbers.getFirst(), numbers, existingAssociations));
}
@Test
void multipleAssociations() {
final List<String> numbers = List.of("+18005550000", "+18005551111", "+18005552222", "+18005553333", "+1800555444");
// Set pni1={number1, number2}, pni2={number3}, number0 and number 4 unset
final UUID pni1 = phoneNumberIdentifiers.setPniIfRequired(numbers.get(1), numbers.subList(1, 3),
Collections.emptyMap()).join();
final UUID pni2 = phoneNumberIdentifiers.setPniIfRequired(numbers.get(3), List.of(numbers.get(3)),
Collections.emptyMap()).join();
final Map<String, UUID> existingAssociations = phoneNumberIdentifiers.fetchPhoneNumbers(numbers).join();
assertEquals(existingAssociations, Map.of(numbers.get(1), pni1, numbers.get(2), pni1, numbers.get(3), pni2));
// The unmapped phone numbers should map to the arbitrarily selected PNI (which is selected based on the order
// of the numbers)
assertEquals(pni1, phoneNumberIdentifiers.setPniIfRequired(numbers.get(0), numbers, existingAssociations).join());
assertEquals(pni1, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.get(0)).join());
assertEquals(pni1, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.get(4)).join());
}
private static class FailN implements Supplier<CompletableFuture<Integer>> {
final AtomicInteger numFails;
FailN(final int numFails) {
this.numFails = new AtomicInteger(numFails);
}
@Override
public CompletableFuture<Integer> get() {
if (numFails.getAndDecrement() == 0) {
return CompletableFuture.completedFuture(7);
}
return CompletableFuture.failedFuture(new IOException("test"));
}
}
@Test
void testRetry() {
assertEquals(7, PhoneNumberIdentifiers.retry(10, IOException.class, new FailN(9)).join());
CompletableFutureTestUtil.assertFailsWithCause(
IOException.class,
PhoneNumberIdentifiers.retry(10, IOException.class, new FailN(10)));
CompletableFutureTestUtil.assertFailsWithCause(
IOException.class,
PhoneNumberIdentifiers.retry(10, RuntimeException.class, new FailN(1)));
}
@Test
void getPhoneNumber() {
final String number = "+18005551234";
assertFalse(phoneNumberIdentifiers.getPhoneNumber(UUID.randomUUID()).isPresent());
assertTrue(phoneNumberIdentifiers.getPhoneNumber(UUID.randomUUID()).join().isEmpty());
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
assertEquals(Optional.of(number), phoneNumberIdentifiers.getPhoneNumber(pni));
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
assertEquals(List.of(number), phoneNumberIdentifiers.getPhoneNumber(pni).join());
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -14,14 +15,15 @@ import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.MutableClock;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@@ -30,83 +32,82 @@ import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
public class RegistrationRecoveryTest {
private static final MutableClock CLOCK = MockUtils.mutableClock(0);
private static final Duration EXPIRATION = Duration.ofSeconds(1000);
private static final String NUMBER = "+18005555555";
private static final UUID PNI = UUID.randomUUID();
private static final SaltedTokenHash ORIGINAL_HASH = SaltedTokenHash.generateFor("pass1");
private static final SaltedTokenHash ANOTHER_HASH = SaltedTokenHash.generateFor("pass2");
@RegisterExtension
private static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
Tables.REGISTRATION_RECOVERY_PASSWORDS);
private static final DynamoDbExtension DYNAMO_DB_EXTENSION =
new DynamoDbExtension(Tables.REGISTRATION_RECOVERY_PASSWORDS);
private RegistrationRecoveryPasswords store;
private RegistrationRecoveryPasswords registrationRecoveryPasswords;
private RegistrationRecoveryPasswordsManager manager;
@BeforeEach
public void before() throws Exception {
CLOCK.setTimeMillis(Clock.systemUTC().millis());
store = new RegistrationRecoveryPasswords(
registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName(),
EXPIRATION,
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
CLOCK
);
manager = new RegistrationRecoveryPasswordsManager(store);
manager = new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
}
@Test
public void testLookupAfterWrite() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
final long initialExp = fetchTimestamp(NUMBER);
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
final long initialExp = fetchTimestamp(PNI);
final long expectedExpiration = CLOCK.instant().getEpochSecond() + EXPIRATION.getSeconds();
assertEquals(expectedExpiration, initialExp);
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
assertTrue(saltedTokenHash.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHash.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHash.get().hash());
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
assertTrue(saltedTokenHashByPni.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByPni.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByPni.get().hash());
}
@Test
public void testLookupAfterRefresh() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
CLOCK.increment(50, TimeUnit.SECONDS);
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
final long updatedExp = fetchTimestamp(NUMBER);
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
final long updatedExp = fetchTimestamp(PNI);
final long expectedExp = CLOCK.instant().getEpochSecond() + EXPIRATION.getSeconds();
assertEquals(expectedExp, updatedExp);
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
assertTrue(saltedTokenHash.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHash.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHash.get().hash());
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
assertTrue(saltedTokenHashByPni.isPresent());
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByPni.get().salt());
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByPni.get().hash());
}
@Test
public void testReplace() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
store.addOrReplace(NUMBER, ANOTHER_HASH).get();
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
registrationRecoveryPasswords.addOrReplace(PNI, ANOTHER_HASH).get();
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
assertTrue(saltedTokenHash.isPresent());
assertEquals(ANOTHER_HASH.salt(), saltedTokenHash.get().salt());
assertEquals(ANOTHER_HASH.hash(), saltedTokenHash.get().hash());
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
assertTrue(saltedTokenHashByPni.isPresent());
assertEquals(ANOTHER_HASH.salt(), saltedTokenHashByPni.get().salt());
assertEquals(ANOTHER_HASH.hash(), saltedTokenHashByPni.get().hash());
}
@Test
public void testRemove() throws Exception {
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
assertTrue(store.lookup(NUMBER).get().isPresent());
assertDoesNotThrow(() -> registrationRecoveryPasswords.removeEntry(PNI).join());
store.removeEntry(NUMBER).get();
assertTrue(store.lookup(NUMBER).get().isEmpty());
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
assertTrue(registrationRecoveryPasswords.lookup(PNI).get().isPresent());
registrationRecoveryPasswords.removeEntry(PNI).get();
assertTrue(registrationRecoveryPasswords.lookup(PNI).get().isEmpty());
}
@Test
@@ -116,31 +117,31 @@ public class RegistrationRecoveryTest {
final byte[] wrongPassword = "qwerty123".getBytes(StandardCharsets.UTF_8);
// initial store
manager.storeForCurrentNumber(NUMBER, password).get();
assertTrue(manager.verify(NUMBER, password).get());
assertFalse(manager.verify(NUMBER, wrongPassword).get());
manager.store(PNI, password).get();
assertTrue(manager.verify(PNI, password).get());
assertFalse(manager.verify(PNI, wrongPassword).get());
// update
manager.storeForCurrentNumber(NUMBER, password).get();
assertTrue(manager.verify(NUMBER, password).get());
assertFalse(manager.verify(NUMBER, wrongPassword).get());
manager.store(PNI, password).get();
assertTrue(manager.verify(PNI, password).get());
assertFalse(manager.verify(PNI, wrongPassword).get());
// replace
manager.storeForCurrentNumber(NUMBER, updatedPassword).get();
assertTrue(manager.verify(NUMBER, updatedPassword).get());
assertFalse(manager.verify(NUMBER, password).get());
assertFalse(manager.verify(NUMBER, wrongPassword).get());
manager.store(PNI, updatedPassword).get();
assertTrue(manager.verify(PNI, updatedPassword).get());
assertFalse(manager.verify(PNI, password).get());
assertFalse(manager.verify(PNI, wrongPassword).get());
manager.removeForNumber(NUMBER).get();
assertFalse(manager.verify(NUMBER, updatedPassword).get());
assertFalse(manager.verify(NUMBER, password).get());
assertFalse(manager.verify(NUMBER, wrongPassword).get());
manager.remove(PNI).get();
assertFalse(manager.verify(PNI, updatedPassword).get());
assertFalse(manager.verify(PNI, password).get());
assertFalse(manager.verify(PNI, wrongPassword).get());
}
private static long fetchTimestamp(final String number) throws ExecutionException, InterruptedException {
private static long fetchTimestamp(final UUID phoneNumberIdentifier) throws ExecutionException, InterruptedException {
return DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient().getItem(GetItemRequest.builder()
.tableName(Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName())
.key(Map.of(RegistrationRecoveryPasswords.KEY_E164, AttributeValues.fromString(number)))
.key(Map.of(RegistrationRecoveryPasswords.KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.build())
.thenApply(getItemResponse -> {
final Map<String, AttributeValue> item = getItemResponse.item();
@@ -12,7 +12,6 @@ import static org.whispersystems.textsecuregcm.storage.Subscriptions.GetResult.T
import static org.whispersystems.textsecuregcm.storage.Subscriptions.GetResult.Type.PASSWORD_MISMATCH;
import jakarta.ws.rs.ClientErrorException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
@@ -36,7 +35,6 @@ class SubscriptionsTest {
private static final long NOW_EPOCH_SECONDS = 1_500_000_000L;
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(3);
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.SUBSCRIPTIONS);
@@ -177,10 +175,10 @@ class SubscriptionsTest {
}
@Test
void testCanceledAt() {
void testSetCanceledAt() {
Instant canceled = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 42);
assertThat(subscriptions.create(user, password, created)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.canceledAt(user, canceled)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.setCanceledAt(user, canceled)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.get(user, password)).succeedsWithin(DEFAULT_TIMEOUT).satisfies(getResult -> {
assertThat(getResult).isNotNull();
assertThat(getResult.type).isEqualTo(FOUND);
@@ -213,6 +211,36 @@ class SubscriptionsTest {
});
}
@Test
void testSubscriptionCreatedClearCanceledAt() {
String subscriptionId = Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(16));
Instant subscriptionCreated = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 1);
Instant canceledAt = subscriptionCreated.plusSeconds(1);
long level = 42;
assertThat(subscriptions.create(user, password, created)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.subscriptionCreated(user, subscriptionId, subscriptionCreated, level))
.succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.setCanceledAt(user, canceledAt)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.get(user, password).join().record.canceledAt).isEqualTo(canceledAt);
assertThat(subscriptions.subscriptionCreated(user, subscriptionId, subscriptionCreated, level))
.succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.get(user, password)).succeedsWithin(DEFAULT_TIMEOUT).satisfies(getResult -> {
assertThat(getResult).isNotNull();
assertThat(getResult.type).isEqualTo(FOUND);
assertThat(getResult.record).isNotNull().satisfies(record -> {
assertThat(record.accessedAt).isEqualTo(subscriptionCreated);
assertThat(record.subscriptionId).isEqualTo(subscriptionId);
assertThat(record.subscriptionCreatedAt).isEqualTo(subscriptionCreated);
assertThat(record.subscriptionLevel).isEqualTo(level);
assertThat(record.subscriptionLevelChangedAt).isEqualTo(subscriptionCreated);
assertThat(record.canceledAt).isNull();
});
});
}
@Test
void testSubscriptionLevelChanged() {
Instant at = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 500);
@@ -235,6 +263,34 @@ class SubscriptionsTest {
});
}
@Test
void testSubscriptionLevelChangedClearCanceledAt() {
Instant at = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 500);
Instant canceledAt = at.plusSeconds(100);
long level = 1776;
String updatedSubscriptionId = "new";
assertThat(subscriptions.create(user, password, created)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.subscriptionCreated(user, "original", created, level - 1))
.succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.setCanceledAt(user, canceledAt)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.get(user, password).join().record.canceledAt).isEqualTo(canceledAt);
assertThat(subscriptions.subscriptionLevelChanged(user, at, level, updatedSubscriptionId))
.succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.get(user, password)).succeedsWithin(DEFAULT_TIMEOUT).satisfies(getResult -> {
assertThat(getResult).isNotNull();
assertThat(getResult.type).isEqualTo(FOUND);
assertThat(getResult.record).isNotNull().satisfies(record -> {
assertThat(record.accessedAt).isEqualTo(at);
assertThat(record.subscriptionLevelChangedAt).isEqualTo(at);
assertThat(record.subscriptionLevel).isEqualTo(level);
assertThat(record.subscriptionId).isEqualTo(updatedSubscriptionId);
assertThat(record.canceledAt).isNull();
});
});
}
@Test
void testSetIapPurchase() {
Instant at = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 500);
@@ -287,6 +343,36 @@ class SubscriptionsTest {
assertThat(record.getProcessorCustomer().orElseThrow()).isEqualTo(pc);
}
@Test
void testSetIapPurchaseClearCanceledAt() {
Instant at = Instant.ofEpochSecond(NOW_EPOCH_SECONDS + 500);
Instant canceledAt = at.plusSeconds(100);
long level = 100;
ProcessorCustomer pc = new ProcessorCustomer("customerId", PaymentProvider.GOOGLE_PLAY_BILLING);
Record record = subscriptions.create(user, password, created).join();
// Should be able to set a fresh subscription
assertThat(subscriptions.setIapPurchase(record, pc, "subscriptionId", level, at))
.succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.setCanceledAt(record.user, canceledAt))
.succeedsWithin(DEFAULT_TIMEOUT);
record = subscriptions.get(user, password).join().record;
assertThat(record.canceledAt).isEqualTo(canceledAt);
// should be able to update the level
Instant nextAt = at.plus(Duration.ofSeconds(10));
long nextLevel = level + 1;
assertThat(subscriptions.setIapPurchase(record, pc, "subscriptionId", nextLevel, nextAt))
.succeedsWithin(DEFAULT_TIMEOUT);
// Resetting the level should clear the "canceled at" timestamp
record = subscriptions.get(user, password).join().record;
assertThat(record.canceledAt).isNull();
}
@Test
void testProcessorAndCustomerId() {
final ProcessorCustomer processorCustomer =
@@ -0,0 +1,237 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
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.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import com.webauthn4j.appattest.DeviceCheckManager;
import com.webauthn4j.appattest.authenticator.DCAppleDevice;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.Util;
class AppleDeviceCheckManagerTest {
private static final UUID ACI = UUID.randomUUID();
@RegisterExtension
static final RedisClusterExtension CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS,
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS_KEY_CONSTRAINT);
private final TestClock clock = TestClock.pinned(Instant.now());
private AppleDeviceChecks appleDeviceChecks;
private Account account;
private AppleDeviceCheckManager appleDeviceCheckManager;
@BeforeEach
void setupDeviceChecks() {
clock.pin(Instant.now());
account = mock(Account.class);
when(account.getUuid()).thenReturn(ACI);
final DeviceCheckManager deviceCheckManager = DeviceCheckTestUtil.appleDeviceCheckManager();
appleDeviceChecks = new AppleDeviceChecks(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DeviceCheckManager.createObjectConverter(),
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS.tableName(),
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS_KEY_CONSTRAINT.tableName());
appleDeviceCheckManager = new AppleDeviceCheckManager(appleDeviceChecks, CLUSTER_EXTENSION.getRedisCluster(),
deviceCheckManager, DeviceCheckTestUtil.SAMPLE_TEAM_ID, DeviceCheckTestUtil.SAMPLE_BUNDLE_ID);
}
@Test
public void missingChallengeAttest() {
assertThatExceptionOfType(ChallengeNotFoundException.class).isThrownBy(() ->
appleDeviceCheckManager.registerAttestation(account,
DeviceCheckTestUtil.SAMPLE_KEY_ID,
DeviceCheckTestUtil.SAMPLE_ATTESTATION));
}
@Test
public void missingChallengeAssert() {
assertThatExceptionOfType(ChallengeNotFoundException.class).isThrownBy(() ->
appleDeviceCheckManager.validateAssert(account,
DeviceCheckTestUtil.SAMPLE_KEY_ID,
AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION, DeviceCheckTestUtil.SAMPLE_CHALLENGE,
DeviceCheckTestUtil.SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8),
DeviceCheckTestUtil.SAMPLE_ASSERTION));
}
@Test
public void tooManyKeys() throws DuplicatePublicKeyException {
final DCAppleDevice dcAppleDevice = DeviceCheckTestUtil.sampleDevice();
// Fill the table with a bunch of keyIds
final List<byte[]> keyIds = IntStream
.range(0, AppleDeviceCheckManager.MAX_DEVICE_KEYS - 1)
.mapToObj(i -> TestRandomUtil.nextBytes(16)).toList();
for (byte[] keyId : keyIds) {
appleDeviceChecks.storeAttestation(account, keyId, dcAppleDevice);
}
// We're allowed 1 more key for this account
assertThatNoException().isThrownBy(() -> registerAttestation(account));
// a new key should be rejected
assertThatExceptionOfType(TooManyKeysException.class).isThrownBy(() ->
appleDeviceCheckManager.registerAttestation(account,
TestRandomUtil.nextBytes(16),
DeviceCheckTestUtil.SAMPLE_ATTESTATION));
// we can however accept an existing key
assertThatNoException().isThrownBy(() -> registerAttestation(account, false));
}
@Test
public void duplicateKeys() {
assertThatNoException().isThrownBy(() -> registerAttestation(account));
final Account duplicator = mock(Account.class);
when(duplicator.getUuid()).thenReturn(UUID.randomUUID());
// Both accounts use the attestation keyId, the second registration should fail
assertThatExceptionOfType(DuplicatePublicKeyException.class)
.isThrownBy(() -> registerAttestation(duplicator));
}
@Test
public void fetchingChallengeRefreshesTtl() throws RateLimitExceededException {
final String challenge =
appleDeviceCheckManager.createChallenge(AppleDeviceCheckManager.ChallengeType.ATTEST, account);
final String redisKey = AppleDeviceCheckManager.challengeKey(AppleDeviceCheckManager.ChallengeType.ATTEST,
account.getUuid());
final String storedChallenge = CLUSTER_EXTENSION.getRedisCluster()
.withCluster(cluster -> cluster.sync().get(redisKey));
assertThat(storedChallenge).isEqualTo(challenge);
final Supplier<Long> ttl = () -> CLUSTER_EXTENSION.getRedisCluster()
.withCluster(cluster -> cluster.sync().ttl(redisKey));
// Wait until the TTL visibly changes (~1sec)
while (ttl.get() >= AppleDeviceCheckManager.CHALLENGE_TTL.toSeconds()) {
Util.sleep(100);
}
// Our TTL fetch needs to happen before the TTL ticks down to make sure the TTL was actually refreshed. So it must
// happen within 1 second. This should be plenty of time, but allow a few retries in case we get very unlucky.
final boolean ttlRefreshed = IntStream.range(0, 5)
.mapToObj(i -> {
assertThatNoException()
.isThrownBy(
() -> appleDeviceCheckManager.createChallenge(AppleDeviceCheckManager.ChallengeType.ATTEST, account));
return ttl.get() == AppleDeviceCheckManager.CHALLENGE_TTL.toSeconds();
})
.anyMatch(detectedRefresh -> detectedRefresh);
assertThat(ttlRefreshed).isTrue();
assertThat(appleDeviceCheckManager.createChallenge(AppleDeviceCheckManager.ChallengeType.ATTEST, account))
.isEqualTo(challenge);
}
@Test
public void validateAssertion() {
assertThatNoException().isThrownBy(() -> registerAttestation(account));
// The sign counter should be 0 since we've made no attests
assertThat(appleDeviceChecks.lookup(account, DeviceCheckTestUtil.SAMPLE_KEY_ID).get().getCounter())
.isEqualTo(0L);
// Rig redis to return our sample challenge for the assert
final String assertChallengeKey = AppleDeviceCheckManager.challengeKey(
AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION,
account.getUuid());
CLUSTER_EXTENSION.getRedisCluster().useCluster(cluster ->
cluster.sync().set(assertChallengeKey, DeviceCheckTestUtil.SAMPLE_CHALLENGE));
assertThatNoException().isThrownBy(() ->
appleDeviceCheckManager.validateAssert(
account,
DeviceCheckTestUtil.SAMPLE_KEY_ID,
AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION, DeviceCheckTestUtil.SAMPLE_CHALLENGE,
DeviceCheckTestUtil.SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8),
DeviceCheckTestUtil.SAMPLE_ASSERTION));
CLUSTER_EXTENSION.getRedisCluster().useCluster(cluster ->
assertThat(cluster.sync().get(assertChallengeKey)).isNull());
// the sign counter should now be 1 (read from our sample assert)
assertThat(appleDeviceChecks.lookup(account, DeviceCheckTestUtil.SAMPLE_KEY_ID).get().getCounter())
.isEqualTo(1L);
}
@Test
public void assertionCounterMovesBackwards() {
assertThatNoException().isThrownBy(() -> registerAttestation(account));
// force set the sign counter for our keyId to be larger than the sign counter in our sample assert (1)
appleDeviceChecks.updateCounter(account, DeviceCheckTestUtil.SAMPLE_KEY_ID, 2);
// Rig redis to return our sample challenge for the assert
CLUSTER_EXTENSION.getRedisCluster().useCluster(cluster -> cluster.sync().set(
AppleDeviceCheckManager.challengeKey(
AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION,
account.getUuid()),
DeviceCheckTestUtil.SAMPLE_CHALLENGE));
assertThatExceptionOfType(RequestReuseException.class).isThrownBy(() ->
appleDeviceCheckManager.validateAssert(
account,
DeviceCheckTestUtil.SAMPLE_KEY_ID,
AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION, DeviceCheckTestUtil.SAMPLE_CHALLENGE,
DeviceCheckTestUtil.SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8),
DeviceCheckTestUtil.SAMPLE_ASSERTION));
}
private void registerAttestation(final Account account)
throws DeviceCheckVerificationFailedException, ChallengeNotFoundException, TooManyKeysException, DuplicatePublicKeyException {
registerAttestation(account, true);
}
private void registerAttestation(final Account account, boolean assertChallengeRemoved)
throws DeviceCheckVerificationFailedException, ChallengeNotFoundException, TooManyKeysException, DuplicatePublicKeyException {
final String attestChallengeKey = AppleDeviceCheckManager.challengeKey(
AppleDeviceCheckManager.ChallengeType.ATTEST,
account.getUuid());
CLUSTER_EXTENSION.getRedisCluster().useCluster(cluster ->
cluster.sync().set(attestChallengeKey, DeviceCheckTestUtil.SAMPLE_CHALLENGE));
try (MockedStatic<Instant> mocked = mockStatic(Instant.class, Mockito.CALLS_REAL_METHODS)) {
mocked.when(Instant::now).thenReturn(DeviceCheckTestUtil.SAMPLE_TIME);
appleDeviceCheckManager.registerAttestation(account,
DeviceCheckTestUtil.SAMPLE_KEY_ID,
DeviceCheckTestUtil.SAMPLE_ATTESTATION);
}
if (assertChallengeRemoved) {
CLUSTER_EXTENSION.getRedisCluster().useCluster(cluster -> {
// should be deleted once the attestation is registered
assertThat(cluster.sync().get(attestChallengeKey)).isNull();
});
}
}
}
@@ -0,0 +1,125 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
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.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.webauthn4j.appattest.DeviceCheckManager;
import com.webauthn4j.appattest.authenticator.DCAppleDevice;
import java.util.List;
import java.util.UUID;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class AppleDeviceChecksTest {
private static final UUID ACI = UUID.randomUUID();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS,
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS_KEY_CONSTRAINT);
private AppleDeviceChecks deviceChecks;
private Account account;
@BeforeEach
void setupDeviceChecks() {
account = mock(Account.class);
when(account.getUuid()).thenReturn(ACI);
deviceChecks = new AppleDeviceChecks(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DeviceCheckManager.createObjectConverter(),
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS.tableName(),
DynamoDbExtensionSchema.Tables.APPLE_DEVICE_CHECKS_KEY_CONSTRAINT.tableName());
}
@Test
public void testSerde() throws DuplicatePublicKeyException {
final DCAppleDevice appleDevice = DeviceCheckTestUtil.appleSampleDevice();
final byte[] keyId = appleDevice.getAttestedCredentialData().getCredentialId();
assertThat(deviceChecks.storeAttestation(account, keyId, appleDevice)).isTrue();
assertThat(deviceChecks.keyIds(account)).containsExactly(keyId);
final DCAppleDevice deserialized = deviceChecks.lookup(account, keyId).orElseThrow();
assertThat(deserialized.getClass()).isEqualTo(appleDevice.getClass());
assertThat(deserialized.getAttestationStatement().getFormat())
.isEqualTo(appleDevice.getAttestationStatement().getFormat());
assertThat(deserialized.getAttestationStatement().getClass())
.isEqualTo(appleDevice.getAttestationStatement().getClass());
assertThat(deserialized.getAttestedCredentialData().getCredentialId())
.isEqualTo(appleDevice.getAttestedCredentialData().getCredentialId());
assertThat(deserialized.getAttestedCredentialData().getCOSEKey())
.isEqualTo(appleDevice.getAttestedCredentialData().getCOSEKey());
assertThat(deserialized.getAttestedCredentialData().getAaguid())
.isEqualTo(appleDevice.getAttestedCredentialData().getAaguid());
assertThat(deserialized.getAuthenticatorExtensions().getExtensions())
.containsExactlyEntriesOf(appleDevice.getAuthenticatorExtensions().getExtensions());
assertThat(deserialized.getCounter())
.isEqualTo(appleDevice.getCounter());
}
@Test
public void duplicateKeys() throws DuplicatePublicKeyException {
final DCAppleDevice appleDevice = DeviceCheckTestUtil.appleSampleDevice();
final byte[] keyId = appleDevice.getAttestedCredentialData().getCredentialId();
final Account dupliateAccount = mock(Account.class);
when(dupliateAccount.getUuid()).thenReturn(UUID.randomUUID());
deviceChecks.storeAttestation(account, keyId, appleDevice);
// Storing same key with a different account fails
assertThatExceptionOfType(DuplicatePublicKeyException.class)
.isThrownBy(() -> deviceChecks.storeAttestation(dupliateAccount, keyId, appleDevice));
// Storing the same key with the same account is fine
assertThatNoException().isThrownBy(() -> deviceChecks.storeAttestation(account, keyId, appleDevice));
}
@Test
public void multipleKeys() throws DuplicatePublicKeyException {
final DCAppleDevice appleDevice = DeviceCheckTestUtil.appleSampleDevice();
final List<byte[]> keyIds = IntStream.range(0, 10).mapToObj(i -> TestRandomUtil.nextBytes(16)).toList();
for (byte[] keyId : keyIds) {
// The keyId should typically match the device attestation, but we don't check that at this layer
assertThat(deviceChecks.storeAttestation(account, keyId, appleDevice)).isTrue();
assertThat(deviceChecks.lookup(account, keyId)).isNotEmpty();
}
final List<byte[]> actual = deviceChecks.keyIds(account);
assertThat(actual).containsExactlyInAnyOrderElementsOf(keyIds);
}
@Test
public void updateCounter() throws DuplicatePublicKeyException {
final DCAppleDevice appleDevice = DeviceCheckTestUtil.appleSampleDevice();
final byte[] keyId = appleDevice.getAttestedCredentialData().getCredentialId();
assertThat(appleDevice.getCounter()).isEqualTo(0L);
deviceChecks.storeAttestation(account, keyId, appleDevice);
assertThat(deviceChecks.lookup(account, keyId).get().getCounter()).isEqualTo(0L);
assertThat(deviceChecks.updateCounter(account, keyId, 2)).isTrue();
assertThat(deviceChecks.lookup(account, keyId).get().getCounter()).isEqualTo(2L);
// Should not update since the counter is stale
assertThat(deviceChecks.updateCounter(account, keyId, 1)).isFalse();
assertThat(deviceChecks.lookup(account, keyId).get().getCounter()).isEqualTo(2L);
}
}
@@ -0,0 +1,134 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
import static org.mockito.Mockito.mockStatic;
import com.webauthn4j.appattest.DeviceCheckManager;
import com.webauthn4j.appattest.authenticator.DCAppleDevice;
import com.webauthn4j.appattest.authenticator.DCAppleDeviceImpl;
import com.webauthn4j.appattest.data.DCAttestationData;
import com.webauthn4j.appattest.data.DCAttestationParameters;
import com.webauthn4j.appattest.data.DCAttestationRequest;
import com.webauthn4j.appattest.server.DCServerProperty;
import com.webauthn4j.data.attestation.AttestationObject;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class DeviceCheckTestUtil {
// https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem
private static final String APPLE_APP_ATTEST_ROOT = """
-----BEGIN CERTIFICATE-----
MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYw
JAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwK
QXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNa
Fw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlv
biBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9y
bmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdh
NbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9au
Yen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/
MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYw
CgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn
53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijV
oyFraWVIyd/dganmrduC1bmTBGwD
-----END CERTIFICATE-----
""";
// Sample attestation from apple docs:
// https://developer.apple.com/documentation/devicecheck/attestation-object-validation-guide#Example-setup
final static String APPLE_SAMPLE_TEAM_ID = "0352187391";
final static String APPLE_SAMPLE_BUNDLE_ID = "com.apple.example_app_attest";
final static String APPLE_SAMPLE_CHALLENGE = "test_server_challenge";
final static byte[] APPLE_SAMPLE_KEY_ID = Base64.getDecoder().decode("bSrEhF8TIzIvWSPwvZ0i2+UOBre4ASH84rK15m6emNY=");
final static byte[] APPLE_SAMPLE_ATTESTATION = loadBinaryResource("apple-sample-attestation");
// Leaf certificate in apple sample attestation expires 2024-04-20
final static Instant APPLE_SAMPLE_TIME = Instant.parse("2024-04-19T00:00:00.00Z");
// Sample attestation from webauthn4j:
// https://github.com/webauthn4j/webauthn4j/blob/6b7a8f8edce4ab589c49ecde8740873ab96c4218/webauthn4j-appattest/src/test/java/com/webauthn4j/appattest/DeviceCheckManagerTest.java#L126
final static String SAMPLE_TEAM_ID = "8YE23NZS57";
final static String SAMPLE_BUNDLE_ID = "com.kayak.travel";
final static byte[] SAMPLE_KEY_ID = Base64.getDecoder().decode("VnfqjSp0rWyyqNhrfh+9/IhLIvXuYTPAmJEVQwl4dko=");
final static String SAMPLE_CHALLENGE = "1234567890abcdefgh"; // same challenge used for the attest and assert
final static byte[] SAMPLE_ASSERTION = loadBinaryResource("webauthn4j-sample-assertion");
final static byte[] SAMPLE_ATTESTATION = loadBinaryResource("webauthn4j-sample-attestation");
// Leaf certificate in sample attestation expires 2020-09-30
final static Instant SAMPLE_TIME = Instant.parse("2020-09-28T00:00:00Z");
public static DeviceCheckManager appleDeviceCheckManager() {
return new DeviceCheckManager(new AppleDeviceCheckTrustAnchor());
}
public static DCAppleDevice sampleDevice() {
final byte[] clientDataHash = sha256(SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8));
return validate(SAMPLE_CHALLENGE, clientDataHash, SAMPLE_KEY_ID, SAMPLE_ATTESTATION, SAMPLE_TEAM_ID,
SAMPLE_BUNDLE_ID, SAMPLE_TIME);
}
public static DCAppleDevice appleSampleDevice() {
// Note: the apple example provides the clientDataHash (typically the SHA256 of the challenge), NOT the challenge,
// despite them referring to the value as a challenge
final byte[] clientDataHash = APPLE_SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8);
return validate(APPLE_SAMPLE_CHALLENGE, clientDataHash, APPLE_SAMPLE_KEY_ID, APPLE_SAMPLE_ATTESTATION,
APPLE_SAMPLE_TEAM_ID, APPLE_SAMPLE_BUNDLE_ID, APPLE_SAMPLE_TIME);
}
private static DCAppleDevice validate(final String challengePlainText, final byte[] clientDataHash,
final byte[] keyId, final byte[] attestation, final String teamId, final String bundleId, final Instant now) {
final DCAttestationRequest dcAttestationRequest = new DCAttestationRequest(keyId, attestation, clientDataHash);
final DCAttestationData dcAttestationData;
try (final MockedStatic<Instant> instantMock = mockStatic(Instant.class, Mockito.CALLS_REAL_METHODS)) {
instantMock.when(Instant::now).thenReturn(now);
dcAttestationData = appleDeviceCheckManager().validate(dcAttestationRequest, new DCAttestationParameters(
new DCServerProperty(
teamId, bundleId,
new DefaultChallenge(challengePlainText.getBytes(StandardCharsets.UTF_8)))));
}
final AttestationObject attestationObject = dcAttestationData.getAttestationObject();
return new DCAppleDeviceImpl(
attestationObject.getAuthenticatorData().getAttestedCredentialData(),
attestationObject.getAttestationStatement(),
attestationObject.getAuthenticatorData().getSignCount(),
attestationObject.getAuthenticatorData().getExtensions());
}
private static byte[] sha256(byte[] bytes) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (final NoSuchAlgorithmException e) {
// All Java implementations are required to support SHA-256
throw new AssertionError(e);
}
return sha256.digest(bytes);
}
private static byte[] loadBinaryResource(final String resourceName) {
try (InputStream stream = DeviceCheckTestUtil.class.getResourceAsStream(resourceName)) {
if (stream == null) {
throw new IllegalArgumentException("Resource not found: " + resourceName);
}
return stream.readAllBytes();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -85,6 +85,7 @@ public class AuthHelper {
public static final String UNDISCOVERABLE_NUMBER = "+18005551234";
public static final UUID UNDISCOVERABLE_UUID = UUID.randomUUID();
public static final UUID UNDISCOVERABLE_PNI = UUID.randomUUID();
public static final String UNDISCOVERABLE_PASSWORD = "IT'S A SECRET TO EVERYBODY.";
public static final ECKeyPair VALID_IDENTITY_KEY_PAIR = Curve.generateKeyPair();
@@ -169,7 +170,9 @@ public class AuthHelper {
when(VALID_ACCOUNT_TWO.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_TWO);
when(UNDISCOVERABLE_ACCOUNT.getNumber()).thenReturn(UNDISCOVERABLE_NUMBER);
when(UNDISCOVERABLE_ACCOUNT.getUuid()).thenReturn(UNDISCOVERABLE_UUID);
when(UNDISCOVERABLE_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(UNDISCOVERABLE_PNI);
when(UNDISCOVERABLE_ACCOUNT.getIdentifier(IdentityType.ACI)).thenReturn(UNDISCOVERABLE_UUID);
when(UNDISCOVERABLE_ACCOUNT.getIdentifier(IdentityType.PNI)).thenReturn(UNDISCOVERABLE_PNI);
when(VALID_ACCOUNT_3.getNumber()).thenReturn(VALID_NUMBER_3);
when(VALID_ACCOUNT_3.getUuid()).thenReturn(VALID_UUID_3);
when(VALID_ACCOUNT_3.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_3);
@@ -1,22 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import org.junit.jupiter.api.Test;
class NumberPrefixTest {
@Test
void testPrefixes() {
assertThat(Util.getNumberPrefix("+14151234567")).isEqualTo("+14151");
assertThat(Util.getNumberPrefix("+22587654321")).isEqualTo("+2258765");
assertThat(Util.getNumberPrefix("+298654321")).isEqualTo("+2986543");
assertThat(Util.getNumberPrefix("+12")).isEqualTo("+12");
}
}
@@ -0,0 +1,111 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
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 com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import java.util.stream.Stream;
import com.google.i18n.phonenumbers.Phonenumber;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
class UtilTest {
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
private static final String NEW_FORMAT_BENIN_E164_STRING = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
private static final String OLD_FORMAT_BENIN_E164_STRING = NEW_FORMAT_BENIN_E164_STRING.replaceFirst("01", "");
@ParameterizedTest
@MethodSource
void getAlternateForms(final String phoneNumber, final List<String> expectedAlternateForms) {
assertEquals(expectedAlternateForms, Util.getAlternateForms(phoneNumber));
}
static List<Arguments> getAlternateForms() {
final String usE164 = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
return List.of(
Arguments.of(usE164, List.of(usE164)),
Arguments.of(NEW_FORMAT_BENIN_E164_STRING, List.of(NEW_FORMAT_BENIN_E164_STRING, OLD_FORMAT_BENIN_E164_STRING)),
Arguments.of(OLD_FORMAT_BENIN_E164_STRING, List.of(OLD_FORMAT_BENIN_E164_STRING, NEW_FORMAT_BENIN_E164_STRING))
);
}
@Test
void getCanonicalNumber() {
final String usE164 = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
assertEquals(Optional.of(usE164), Util.getCanonicalNumber(List.of(usE164)));
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
assertEquals(Optional.of(newFormatBeninE164), Util.getCanonicalNumber(List.of(oldFormatBeninE164, newFormatBeninE164)));
assertEquals(Optional.empty(), Util.getCanonicalNumber(List.of()));
}
@ParameterizedTest
@CsvSource({
"0, 1, false",
"123456789, 1, true",
"123456789, 123, true",
"123456789, 456, false",
})
void startsWithDecimal(final long number, final long prefix, final boolean expectStartsWithPrefix) {
assertEquals(expectStartsWithPrefix, Util.startsWithDecimal(number, prefix));
}
@ParameterizedTest
@MethodSource
void isOldFormatBeninPhoneNumber4(final Phonenumber.PhoneNumber beninNumber, final boolean isOldFormatBeninNumber) {
if (isOldFormatBeninNumber) {
assertTrue(Util.isOldFormatBeninPhoneNumber(beninNumber));
} else {
assertFalse(Util.isOldFormatBeninPhoneNumber(beninNumber));
}
}
private static Stream<Arguments> isOldFormatBeninPhoneNumber4() throws NumberParseException {
final Phonenumber.PhoneNumber oldFormatBeninE164 = PhoneNumberUtil.getInstance().parse(OLD_FORMAT_BENIN_E164_STRING, null);
final Phonenumber.PhoneNumber newFormatBeninE164 = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
return Stream.of(
Arguments.of(oldFormatBeninE164, true),
Arguments.of(newFormatBeninE164, false),
Arguments.of(PhoneNumberUtil.getInstance().getExampleNumber("US"), false)
);
}
@ParameterizedTest
@MethodSource
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber)
throws NumberParseException {
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
}
private static Stream<Arguments> normalizeBeninPhoneNumber() throws NumberParseException {
final Phonenumber.PhoneNumber oldFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(OLD_FORMAT_BENIN_E164_STRING, null);
final Phonenumber.PhoneNumber newFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
final Phonenumber.PhoneNumber usPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("US");
return Stream.of(
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
Arguments.of(oldFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
Arguments.of(usPhoneNumber, usPhoneNumber)
);
}
}
@@ -99,7 +99,7 @@ class WebSocketConnectionIntegrationTest {
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7),
sharedExecutorService);
@@ -73,12 +73,15 @@ class FinishPushNotificationExperimentCommandTest {
null,
null,
null,
null,
pushNotificationExperimentSamples,
null,
null,
null,
null,
null,
null,
null,
null);
//noinspection unchecked
@@ -66,6 +66,9 @@ class NotifyIdleDevicesCommandTest {
null,
null,
null,
null,
null,
null,
null);
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
@@ -62,12 +62,15 @@ class StartPushNotificationExperimentCommandTest {
null,
null,
null,
null,
pushNotificationExperimentSamples,
null,
null,
null,
null,
null,
null,
null,
null);
}
+41 -21
View File
@@ -89,6 +89,15 @@ appleAppStore:
# An apple root cert https://www.apple.com/certificateauthority/
- MIIEuzCCA6OgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwHhcNMDYwNDI1MjE0MDM2WhcNMzUwMjA5MjE0MDM2WjBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkkakJH5HbHkdQ6wXtXnmELes2oldMVeyLGYne+Uts9QerIjAC6Bg++FAJ039BqJj50cpmnCRrEdCju+QbKsMflZ56DKRHi1vUFjczy8QPTc4UadHJGXL1XQ7Vf1+b8iUDulWPTV0N8WQ1IxVLFVkds5T39pyez1C6wVhQZ48ItCD3y6wsIG9wtj8BMIy3Q88PnT3zK0koGsj+zrW5DtleHNbLPbU6rfQPDgCSC7EhFi501TwN22IWq6NxkkdTVcGvL0Gz+PvjcM3mo0xFfh9Ma1CWQYnEdGILEINBhzOKgbEwWOxaBDKMaLOPHd5lc/9nXmW8Sdh2nzMUZaF3lMktAgMBAAGjggF6MIIBdjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUK9BpR5R2Cf70a40uQKb3R01/CF4wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wggERBgNVHSAEggEIMIIBBDCCAQAGCSqGSIb3Y2QFATCB8jAqBggrBgEFBQcCARYeaHR0cHM6Ly93d3cuYXBwbGUuY29tL2FwcGxlY2EvMIHDBggrBgEFBQcCAjCBthqBs1JlbGlhbmNlIG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBjb25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZpY2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMA0GCSqGSIb3DQEBBQUAA4IBAQBcNplMLXi37Yyb3PN3m/J20ncwT8EfhYOFG5k9RzfyqZtAjizUsZAS2L70c5vu0mQPy3lPNNiiPvl4/2vIB+x9OYOLUyDTOMSxv5pPCmv/K/xZpwUJfBdAVhEedNO3iyM7R6PVbyTi69G3cN8PReEnyvFteO3ntRcXqNx+IjXKJdXZD9Zr1KIkIxH3oayPc4FgxhtbCS+SsvhESPBgOJ4V9T0mZyCKM2r3DYLP3uujL/lTaltkwGMzd/c6ByxW69oPIQ7aunMZT7XZNn/Bh1XZp5m5MkL72NVxnn6hUrcbvZNCJBIqxw8dtk2cXmPIS4AXUKqK1drk/NAJBzewdXUh
appleDeviceCheck:
production: false
teamId: 0123456789
bundleId: bundle.name
deviceCheck:
backupRedemptionDuration: P30D
backupRedemptionLevel: 201
dynamoDbClient:
type: local
@@ -99,6 +108,10 @@ dynamoDbTables:
phoneNumberIdentifierTableName: pni_assignment_test
usernamesTableName: usernames_test
usedLinkDeviceTokensTableName: used_link_device_tokens_test
appleDeviceChecks:
tableName: apple_device_checks_test
appleDeviceCheckPublicKeys:
tableName: apple_device_check_public_keys_test
backups:
tableName: backups_test
clientReleases:
@@ -111,6 +124,11 @@ dynamoDbTables:
tableName: issued_receipts_test
expiration: P30D # Duration of time until rows expire
generator: abcdefg12345678= # random base64-encoded binary sequence
maxIssuedReceiptsPerPaymentId:
STRIPE: 1
BRAINTREE: 1
GOOGLE_PLAY_BILLING: 1
APPLE_APP_STORE: 1
ecKeys:
tableName: keys_test
ecSignedPreKeys:
@@ -200,34 +218,36 @@ svr2:
-----END CERTIFICATE-----
svr3:
uri: svr3.example.com
backend1Uri: backend1.example.com
backend2Uri: backend2.example.com
backend3Uri: backend3.example.com
userAuthenticationTokenSharedSecret: secret://svr3.userAuthenticationTokenSharedSecret
userIdTokenSharedSecret: secret://svr3.userIdTokenSharedSecret
svrCaCertificates:
# This is a randomly generated test certificate
- |
-----BEGIN CERTIFICATE-----
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
AAAAAAAAAAAAAAAAAAAA
MIIDazCCAlOgAwIBAgIUW5lcNWkuynRVc8Rq5pO6mHQBuZAwDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDAzMjUwMzE4MTNaFw0yOTAz
MjQwMzE4MTNaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw
HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQCfH4Um+fv2r4KudhD37/UXp8duRLTmp4XvpBTpDHpD
2HF8p2yThVKlJnMkP/9Ey1Rb0vhxO7DCltLdW8IYcxJuHoyMvyhGUEtxxkOZbrk8
ciUR9jTZ37x7vXRGj/RxcdlS6iD0MeF0D/LAkImt4T/kiKwDbENrVEnYWJmipCKP
ribxWky7HqxDCoYMQr0zatxB3A9mx5stH+H3kbw3CZcm+ugF9ZIKDEVHb0lf28gq
llmD120q/vs9YV3rzVL7sBGDqf6olkulvHQJKElZg2rdcHWFcngSlU2BjR04oyuH
c/SSiLSB3YB0tdFGta5uorXyV1y7RElPeBfOfvEjsG3TAgMBAAGjUzBRMB0GA1Ud
DgQWBBQX+xlgSWWbDjv0SrJ+h67xauJ80zAfBgNVHSMEGDAWgBQX+xlgSWWbDjv0
SrJ+h67xauJ80zAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAw
ZG2MCCjscn6h/QOoJU+IDfa68OqLq0I37gMnLMde4yEhAmm//miePIq4Uz9GRJ+h
rAmdEnspKgyQ93PjF7Xpk/JdJA4B1bIrsOl/cSwqx2sFhRt8Kt1DHGlGWXqOaHRP
UkZ86MyRL3sXly6WkxEYxZJeQaOzMy2XmQh7grzrlTBuSI+0xf7vsRRDipxr6LVQ
6qGWyGODLLc2JD1IXj/1HpRVT2LoGGlKMuyxACQAm4oak1vvJ9mGxgfd9AU+eo58
O/esB2Eaf+QqMPELdFSZQfG2jvp+3WQTZK8fDKHyLr076G3UetEMy867F6fzTSZd
9Kxq0DY7RCEpdHMCKcOL
-----END CERTIFICATE-----
messageCache: # Redis server configuration for message store cache
persistDelayMinutes: 1
cluster:
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more