mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 04:46:47 +00:00
Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2f5e0e26f | ||
|
|
9121032114 | ||
|
|
541bf968e5 | ||
|
|
8c3ebdcbab | ||
|
|
0593e9e89f | ||
|
|
0d412c88fd | ||
|
|
8280106493 | ||
|
|
a3e106fe04 | ||
|
|
981a04f33b | ||
|
|
26025e5abd | ||
|
|
4839a5ba70 | ||
|
|
85a1550485 | ||
|
|
77658415b2 | ||
|
|
68f27be7cd | ||
|
|
6460327372 | ||
|
|
a96c0ec7a3 | ||
|
|
33c0a27b85 | ||
|
|
d5b39cd496 | ||
|
|
5a35d69ed0 | ||
|
|
e1e94a33e2 | ||
|
|
18c9b177f3 | ||
|
|
1970741049 | ||
|
|
f16428ce2a | ||
|
|
14427523ae | ||
|
|
236b0496d3 | ||
|
|
f68ddf66e9 | ||
|
|
20685b6d69 | ||
|
|
4988b4e0f5 | ||
|
|
651e444875 | ||
|
|
2093fed554 | ||
|
|
cc7bb8b549 | ||
|
|
a99ac14c6a | ||
|
|
2c163352c3 | ||
|
|
fb6c4eca34 | ||
|
|
142e2cbe9d | ||
|
|
c70dd119d3 | ||
|
|
9e312cbdfa | ||
|
|
4d87b741cd | ||
|
|
d08bc4c413 | ||
|
|
f5d3d1e65d | ||
|
|
916314233f | ||
|
|
c7e6ee7297 | ||
|
|
557a6ecd4f | ||
|
|
0e04cac800 | ||
|
|
1db9258d39 | ||
|
|
2803c2acdb | ||
|
|
8be43566a4 | ||
|
|
d865cec2a4 | ||
|
|
6f0370a073 | ||
|
|
5b9f8177f2 | ||
|
|
6967e4e54b | ||
|
|
96fb0ac3ae | ||
|
|
7201938793 | ||
|
|
cdd6f78c73 |
No files matched your search
@@ -8,6 +8,7 @@ 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;
|
||||
@@ -20,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 {
|
||||
|
||||
@@ -28,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();
|
||||
@@ -35,9 +37,6 @@ public class IntegrationTools {
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient =
|
||||
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers());
|
||||
|
||||
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbAsyncClient, Clock.systemUTC());
|
||||
|
||||
@@ -45,20 +44,25 @@ public class IntegrationTools {
|
||||
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
|
||||
|
||||
return new IntegrationTools(
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers),
|
||||
new VerificationSessionManager(verificationSessions)
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
|
||||
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) {
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>1.9.24</kotlin.version>
|
||||
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
|
||||
<lettuce.version>6.4.1.RELEASE</lettuce.version>
|
||||
<lettuce.version>6.5.1.RELEASE</lettuce.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>
|
||||
|
||||
@@ -16,9 +16,6 @@ directoryV2.client.userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789
|
||||
svr2.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth tokens for Signal users
|
||||
svr2.userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth identity tokens for Signal users
|
||||
|
||||
svr3.userAuthenticationTokenSharedSecret: cbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR3 to generate auth tokens for Signal users
|
||||
svr3.userIdTokenSharedSecret: dbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR3 to generate auth identity tokens for Signal users
|
||||
|
||||
tus.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG=
|
||||
|
||||
gcpAttachments.rsaSigningKey: |
|
||||
@@ -92,9 +89,6 @@ paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
paymentsService.fixerApiKey: unset
|
||||
paymentsService.coinMarketCapApiKey: unset
|
||||
|
||||
artService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret not shared with any external service, but used in ArtController
|
||||
artService.userAuthenticationTokenUserIdSecret: AAAAAAAAAAA= # base64-encoded secret to obscure user phone numbers from Sticker Creator
|
||||
|
||||
currentReportingKey.secret: AAAAAAAAAAA=
|
||||
currentReportingKey.salt: AAAAAAAAAAA=
|
||||
|
||||
|
||||
+17
-33
@@ -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:
|
||||
@@ -202,35 +219,6 @@ svr2:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
svr3:
|
||||
uri: svr3.example.com
|
||||
userAuthenticationTokenSharedSecret: secret://svr3.userAuthenticationTokenSharedSecret
|
||||
userIdTokenSharedSecret: secret://svr3.userIdTokenSharedSecret
|
||||
svrCaCertificates:
|
||||
- |
|
||||
-----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
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
cluster:
|
||||
@@ -343,10 +331,6 @@ paymentsService:
|
||||
coinMarketCapCurrencyIds:
|
||||
MOB: 7878
|
||||
|
||||
artService:
|
||||
userAuthenticationTokenSharedSecret: secret://artService.userAuthenticationTokenSharedSecret
|
||||
userAuthenticationTokenUserIdSecret: secret://artService.userAuthenticationTokenUserIdSecret
|
||||
|
||||
badges:
|
||||
badges:
|
||||
- id: TEST
|
||||
|
||||
@@ -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>
|
||||
|
||||
+20
-18
@@ -16,7 +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.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
@@ -25,6 +25,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;
|
||||
@@ -50,7 +51,6 @@ import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.S3ObjectMonitorFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ShortCodeExpanderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
|
||||
@@ -96,6 +96,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
|
||||
@@ -145,10 +155,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private SecureValueRecovery2Configuration svr2;
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private SecureValueRecovery3Configuration svr3;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -210,11 +216,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ArtServiceConfiguration artService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -359,6 +360,14 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return appleAppStore;
|
||||
}
|
||||
|
||||
public AppleDeviceCheckConfiguration getAppleDeviceCheck() {
|
||||
return appleDeviceCheck;
|
||||
}
|
||||
|
||||
public DeviceCheckConfiguration getDeviceCheck() {
|
||||
return deviceCheck;
|
||||
}
|
||||
|
||||
public DynamoDbClientFactory getDynamoDbClientConfiguration() {
|
||||
return dynamoDbClient;
|
||||
}
|
||||
@@ -390,9 +399,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public SecureValueRecovery2Configuration getSvr2Configuration() {
|
||||
return svr2;
|
||||
}
|
||||
public SecureValueRecovery3Configuration getSvr3Configuration() {
|
||||
return svr3;
|
||||
}
|
||||
|
||||
public DirectoryV2Configuration getDirectoryV2Configuration() {
|
||||
return directoryV2;
|
||||
@@ -457,10 +463,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return paymentsService;
|
||||
}
|
||||
|
||||
public ArtServiceConfiguration getArtServiceConfiguration() {
|
||||
return artService;
|
||||
}
|
||||
|
||||
public ZkConfig getZkConfig() {
|
||||
return zkConfig;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -107,13 +108,13 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArtController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ChallengeController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DeviceCheckController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DeviceController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DirectoryV2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.DonationController;
|
||||
@@ -129,7 +130,6 @@ import org.whispersystems.textsecuregcm.controllers.RegistrationController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery3Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
|
||||
import org.whispersystems.textsecuregcm.controllers.VerificationController;
|
||||
@@ -240,6 +240,9 @@ import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
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.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
@@ -262,8 +265,6 @@ import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MigrateDeletedAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MigrateRegistrationRecoveryPasswordsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
@@ -331,9 +332,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
|
||||
bootstrap.addCommand(new MigrateDeletedAccountsCommand());
|
||||
bootstrap.addCommand(new MigrateRegistrationRecoveryPasswordsCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -399,6 +397,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.workQueue(messageDeletionQueue).build();
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
clock,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getAccounts().getTableName(),
|
||||
@@ -477,12 +476,14 @@ 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 storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService virtualThreadEventLoggerExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "virtualThreadEventLogger-%d")).minThreads(1).maxThreads(1).build();
|
||||
ExecutorService asyncOperationQueueingExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
|
||||
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "secureValueRecoveryServiceRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
|
||||
@@ -563,6 +564,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.scheduledExecutorService(name(getClass(), "cloudflareTurnRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService messagePollExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "messagePollExecutor-%d")).threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "provisioningWebsocketTimeout-%d")).threads(1).build();
|
||||
|
||||
final ManagedNioEventLoopGroup dnsResolutionEventLoopGroup = new ManagedNioEventLoopGroup();
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.next())
|
||||
@@ -578,17 +581,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getSecureStorageServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator paymentsCredentialsGenerator = PaymentsController.credentialsGenerator(
|
||||
config.getPaymentsServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator artCredentialsGenerator = ArtController.credentialsGenerator(
|
||||
config.getArtServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator svr2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
config.getSvr2Configuration());
|
||||
ExternalServiceCredentialsGenerator svr3CredentialsGenerator = SecureValueRecovery3Controller.credentialsGenerator(
|
||||
config.getSvr3Configuration());
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers);
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
|
||||
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
|
||||
@@ -601,7 +600,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getKeyTransparencyServiceConfiguration().clientPrivateKey().value(),
|
||||
keyTransparencyCallbackExecutor);
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
secureValueRecovery2ServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
@@ -633,7 +632,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
PushNotificationManager pushNotificationManager =
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager =
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor);
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
|
||||
@@ -641,7 +640,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,
|
||||
@@ -656,8 +656,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
disconnectionRequestManager.addListener(webSocketConnectionEventManager);
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
|
||||
pushNotificationManager, rateLimiters);
|
||||
|
||||
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
|
||||
accountsManager);
|
||||
@@ -793,6 +793,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(
|
||||
@@ -1078,13 +1092,12 @@ 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),
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters),
|
||||
new ArtController(rateLimiters, artCredentialsGenerator),
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager),
|
||||
new ArchiveController(backupAuthManager, backupManager),
|
||||
@@ -1096,14 +1109,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),
|
||||
@@ -1116,13 +1132,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
new SecureValueRecovery3Controller(svr3CredentialsGenerator, accountsManager),
|
||||
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
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,
|
||||
@@ -1144,7 +1160,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager,
|
||||
disconnectionRequestManager));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(webSocketConnectionEventManager));
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
+7
-2
@@ -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");
|
||||
|
||||
+3
-13
@@ -22,7 +22,7 @@ import org.apache.commons.lang3.StringUtils;
|
||||
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;
|
||||
@@ -55,7 +55,6 @@ public class RegistrationLockVerificationManager {
|
||||
private final AccountsManager accounts;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator svr3CredentialGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
@@ -64,14 +63,12 @@ public class RegistrationLockVerificationManager {
|
||||
final AccountsManager accounts,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
|
||||
final ExternalServiceCredentialsGenerator svr3CredentialGenerator,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.accounts = accounts;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.svr2CredentialGenerator = svr2CredentialGenerator;
|
||||
this.svr3CredentialGenerator = svr3CredentialGenerator;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -156,7 +153,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();
|
||||
@@ -173,7 +170,7 @@ public class RegistrationLockVerificationManager {
|
||||
.entity(new RegistrationLockFailure(
|
||||
existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount),
|
||||
svr3FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
null))
|
||||
.build());
|
||||
}
|
||||
|
||||
@@ -187,11 +184,4 @@ public class RegistrationLockVerificationManager {
|
||||
return svr2CredentialGenerator.generateForUuid(account.getUuid());
|
||||
}
|
||||
|
||||
private @Nullable Svr3Credentials svr3FailureCredentials(final StoredRegistrationLock existingRegistrationLock, final Account account) {
|
||||
if (!existingRegistrationLock.needsFailureCredentials()) {
|
||||
return null;
|
||||
}
|
||||
final ExternalServiceCredentials creds = svr3CredentialGenerator.generateForUuid(account.getUuid());
|
||||
return new Svr3Credentials(creds.username(), creds.password(), account.getSvr3ShareSet());
|
||||
}
|
||||
}
|
||||
+22
-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,
|
||||
|
||||
+19
@@ -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) {}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import static org.apache.commons.lang3.ObjectUtils.firstNonNull;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record ArtServiceConfiguration(@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotNull SecretBytes userAuthenticationTokenUserIdSecret,
|
||||
@NotNull Duration tokenExpiration) {
|
||||
public ArtServiceConfiguration {
|
||||
tokenExpiration = firstNonNull(tokenExpiration, Duration.ofDays(1));
|
||||
}
|
||||
}
|
||||
+15
@@ -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) {}
|
||||
+18
@@ -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() {
|
||||
|
||||
+16
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record SecureValueRecovery3Configuration(
|
||||
@NotBlank String uri,
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@ExactlySize(32) SecretBytes userIdTokenSharedSecret,
|
||||
@NotEmpty List<@NotBlank String> svrCaCertificates,
|
||||
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull @Valid RetryConfiguration retry) {
|
||||
|
||||
public SecureValueRecovery3Configuration {
|
||||
if (circuitBreaker == null) {
|
||||
circuitBreaker = new CircuitBreakerConfiguration();
|
||||
}
|
||||
|
||||
if (retry == null) {
|
||||
retry = new RetryConfiguration();
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -22,7 +22,7 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private Map<String, DynamicPreRegistrationExperimentEnrollmentConfiguration> preRegistrationExperiments = Collections.emptyMap();
|
||||
private Map<String, DynamicE164ExperimentEnrollmentConfiguration> e164Experiments = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -66,7 +66,7 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false);
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -77,9 +77,9 @@ public class DynamicConfiguration {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
}
|
||||
|
||||
public Optional<DynamicPreRegistrationExperimentEnrollmentConfiguration> getPreRegistrationEnrollmentConfiguration(
|
||||
public Optional<DynamicE164ExperimentEnrollmentConfiguration> getE164ExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(preRegistrationExperiments.get(experimentName));
|
||||
return Optional.ofNullable(e164Experiments.get(experimentName));
|
||||
}
|
||||
|
||||
public Map<String, RateLimiterConfig> getLimits() {
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ import jakarta.validation.constraints.Min;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
public class DynamicPreRegistrationExperimentEnrollmentConfiguration {
|
||||
public class DynamicE164ExperimentEnrollmentConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
+4
-2
@@ -6,8 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
/**
|
||||
* @param enableLettuceRemoteTag - whether the `remote` tag should be added. Note: although this is dynamic, meters are
|
||||
* @param enableLettuceRemoteTag whether the `remote` tag should be added. Note: although this is dynamic, meters are
|
||||
* cached after creation, so changes will only affect servers launched after the change.
|
||||
* @param enableAwsSdkMetrics whether to record AWS SDK metrics. Note: although this is dynamic, meters are cached after
|
||||
* creation, so changes will only affect servers launched after the change.
|
||||
*/
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag) {
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics) {
|
||||
}
|
||||
+3
-19
@@ -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,31 +260,14 @@ 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));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/me")
|
||||
@Deprecated() // use whoami
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse getMe(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return buildAccountIdentityResponse(auth);
|
||||
registrationRecoveryPasswordsManager.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/whoami")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse whoAmI(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return buildAccountIdentityResponse(auth);
|
||||
}
|
||||
|
||||
private AccountIdentityResponse buildAccountIdentityResponse(AccountAndAuthenticatedDeviceHolder auth) {
|
||||
return new AccountIdentityResponse(auth.getAccount().getUuid(),
|
||||
auth.getAccount().getNumber(),
|
||||
auth.getAccount().getPhoneNumberIdentifier(),
|
||||
auth.getAccount().getUsernameHash().filter(h -> h.length > 0).orElse(null),
|
||||
auth.getAccount().getUsernameLinkHandle(),
|
||||
auth.getAccount().hasCapability(DeviceCapability.STORAGE));
|
||||
return AccountIdentityResponseBuilder.fromAccount(auth.getAccount());
|
||||
}
|
||||
|
||||
@DELETE
|
||||
|
||||
+4
-15
@@ -54,7 +54,6 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@@ -146,13 +145,7 @@ public class AccountControllerV2 {
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds());
|
||||
|
||||
return new AccountIdentityResponse(
|
||||
updatedAccount.getUuid(),
|
||||
updatedAccount.getNumber(),
|
||||
updatedAccount.getPhoneNumberIdentifier(),
|
||||
updatedAccount.getUsernameHash().orElse(null),
|
||||
updatedAccount.getUsernameLinkHandle(),
|
||||
updatedAccount.hasCapability(DeviceCapability.STORAGE));
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
@@ -205,13 +198,7 @@ public class AccountControllerV2 {
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds());
|
||||
|
||||
return new AccountIdentityResponse(
|
||||
updatedAccount.getUuid(),
|
||||
updatedAccount.getNumber(),
|
||||
updatedAccount.getPhoneNumberIdentifier(),
|
||||
updatedAccount.getUsernameHash().orElse(null),
|
||||
updatedAccount.getUsernameLinkHandle(),
|
||||
updatedAccount.hasCapability(DeviceCapability.STORAGE));
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
@@ -232,6 +219,8 @@ public class AccountControllerV2 {
|
||||
@Path("/phone_number_discoverability")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Sets whether the account should be discoverable by phone number in the directory.")
|
||||
@ApiResponse(responseCode = "204", description = "The setting was successfully updated.")
|
||||
public void setPhoneNumberDiscoverability(
|
||||
@Mutable @Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.Entitlements;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
|
||||
public class AccountIdentityResponseBuilder {
|
||||
|
||||
private final Account account;
|
||||
private boolean storageCapable;
|
||||
private Clock clock;
|
||||
|
||||
public AccountIdentityResponseBuilder(Account account) {
|
||||
this.account = account;
|
||||
this.storageCapable = account.hasCapability(DeviceCapability.STORAGE);
|
||||
this.clock = Clock.systemUTC();
|
||||
}
|
||||
|
||||
public AccountIdentityResponseBuilder storageCapable(boolean storageCapable) {
|
||||
this.storageCapable = storageCapable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AccountIdentityResponseBuilder clock(Clock clock) {
|
||||
this.clock = clock;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AccountIdentityResponse build() {
|
||||
final List<Entitlements.BadgeEntitlement> badges = account.getBadges()
|
||||
.stream()
|
||||
.filter(bv -> bv.expiration().isAfter(clock.instant()))
|
||||
.map(badge -> new Entitlements.BadgeEntitlement(badge.id(), badge.expiration(), badge.visible()))
|
||||
.toList();
|
||||
|
||||
final Entitlements.BackupEntitlement backupEntitlement = Optional
|
||||
.ofNullable(account.getBackupVoucher())
|
||||
.filter(bv -> bv.expiration().isAfter(clock.instant()))
|
||||
.map(bv -> new Entitlements.BackupEntitlement(bv.receiptLevel(), bv.expiration()))
|
||||
.orElse(null);
|
||||
|
||||
return new AccountIdentityResponse(account.getUuid(),
|
||||
account.getNumber(),
|
||||
account.getPhoneNumberIdentifier(),
|
||||
account.getUsernameHash().filter(h -> h.length > 0).orElse(null),
|
||||
account.getUsernameLinkHandle(),
|
||||
storageCapable,
|
||||
new Entitlements(badges, backupEntitlement));
|
||||
}
|
||||
|
||||
public static AccountIdentityResponse fromAccount(final Account account) {
|
||||
return new AccountIdentityResponseBuilder(account).build();
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/art")
|
||||
@Tag(name = "Art")
|
||||
public class ArtController {
|
||||
private final ExternalServiceCredentialsGenerator artServiceCredentialsGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final ArtServiceConfiguration cfg) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userAuthenticationTokenUserIdSecret())
|
||||
.prependUsername(false)
|
||||
.truncateSignature(false)
|
||||
.build();
|
||||
}
|
||||
|
||||
public ArtController(final RateLimiters rateLimiters,
|
||||
final ExternalServiceCredentialsGenerator artServiceCredentialsGenerator) {
|
||||
this.artServiceCredentialsGenerator = artServiceCredentialsGenerator;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(final @ReadOnly @Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validate(uuid);
|
||||
return artServiceCredentialsGenerator.generateForUuid(uuid);
|
||||
}
|
||||
}
|
||||
+293
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-13
@@ -65,9 +65,9 @@ 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.TransferArchiveResult;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
@@ -142,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
|
||||
@@ -399,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")
|
||||
@@ -550,7 +546,10 @@ public class DeviceController {
|
||||
archive when available.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Either a new transfer archive was uploaded for the authenticated device, or the upload has failed",
|
||||
content = @Content(schema = @Schema(implementation = TransferArchiveResult.class)))
|
||||
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")
|
||||
|
||||
+15
-10
@@ -123,13 +123,14 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.websocket.Stories;
|
||||
import org.whispersystems.websocket.WebsocketHeaders;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -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;
|
||||
@@ -268,10 +272,10 @@ public class MessageController {
|
||||
description="The message is not a story and some the recipient service ID does not correspond to a registered Signal user")
|
||||
@ApiResponse(
|
||||
responseCode = "409", description = "Incorrect set of devices supplied for recipient",
|
||||
content = @Content(schema = @Schema(implementation = AccountMismatchedDevices[].class)))
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
|
||||
@ApiResponse(
|
||||
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
|
||||
content = @Content(schema = @Schema(implementation = AccountStaleDevices[].class)))
|
||||
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
|
||||
@ApiResponse(
|
||||
responseCode="428",
|
||||
description="The sender should complete a challenge before proceeding")
|
||||
@@ -745,10 +749,10 @@ public class MessageController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<OutgoingMessageEntityList> getPendingMessages(@ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(Stories.X_SIGNAL_RECEIVE_STORIES) String receiveStoriesHeader,
|
||||
@HeaderParam(WebsocketHeaders.X_SIGNAL_RECEIVE_STORIES) String receiveStoriesHeader,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
|
||||
|
||||
boolean shouldReceiveStories = Stories.parseReceiveStoriesHeader(receiveStoriesHeader);
|
||||
boolean shouldReceiveStories = WebsocketHeaders.parseReceiveStoriesHeader(receiveStoriesHeader);
|
||||
|
||||
pushNotificationManager.handleMessagesRetrieved(auth.getAccount(), auth.getAuthenticatedDevice(), userAgent);
|
||||
|
||||
@@ -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);
|
||||
|
||||
+39
-5
@@ -10,6 +10,11 @@ import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.StringToClassMapItem;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
@@ -109,25 +114,54 @@ public class OneTimeDonationController {
|
||||
|
||||
public static class CreateBoostRequest {
|
||||
|
||||
@Schema(required = true, maxLength = 3, minLength = 3)
|
||||
@NotEmpty
|
||||
@ExactlySize(3)
|
||||
public String currency;
|
||||
|
||||
@Schema(required = true, minimum = "1", description = "The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)")
|
||||
@Min(1)
|
||||
public long amount;
|
||||
|
||||
@Schema(description = "The level for the boost payment. Assumed to be the boost level if missing")
|
||||
public Long level;
|
||||
|
||||
@Schema(description = "The payment method", defaultValue = "CARD")
|
||||
public PaymentMethod paymentMethod = PaymentMethod.CARD;
|
||||
}
|
||||
|
||||
public record CreateBoostResponse(String clientSecret) {}
|
||||
public record CreateBoostResponse(
|
||||
@Schema(description = "A client secret that can be used to complete a stripe PaymentIntent")
|
||||
String clientSecret) {}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a Stripe PaymentIntent with the requested amount and currency
|
||||
*/
|
||||
@POST
|
||||
@Path("/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Create a Stripe payment intent", description = """
|
||||
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
|
||||
|
||||
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Payment Intent created", content = @Content(schema = @Schema(implementation = CreateBoostResponse.class)))
|
||||
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
|
||||
@ApiResponse(responseCode = "400", description = """
|
||||
Invalid argument. The response body may include an error code with more specific information. If the error code
|
||||
is `amount_below_currency_minimum` the body will also include the `minimum` field indicating the minimum amount
|
||||
for the currency. If the error code is `amount_above_sepa_limit` the body will also include the `maximum`
|
||||
field indicating the maximum amount for a SEPA transaction.
|
||||
""",
|
||||
content = @Content(schema = @Schema(
|
||||
type = "object",
|
||||
properties = {
|
||||
@StringToClassMapItem(key = "error", value = String.class)
|
||||
})))
|
||||
@ApiResponse(responseCode = "409", description = "Provided level does not match the currency/amount combination",
|
||||
content = @Content(schema = @Schema(
|
||||
type = "object",
|
||||
properties = {
|
||||
@StringToClassMapItem(key = "error", value = String.class)
|
||||
})))
|
||||
public CompletableFuture<Response> createBoostPaymentIntent(
|
||||
@ReadOnly @Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid CreateBoostRequest request,
|
||||
|
||||
+6
-6
@@ -166,12 +166,12 @@ public class RegistrationController {
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
|
||||
return new AccountIdentityResponse(account.getUuid(),
|
||||
account.getNumber(),
|
||||
account.getPhoneNumberIdentifier(),
|
||||
account.getUsernameHash().orElse(null),
|
||||
account.getUsernameLinkHandle(),
|
||||
existingAccount.map(a -> a.hasCapability(DeviceCapability.STORAGE)).orElse(false));
|
||||
return new AccountIdentityResponseBuilder(account)
|
||||
// If there was an existing account, return whether it could have had something in the storage service
|
||||
.storageCapable(existingAccount
|
||||
.map(a -> a.hasCapability(DeviceCapability.STORAGE))
|
||||
.orElse(false))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.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.core.MediaType;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckResponseV3;
|
||||
import org.whispersystems.textsecuregcm.entities.SetShareSetRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.Svr3Credentials;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Optionals;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v3/backup")
|
||||
@Tag(name = "Secure Value Recovery")
|
||||
public class SecureValueRecovery3Controller {
|
||||
|
||||
private static final long MAX_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecovery3Configuration cfg) {
|
||||
return credentialsGenerator(cfg, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecovery3Configuration cfg,
|
||||
final Clock clock) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
|
||||
.prependUsername(false)
|
||||
.withDerivedUsernameTruncateLength(16)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}
|
||||
|
||||
private final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator;
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
public SecureValueRecovery3Controller(final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator,
|
||||
final AccountsManager accountsManager) {
|
||||
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Generate credentials for SVR3",
|
||||
description = """
|
||||
Generate SVR3 service credentials. Generated credentials have an expiration time of 30 days
|
||||
(however, the TTL is fully controlled by the server side and may change even for already generated credentials).
|
||||
|
||||
If a share-set has been previously set via /v3/backups/share-set, it will be included in the response
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials and share-set", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public Svr3Credentials getAuth(@ReadOnly @Auth final AuthenticatedDevice auth) {
|
||||
final ExternalServiceCredentials creds = backupServiceCredentialGenerator.generateFor(
|
||||
auth.getAccount().getUuid().toString());
|
||||
return new Svr3Credentials(creds.username(), creds.password(), auth.getAccount().getSvr3ShareSet());
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/share-set")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Set a share-set for the account",
|
||||
description = """
|
||||
Add a share-set to the account that can later be retrieved at v3/backups/auth or during registration. After
|
||||
storing a value with SVR3, clients must store the returned share-set so the value can be restored later.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "Successfully set share-set")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public void setShareSet(
|
||||
@Mutable @Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final SetShareSetRequest request) {
|
||||
accountsManager.update(auth.getAccount(), account -> account.setSvr3ShareSet(request.shareSet()));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/auth/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@RateLimitedByIp(RateLimiters.For.BACKUP_AUTH_CHECK)
|
||||
@Operation(
|
||||
summary = "Check SVR3 credentials",
|
||||
description = """
|
||||
Over time, clients may wind up with multiple sets of SVR3 authentication credentials in cloud storage.
|
||||
To determine which set is most current and should be used to communicate with SVR3 to retrieve a master key
|
||||
(from which a registration recovery password can be derived), clients should call this endpoint
|
||||
with a list of stored credentials. The response will identify which (if any) set of credentials are
|
||||
appropriate for communicating with SVR3.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with the check results.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "422", description = "Provided list of SVR3 credentials could not be parsed")
|
||||
@ApiResponse(responseCode = "400", description = "`POST` request body is not a valid `JSON`")
|
||||
public AuthCheckResponseV3 authCheck(@NotNull @Valid final AuthCheckRequest request) {
|
||||
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
|
||||
request.tokens(),
|
||||
backupServiceCredentialGenerator,
|
||||
MAX_AGE_SECONDS);
|
||||
|
||||
final Optional<Account> account = accountsManager.getByE164(request.number());
|
||||
|
||||
// the username associated with the provided number
|
||||
final Optional<String> matchingUsername = account
|
||||
.map(Account::getUuid)
|
||||
.map(backupServiceCredentialGenerator::generateForUuid)
|
||||
.map(ExternalServiceCredentials::username);
|
||||
|
||||
return new AuthCheckResponseV3(credentials.stream().collect(Collectors.toMap(
|
||||
ExternalServiceCredentialsSelector.CredentialInfo::token,
|
||||
info -> {
|
||||
if (!info.valid()) {
|
||||
// This isn't a valid credential (could be for a different SVR service, expired, etc)
|
||||
return AuthCheckResponseV3.Result.invalid();
|
||||
}
|
||||
final String credUsername = info.credentials().username();
|
||||
|
||||
return Optionals
|
||||
// If the account exists, and the account's username matches this credential's username, return a match
|
||||
.zipWith(account, matchingUsername.filter(credUsername::equals), (a, ignored) ->
|
||||
AuthCheckResponseV3.Result.match(a.getSvr3ShareSet()))
|
||||
// Otherwise, return no-match
|
||||
.orElseGet(AuthCheckResponseV3.Result::noMatch);
|
||||
}
|
||||
)));
|
||||
}
|
||||
}
|
||||
+16
@@ -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());
|
||||
}
|
||||
|
||||
@@ -701,6 +712,11 @@ public class SubscriptionController {
|
||||
// a missing customer ID indicates the client made requests out of order,
|
||||
// and needs to call create_payment_method to create a customer for the given payment method
|
||||
new ClientErrorException(Status.CONFLICT)))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
throw new ClientErrorException(Status.CONFLICT);
|
||||
}))
|
||||
.thenApply(customer -> Response.ok().build());
|
||||
}
|
||||
|
||||
|
||||
+120
-13
@@ -15,6 +15,13 @@ import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
@@ -68,6 +75,7 @@ import org.whispersystems.textsecuregcm.entities.VerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotification;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -83,6 +91,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 +125,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 +137,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 +148,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;
|
||||
@@ -148,7 +160,19 @@ public class VerificationController {
|
||||
@Path("/session")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid CreateVerificationSessionRequest request)
|
||||
@Operation(
|
||||
summary = "Creates a new verification session for a specific phone number",
|
||||
description = """
|
||||
Initiates a session to be able to verify the phone number for account registration. Check the response and
|
||||
submit requested information at PATCH /session/{sessionId}
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The verification session was created successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
|
||||
@@ -156,7 +180,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);
|
||||
}
|
||||
@@ -196,12 +220,28 @@ public class VerificationController {
|
||||
@Path("/session/{sessionId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Update a registration verification session",
|
||||
description = """
|
||||
Updates the session with requested information like an answer to a push challenge or captcha.
|
||||
If `requestedInformation` in the response is empty, and `allowedToRequestCode` is `true`, proceed to call
|
||||
`POST /session/{sessionId}/code`. If `requestedInformation` is empty and `allowedToRequestCode` is `false`,
|
||||
then the caller must create a new verification session.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Session was updated successfully with the information provided", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "The information provided was not accepted (e.g push challenge or captcha verification failed)")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse updateSession(
|
||||
@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Context ContainerRequestContext requestContext,
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest,
|
||||
@Context ContainerRequestContext context) {
|
||||
@Context final ContainerRequestContext requestContext,
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest) {
|
||||
|
||||
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
@@ -212,7 +252,7 @@ public class VerificationController {
|
||||
VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
final VerificationCheck verificationCheck = registrationFraudChecker.checkVerificationAttempt(
|
||||
context,
|
||||
requestContext,
|
||||
verificationSession,
|
||||
registrationServiceSession.number(),
|
||||
updateVerificationSessionRequest);
|
||||
@@ -429,6 +469,15 @@ public class VerificationController {
|
||||
@GET
|
||||
@Path("/session/{sessionId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get a registration verification session",
|
||||
description = """
|
||||
Retrieve metadata of the registration verification session with the specified ID
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Session was retrieved successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "422", description = "Malformed session ID encoding")
|
||||
public VerificationSessionResponse getSession(@PathParam("sessionId") final String encodedSessionId) {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
@@ -441,10 +490,45 @@ public class VerificationController {
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Request a verification code",
|
||||
description = """
|
||||
Sends a verification code to the phone number associated with the specified session via SMS or phone call.
|
||||
This endpoint can only be called when the session metadata includes "allowedToRequestCode = true"
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Verification code was successfully sent", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "409", description = "The session is already verified or not in a state to request a code because requested information hasn't been provided yet",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "418", description = "The request to send a verification code with the given transport could not be fulfilled, but may succeed with a different transport",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "422", description = "Request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = """
|
||||
Too may attempts; the caller is not permitted to send a verification code via the requested channel at this time
|
||||
and may need to wait before trying again; if the session metadata does not specify a time at which the caller may
|
||||
try again, then the caller has exhausted their permitted attempts and must either try a different transport or
|
||||
create a new verification session.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)
|
||||
))
|
||||
@ApiResponse(responseCode = "440", description = """
|
||||
The attempt to send a verification code failed because an external service (e.g. the SMS provider) refused to
|
||||
deliver the code. This may be a temporary or permanent failure, as indicated in the response body. If temporary,
|
||||
clients may try again after a reasonable delay. If permanent, clients should not retry the request and should
|
||||
communicate the permanent failure to the end user. Permanent failures may result in the server disallowing all
|
||||
future attempts to request or submit verification codes (since those attempts would be all but guaranteed to fail).
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = RegistrationServiceSenderExceptionMapper.SendVerificationCodeFailureResponse.class)))
|
||||
public VerificationSessionResponse requestVerificationCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) Optional<String> acceptLanguage,
|
||||
@NotNull @Valid VerificationCodeRequest verificationCodeRequest) throws Throwable {
|
||||
@Parameter(in = ParameterIn.HEADER, description = "Ordered list of languages in which the client prefers to receive SMS or voice verification messages") @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE)
|
||||
final Optional<String> acceptLanguage,
|
||||
@NotNull @Valid final VerificationCodeRequest verificationCodeRequest) throws Throwable {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
@@ -546,8 +630,31 @@ public class VerificationController {
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Submit a verification code",
|
||||
description = """
|
||||
Submits a verification code received via SMS or voice for verification
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = """
|
||||
The request to check a verification code was processed (though the submitted code may not be the correct code);
|
||||
the session metadata will indicate whether the submitted code was correct
|
||||
""", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID or verification code")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "409", description = "The session is already verified or no code has been requested yet for this session",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "429", description = """
|
||||
Too many attempts; the caller is not permitted to submit a verification code at this time and may need to wait
|
||||
before trying again; if the session metadata does not specify a time at which the caller may try again, then the
|
||||
caller has exhausted their permitted attempts and must create a new verification session.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
@@ -598,7 +705,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 +733,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 +751,7 @@ public class VerificationController {
|
||||
.orElseThrow(NotFoundException::new);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
return registrationServiceSession;
|
||||
|
||||
+4
-1
@@ -31,5 +31,8 @@ public record AccountIdentityResponse(
|
||||
@Nullable UUID usernameLinkHandle,
|
||||
|
||||
@Schema(description="whether any of this account's devices support storage")
|
||||
boolean storageCapable) {
|
||||
boolean storageCapable,
|
||||
|
||||
@Schema(description = "entitlements for this account and their current expirations")
|
||||
Entitlements entitlements) {
|
||||
}
|
||||
+2
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import org.whispersystems.textsecuregcm.util.E164;
|
||||
@@ -16,6 +17,7 @@ import org.whispersystems.textsecuregcm.util.E164;
|
||||
// https://github.com/FasterXML/jackson-databind/issues/1497
|
||||
public final class CreateVerificationSessionRequest {
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "The e164-formatted phone number to be verified")
|
||||
@E164
|
||||
@NotBlank
|
||||
@JsonProperty
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.InstantAdapter;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public record Entitlements(
|
||||
@Schema(description = "Active badges added via /v1/donation/redeem-receipt")
|
||||
List<BadgeEntitlement> badges,
|
||||
@Schema(description = "If present, the backup level set via /v1/archives/redeem-receipt")
|
||||
@Nullable BackupEntitlement backup) {
|
||||
|
||||
public record BadgeEntitlement(
|
||||
@Schema(description = "The badge id")
|
||||
String id,
|
||||
|
||||
@Schema(description = "When the badge expires, in number of seconds since epoch", implementation = Long.class)
|
||||
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
@JsonProperty("expirationSeconds")
|
||||
Instant expiration,
|
||||
|
||||
@Schema(description = "Whether the badge is currently configured to be visible")
|
||||
boolean visible) {
|
||||
}
|
||||
|
||||
public record BackupEntitlement(
|
||||
@Schema(description = "The backup level of the account")
|
||||
long backupLevel,
|
||||
|
||||
@Schema(description = "When the backup entitlement expires, in number of seconds since epoch", implementation = Long.class)
|
||||
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
@JsonProperty("expirationSeconds")
|
||||
Instant expiration) {
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -13,6 +14,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
|
||||
The verification code associated with this device. Must match the verification code
|
||||
provided by the server when provisioning this device.
|
||||
""")
|
||||
@NotBlank
|
||||
String verificationCode,
|
||||
|
||||
@Valid
|
||||
|
||||
+5
-2
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
|
||||
@Schema(description = """
|
||||
@@ -16,7 +17,9 @@ public record RegistrationLockFailure(
|
||||
@Schema(description = "Time remaining in milliseconds before the existing registration lock expires")
|
||||
long timeRemaining,
|
||||
@Schema(description = "Credentials that can be used with SVR2")
|
||||
@Nullable
|
||||
ExternalServiceCredentials svr2Credentials,
|
||||
@Schema(description = "Credentials that can be used with SVR3")
|
||||
Svr3Credentials svr3Credentials) {
|
||||
@Deprecated
|
||||
@Nullable
|
||||
ExternalServiceCredentials svr3Credentials) {
|
||||
}
|
||||
+5
-2
@@ -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) {
|
||||
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record SetShareSetRequest(
|
||||
@Schema(description = """
|
||||
A share-set generated by a client after storing a value in SVR3, serialized in un-padded standard base64
|
||||
""", implementation = String.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@NotEmpty
|
||||
@ExactlySize(SHARE_SET_SIZE)
|
||||
byte[] shareSet) {
|
||||
public static final int SHARE_SET_SIZE = 169;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
@Schema(description = """
|
||||
A time limited external service credential that can be used to authenticate and restore from SVR3.
|
||||
""")
|
||||
public record Svr3Credentials(
|
||||
|
||||
@Schema(description = "The credential username")
|
||||
String username,
|
||||
|
||||
@Schema(description = "The credential password")
|
||||
String password,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
If present, a shareSet previously stored for this account via /v3/backups/shareSet. Required to restore a value
|
||||
from SVR3. Encoded in standard un-padded base64.
|
||||
""", implementation = String.class)
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@Nullable byte[] shareSet) {}
|
||||
-4
@@ -14,8 +14,4 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
@JsonSubTypes.Type(value = RemoteAttachment.class, name = "success"),
|
||||
@JsonSubTypes.Type(value = RemoteAttachmentError.class, name = "error"),
|
||||
})
|
||||
@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 = {RemoteAttachmentError.class, RemoteAttachment.class})
|
||||
public sealed interface TransferArchiveResult permits RemoteAttachment, RemoteAttachmentError {}
|
||||
+4
@@ -25,4 +25,8 @@ public record TransferArchiveUploadedRequest(
|
||||
|
||||
@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) {}
|
||||
+18
-6
@@ -7,14 +7,26 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.annotation.Nullable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotification;
|
||||
|
||||
public record UpdateVerificationSessionRequest(@Nullable String pushToken,
|
||||
@Nullable PushTokenType pushTokenType,
|
||||
@Nullable String pushChallenge,
|
||||
@Nullable String captcha,
|
||||
@Nullable String mcc,
|
||||
@Nullable String mnc) {
|
||||
public record UpdateVerificationSessionRequest(
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "The APNs or FCM device token to which a push challenge can be sent")
|
||||
@Nullable String pushToken,
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "The type of push token")
|
||||
@Nullable PushTokenType pushTokenType,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Value received by the device in the push challenge")
|
||||
@Nullable String pushChallenge,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Captcha token returned after solving a captcha challenge")
|
||||
@Nullable String captcha,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Mobile country code of the phone subscriber")
|
||||
@Nullable String mcc,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Mobile network code of the phone subscriber")
|
||||
@Nullable String mnc) {
|
||||
|
||||
public enum PushTokenType {
|
||||
@JsonProperty("apn")
|
||||
|
||||
+6
-1
@@ -6,10 +6,15 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
|
||||
public record VerificationCodeRequest(@NotNull Transport transport, @NotNull String client) {
|
||||
public record VerificationCodeRequest(@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Transport via which to send the verification code")
|
||||
@NotNull Transport transport,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Client type to facilitate platform-specific SMS verification")
|
||||
@NotNull String client) {
|
||||
|
||||
public enum Transport {
|
||||
@JsonProperty("sms")
|
||||
|
||||
+22
-4
@@ -7,11 +7,29 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public record VerificationSessionResponse(String id, @Nullable Long nextSms, @Nullable Long nextCall,
|
||||
@Nullable Long nextVerificationAttempt, boolean allowedToRequestCode,
|
||||
List<VerificationSession.Information> requestedInformation,
|
||||
boolean verified) {
|
||||
public record VerificationSessionResponse(
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe ID for the session")
|
||||
String id,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next SMS can be requested for this session")
|
||||
@Nullable Long nextSms,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next voice call can be requested for this session")
|
||||
@Nullable Long nextCall,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which the client can submit a verification code for this session")
|
||||
@Nullable Long nextVerificationAttempt,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Whether it is allowed to request a verification code for this session")
|
||||
boolean allowedToRequestCode,
|
||||
|
||||
@Schema(description = "A list of requested information that the client needs to submit before requesting code delivery")
|
||||
List<VerificationSession.Information> requestedInformation,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Whether this session is verified")
|
||||
boolean verified) {
|
||||
|
||||
}
|
||||
+3
-3
@@ -12,7 +12,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPreRegistrationExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicE164ExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -73,8 +73,8 @@ public class ExperimentEnrollmentManager {
|
||||
|
||||
public boolean isEnrolled(final String e164, final String experimentName) {
|
||||
|
||||
final Optional<DynamicPreRegistrationExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager
|
||||
.getConfiguration().getPreRegistrationEnrollmentConfiguration(experimentName);
|
||||
final Optional<DynamicE164ExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager
|
||||
.getConfiguration().getE164ExperimentEnrollmentConfiguration(experimentName);
|
||||
|
||||
return maybeConfiguration.map(config -> {
|
||||
|
||||
|
||||
+2
-1
@@ -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());
|
||||
}
|
||||
}
|
||||
-10
@@ -16,21 +16,11 @@ import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.signal.chat.credentials.ExternalServiceType;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryV2ClientConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
|
||||
enum ExternalServiceDefinitions {
|
||||
ART(ExternalServiceType.EXTERNAL_SERVICE_TYPE_ART, (chatConfig, clock) -> {
|
||||
final ArtServiceConfiguration cfg = chatConfig.getArtServiceConfiguration();
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userAuthenticationTokenUserIdSecret())
|
||||
.prependUsername(false)
|
||||
.truncateSignature(false)
|
||||
.build();
|
||||
}),
|
||||
DIRECTORY(ExternalServiceType.EXTERNAL_SERVICE_TYPE_DIRECTORY, (chatConfig, clock) -> {
|
||||
final DirectoryV2ClientConfiguration cfg = chatConfig.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration();
|
||||
return ExternalServiceCredentialsGenerator
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2
-2
@@ -22,10 +22,10 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
public Response toResponse(final SubscriptionException exception) {
|
||||
|
||||
// Some exceptions have specific error body formats
|
||||
if (exception instanceof SubscriptionException.AmountTooSmall e) {
|
||||
if (exception instanceof SubscriptionException.InvalidAmount e) {
|
||||
return Response
|
||||
.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", "amount_too_small"))
|
||||
.entity(Map.of("error", e.getErrorCode()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -85,6 +85,8 @@ public class MetricsUtil {
|
||||
.percentiles(.75, .95, .99, .999)
|
||||
.build();
|
||||
|
||||
final String awsSdkMetricNamePrefix = MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class);
|
||||
|
||||
return config
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
@@ -108,7 +110,9 @@ public class MetricsUtil {
|
||||
return MeterFilter.super.map(id);
|
||||
}
|
||||
})
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MessageMetrics.DELIVERY_LATENCY_TIMER_NAME + ".percentile"));
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MessageMetrics.DELIVERY_LATENCY_TIMER_NAME + ".percentile"))
|
||||
.meterFilter(MeterFilter.deny(id -> !dynamicConfigurationManager.getConfiguration().getMetricsConfiguration().enableAwsSdkMetrics()
|
||||
&& id.getName().startsWith(awsSdkMetricNamePrefix)));
|
||||
}
|
||||
|
||||
public static void registerSystemResourceMetrics(final Environment environment) {
|
||||
|
||||
+3
-2
@@ -8,6 +8,7 @@ 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;
|
||||
@@ -102,13 +103,13 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
|
||||
|
||||
@Override
|
||||
public void publish(final MetricCollection metricCollection) {
|
||||
/* if (METRIC_COLLECTION_TYPE_API_CALL.equals(metricCollection.name())) {
|
||||
if (METRIC_COLLECTION_TYPE_API_CALL.equals(metricCollection.name())) {
|
||||
try {
|
||||
recordMetricsExecutorService.submit(() -> recordApiCallMetrics(metricCollection));
|
||||
} catch (final RejectedExecutionException ignored) {
|
||||
// This can happen if clients make new calls to an upstream service while the server is shutting down
|
||||
}
|
||||
} */
|
||||
}
|
||||
}
|
||||
|
||||
private void recordApiCallMetrics(final MetricCollection apiCallMetricCollection) {
|
||||
|
||||
+18
-8
@@ -23,10 +23,12 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -64,6 +66,10 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
private final FaultTolerantRedisClusterClient clusterClient;
|
||||
private final Executor listenerEventExecutor;
|
||||
|
||||
// Note that this MUST be a single-threaded executor; its function is to process tasks that should usually be
|
||||
// non-blocking, but can rarely block, and do so in the order in which those tasks were submitted.
|
||||
private final Executor asyncOperationQueueingExecutor;
|
||||
|
||||
@Nullable
|
||||
private FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubConnection;
|
||||
|
||||
@@ -102,13 +108,15 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
public WebSocketConnectionEventManager(final AccountsManager accountsManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final FaultTolerantRedisClusterClient clusterClient,
|
||||
final Executor listenerEventExecutor) {
|
||||
final Executor listenerEventExecutor,
|
||||
final Executor asyncOperationQueueingExecutor) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
|
||||
this.clusterClient = clusterClient;
|
||||
this.listenerEventExecutor = listenerEventExecutor;
|
||||
this.asyncOperationQueueingExecutor = asyncOperationQueueingExecutor;
|
||||
|
||||
this.listenersByAccountAndDeviceIdentifier =
|
||||
Metrics.gaugeMapSize(LISTENER_GAUGE_NAME, Tags.empty(), new ConcurrentHashMap<>());
|
||||
@@ -169,8 +177,9 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
|
||||
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
|
||||
(key, existingListener) -> {
|
||||
subscribeFuture.set(pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().ssubscribe(eventChannel)));
|
||||
subscribeFuture.set(CompletableFuture.supplyAsync(() -> pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().ssubscribe(eventChannel)), asyncOperationQueueingExecutor)
|
||||
.thenCompose(Function.identity()));
|
||||
|
||||
if (existingListener != null) {
|
||||
displacedListener.set(existingListener);
|
||||
@@ -223,9 +232,10 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
|
||||
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
|
||||
(ignored, existingListener) -> {
|
||||
unsubscribeFuture.set(pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().sunsubscribe(getClientEventChannel(accountIdentifier, deviceId)))
|
||||
.thenRun(Util.NOOP));
|
||||
unsubscribeFuture.set(CompletableFuture.supplyAsync(() -> pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().sunsubscribe(getClientEventChannel(accountIdentifier, deviceId)))
|
||||
.thenRun(Util.NOOP), asyncOperationQueueingExecutor)
|
||||
.thenCompose(Function.identity()));
|
||||
|
||||
return null;
|
||||
});
|
||||
@@ -295,9 +305,9 @@ public class WebSocketConnectionEventManager extends RedisClusterPubSubAdapter<b
|
||||
listenersByAccountAndDeviceIdentifier.compute(accountAndDeviceIdentifier, (ignored, existingListener) -> {
|
||||
if (existingListener == null && pubSubConnection != null) {
|
||||
// Enqueue, but do not block on, an "unsubscribe" operation
|
||||
pubSubConnection.usePubSubConnection(connection ->
|
||||
asyncOperationQueueingExecutor.execute(() -> pubSubConnection.usePubSubConnection(connection ->
|
||||
connection.async().sunsubscribe(getClientEventChannel(accountAndDeviceIdentifier.accountIdentifier(),
|
||||
accountAndDeviceIdentifier.deviceId())));
|
||||
accountAndDeviceIdentifier.deviceId()))));
|
||||
}
|
||||
|
||||
// Make no change to the existing listener whether present or absent
|
||||
|
||||
@@ -100,19 +100,6 @@ public class Account {
|
||||
@JsonProperty("inCds")
|
||||
private boolean discoverableByPhoneNumber = true;
|
||||
|
||||
/**
|
||||
* A share-set the account holder has stored.
|
||||
*
|
||||
* A share-set is generated when a client stores a value in SVR3, and should be stored here with the account. When
|
||||
* they later want to recover the value, they need their share-set and their secret pin. The share-set is not a secret
|
||||
* and, without the correct pin, is useless information.
|
||||
*
|
||||
* SVR3 share-sets are currently 167 bytes.
|
||||
*/
|
||||
@JsonProperty("svr3ss")
|
||||
@Nullable
|
||||
private byte[] svr3ShareSet;
|
||||
|
||||
@JsonProperty("bcr")
|
||||
@Nullable
|
||||
private byte[] messagesBackupCredentialRequest;
|
||||
@@ -485,14 +472,6 @@ public class Account {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public @Nullable byte[] getSvr3ShareSet() {
|
||||
return svr3ShareSet;
|
||||
}
|
||||
|
||||
public void setSvr3ShareSet(final byte[] svr3ShareSet) {
|
||||
this.svr3ShareSet = svr3ShareSet;
|
||||
}
|
||||
|
||||
public void setBackupCredentialRequests(final byte[] messagesBackupCredentialRequest,
|
||||
final byte[] mediaBackupCredentialRequest) {
|
||||
|
||||
|
||||
@@ -47,8 +47,6 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple3;
|
||||
import reactor.util.function.Tuples;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -59,7 +57,6 @@ import software.amazon.awssdk.services.dynamodb.model.Delete;
|
||||
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.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
@@ -82,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);
|
||||
|
||||
@@ -139,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";
|
||||
|
||||
@@ -162,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;
|
||||
@@ -171,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,
|
||||
@@ -183,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;
|
||||
@@ -194,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;
|
||||
@@ -242,11 +227,10 @@ 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 deletedAccountDeletePNI = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier());
|
||||
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier());
|
||||
|
||||
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
|
||||
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDeletePNI, deletedAccountDelete));
|
||||
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete));
|
||||
|
||||
writeItems.addAll(additionalWriteItems);
|
||||
|
||||
@@ -255,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);
|
||||
@@ -331,10 +315,6 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElse(null),
|
||||
existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElse(null));
|
||||
|
||||
// Carry over the old SVR3 share-set. This is required for an account to restore information from SVR. The share-
|
||||
// set is not a secret, if the new account claimer does not have the SVR3 pin, it is useless.
|
||||
accountToCreate.setSvr3ShareSet(existingAccount.getSvr3ShareSet());
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
|
||||
@@ -384,7 +364,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;
|
||||
@@ -440,12 +420,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));
|
||||
});
|
||||
maybeDisplacedAccountIdentifier.ifPresent(displacedAccountIdentifier ->
|
||||
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalPni)));
|
||||
|
||||
// The `catch (TransactionCanceledException) block needs to check whether the cancellation reason is the account
|
||||
// update write item
|
||||
@@ -481,7 +458,7 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.transactItems(writeItems)
|
||||
.build();
|
||||
|
||||
db().transactWriteItems(request);
|
||||
dynamoDbClient.transactWriteItems(request);
|
||||
|
||||
account.setVersion(account.getVersion() + 1);
|
||||
succeeded = true;
|
||||
@@ -606,7 +583,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 -> {
|
||||
@@ -615,7 +592,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);
|
||||
@@ -791,7 +768,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 -> {
|
||||
@@ -832,7 +809,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())
|
||||
@@ -881,7 +858,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);
|
||||
@@ -1012,7 +989,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;
|
||||
@@ -1062,7 +1039,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 -> {
|
||||
@@ -1073,7 +1050,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();
|
||||
}
|
||||
|
||||
@@ -1161,44 +1138,23 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.map(Accounts::fromItem)));
|
||||
}
|
||||
|
||||
private TransactWriteItem buildPutDeletedAccount(final UUID uuid, final String e164) {
|
||||
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(clock.instant().plus(DELETED_ACCOUNTS_TIME_TO_LIVE).getEpochSecond())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
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(pni.toString()),
|
||||
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) {
|
||||
return TransactWriteItem.builder()
|
||||
.delete(Delete.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164)))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private TransactWriteItem buildRemoveDeletedAccount(final UUID pni) {
|
||||
return TransactWriteItem.builder()
|
||||
.delete(Delete.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(pni.toString())))
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_PNI, AttributeValues.fromString(pni.toString())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
@@ -1210,34 +1166,24 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final String e164) {
|
||||
final GetItemResponse response = db().getItem(GetItemRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164)))
|
||||
.build());
|
||||
|
||||
return Optional.ofNullable(AttributeValues.getUUID(response.item(), DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, null));
|
||||
}
|
||||
|
||||
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final UUID phoneNumberIdentifier) {
|
||||
final GetItemResponse response = db().getItem(GetItemRequest.builder()
|
||||
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.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) {
|
||||
@@ -1245,9 +1191,10 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
return response.items().stream()
|
||||
.map(item -> item.get(DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s())
|
||||
.filter(e164OrPni -> e164OrPni.startsWith("+"))
|
||||
.findFirst();
|
||||
.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) {
|
||||
@@ -1259,7 +1206,6 @@ 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())
|
||||
));
|
||||
|
||||
@@ -1268,7 +1214,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);
|
||||
@@ -1285,7 +1231,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)
|
||||
@@ -1296,68 +1242,6 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.sequential();
|
||||
}
|
||||
|
||||
public Flux<Tuple3<String, UUID, Long>> getE164KeyedDeletedAccounts(final int segments, final Scheduler scheduler) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> asyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.consistentRead(true)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.build())
|
||||
.items())
|
||||
.map(item ->
|
||||
Tuples.of(
|
||||
item.get(DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s(),
|
||||
AttributeValues.getUUID(item, DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, null),
|
||||
AttributeValues.getLong(item, DELETED_ACCOUNTS_ATTR_EXPIRES, 0)))
|
||||
.filter(item -> item.getT1().startsWith("+"))
|
||||
.sequential();
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> insertPniDeletedAccount(final String e164, final UUID pni, final UUID aci, final long expiration) {
|
||||
// This happens under a pessimistic lock, but that wasn't taken before we found the record we want to migrate,
|
||||
// so make sure the e164 record is unchanged before updating the PNI record
|
||||
return asyncClient.getItem(GetItemRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164.toString())))
|
||||
.build())
|
||||
.thenComposeAsync(getItemResponse ->
|
||||
getItemResponse.hasItem()
|
||||
&& AttributeValues.getString(
|
||||
getItemResponse.item(), DELETED_ACCOUNTS_KEY_ACCOUNT_E164, "").equals(e164)
|
||||
&& AttributeValues.getUUID(
|
||||
getItemResponse.item(), DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, UUID.randomUUID()).equals(aci)
|
||||
&& AttributeValues.getLong(
|
||||
getItemResponse.item(), DELETED_ACCOUNTS_ATTR_EXPIRES, 0) == expiration
|
||||
? asyncClient.putItem(
|
||||
PutItemRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.item(
|
||||
Map.of(
|
||||
DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(pni.toString()),
|
||||
DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(aci),
|
||||
DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(expiration)))
|
||||
.conditionExpression("attribute_not_exists(#key)")
|
||||
.expressionAttributeNames(Map.of("#key", DELETED_ACCOUNTS_KEY_ACCOUNT_E164))
|
||||
.build())
|
||||
.thenApply(ignored -> true)
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) {
|
||||
// there was already a PNI record; no problem, do nothing
|
||||
return false;
|
||||
}
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
})
|
||||
: CompletableFuture.completedFuture(false));
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private Optional<Account> getByIndirectLookup(
|
||||
final Timer timer,
|
||||
@@ -1412,7 +1296,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)
|
||||
@@ -1422,7 +1306,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)
|
||||
@@ -1430,36 +1314,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")
|
||||
@@ -1481,7 +1338,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);
|
||||
});
|
||||
}
|
||||
|
||||
+20
-32
@@ -90,7 +90,6 @@ import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple3;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
|
||||
@@ -126,6 +125,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final ProfilesManager profilesManager;
|
||||
private final SecureStorageClient secureStorageClient;
|
||||
private final SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
@@ -277,7 +277,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return createTimer.record(() -> {
|
||||
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.
|
||||
@@ -385,7 +385,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
Metrics.counter(CREATE_COUNTER_NAME, tags).increment();
|
||||
|
||||
accountAttributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
|
||||
registrationRecoveryPasswordsManager.storeForCurrentNumber(account.getNumber(),
|
||||
registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI),
|
||||
registrationRecoveryPassword));
|
||||
}, accountLockExecutor);
|
||||
|
||||
@@ -654,16 +654,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
// 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;
|
||||
|
||||
@@ -1205,31 +1205,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
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) {
|
||||
return accounts.getAll(segments, scheduler);
|
||||
}
|
||||
|
||||
public Flux<Tuple3<String, UUID, Long>> getE164KeyedDeletedAccounts(final int segments, final Scheduler scheduler) {
|
||||
return accounts.getE164KeyedDeletedAccounts(segments, scheduler);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> migrateDeletedAccount(final String e164, final UUID aci, final long expiration) {
|
||||
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164)
|
||||
.thenCompose(
|
||||
pni -> accountLockManager.withLockAsync(
|
||||
List.of(pni),
|
||||
() -> accounts.insertPniDeletedAccount(e164, pni, aci, expiration),
|
||||
accountLockExecutor));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> delete(final Account account, final DeletionReason deletionReason) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
@@ -1262,24 +1249,25 @@ 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);
|
||||
}));
|
||||
|
||||
return CompletableFuture.allOf(
|
||||
secureStorageClient.deleteStoredData(account.getUuid()),
|
||||
deleteBackupFuture,
|
||||
svr2DeleteBackupFuture,
|
||||
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()));
|
||||
|
||||
+32
-18
@@ -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;
|
||||
@@ -36,23 +40,26 @@ import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
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 +78,23 @@ 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)")
|
||||
.updateExpression("SET #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 +109,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()));
|
||||
}
|
||||
|
||||
|
||||
+202
-24
@@ -10,14 +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 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.KeysAndAttributes;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
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
|
||||
@@ -35,8 +59,13 @@ 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;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PhoneNumberIdentifiers.class);
|
||||
|
||||
public PhoneNumberIdentifiers(final DynamoDbAsyncClient dynamoDbClient, final String tableName) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
@@ -44,38 +73,187 @@ public class PhoneNumberIdentifiers {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 CompletableFuture<UUID> getPhoneNumberIdentifier(final String phoneNumber) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
// 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);
|
||||
|
||||
return dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
|
||||
.projectionExpression(ATTR_PHONE_NUMBER_IDENTIFIER)
|
||||
.build())
|
||||
.thenCompose(response -> response.hasItem()
|
||||
? CompletableFuture.completedFuture(AttributeValues.getUUID(response.item(), ATTR_PHONE_NUMBER_IDENTIFIER, null))
|
||||
: generatePhoneNumberIdentifierIfNotExists(phoneNumber))
|
||||
.whenComplete((ignored, throwable) -> sample.stop(GET_PNI_TIMER));
|
||||
return retry(MAX_RETRIES, TransactionConflictException.class, () -> fetchPhoneNumbers(allPhoneNumberForms)
|
||||
.thenCompose(mappings -> setPniIfRequired(phoneNumber, allPhoneNumberForms, mappings)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
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);
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<UUID> generatePhoneNumberIdentifierIfNotExists(final String phoneNumber) {
|
||||
CompletableFuture<Map<String, UUID>> fetchPhoneNumbers(List<String> phoneNumbers) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return 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())
|
||||
.thenApply(response -> AttributeValues.getUUID(response.attributes(), ATTR_PHONE_NUMBER_IDENTIFIER, null))
|
||||
.whenComplete((ignored, throwable) -> sample.stop(SET_PNI_TIMER));
|
||||
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));
|
||||
}
|
||||
}
|
||||
+15
-156
@@ -16,28 +16,17 @@ 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.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple3;
|
||||
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.Delete;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Put;
|
||||
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.PutItemRequest;
|
||||
|
||||
public class RegistrationRecoveryPasswords {
|
||||
|
||||
// As a temporary transitional measure, this can be either a string representation of an E164-formatted phone number
|
||||
// or a UUID (PNI) string
|
||||
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";
|
||||
@@ -61,10 +50,10 @@ public class RegistrationRecoveryPasswords {
|
||||
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 -> Optional.ofNullable(getItemResponse.item())
|
||||
@@ -73,67 +62,26 @@ public class RegistrationRecoveryPasswords {
|
||||
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem));
|
||||
}
|
||||
|
||||
CompletableFuture<Optional<Pair<SaltedTokenHash, Long>>> lookupWithExpiration(final String key) {
|
||||
return asyncClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(key)))
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.thenApply(getItemResponse -> Optional.ofNullable(getItemResponse.item())
|
||||
.filter(item -> item.containsKey(ATTR_SALT))
|
||||
.filter(item -> item.containsKey(ATTR_HASH))
|
||||
.filter(item -> item.containsKey(ATTR_EXP))
|
||||
.map(item -> new Pair<>(saltedTokenHashFromItem(item), Long.parseLong(item.get(ATTR_EXP).n()))));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final UUID phoneNumberIdentifier) {
|
||||
return lookup(phoneNumberIdentifier.toString());
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> addOrReplace(final String number, final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
|
||||
public CompletableFuture<Void> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
|
||||
final long expirationSeconds = expirationSeconds();
|
||||
|
||||
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
|
||||
.transactItems(
|
||||
buildPutRecoveryPasswordWriteItem(number, expirationSeconds, data.salt(), data.hash()),
|
||||
buildPutRecoveryPasswordWriteItem(phoneNumberIdentifier.toString(), expirationSeconds, data.salt(), data.hash()))
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
private TransactWriteItem buildPutRecoveryPasswordWriteItem(final String key,
|
||||
final long expirationSeconds,
|
||||
final String salt,
|
||||
final String hash) {
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
return asyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_E164, AttributeValues.fromString(key),
|
||||
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
|
||||
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
|
||||
ATTR_SALT, AttributeValues.fromString(salt),
|
||||
ATTR_HASH, AttributeValues.fromString(hash)))
|
||||
ATTR_SALT, AttributeValues.fromString(data.salt()),
|
||||
ATTR_HASH, AttributeValues.fromString(data.hash())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> removeEntry(final String number, final UUID phoneNumberIdentifier) {
|
||||
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
|
||||
.transactItems(
|
||||
buildDeleteRecoveryPasswordWriteItem(number),
|
||||
buildDeleteRecoveryPasswordWriteItem(phoneNumberIdentifier.toString()))
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
private TransactWriteItem buildDeleteRecoveryPasswordWriteItem(final String key) {
|
||||
return TransactWriteItem.builder()
|
||||
.delete(Delete.builder()
|
||||
public CompletableFuture<Void> removeEntry(final UUID phoneNumberIdentifier) {
|
||||
return asyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(key)))
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.build())
|
||||
.build();
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -141,95 +89,6 @@ public class RegistrationRecoveryPasswords {
|
||||
return clock.instant().plus(expiration).getEpochSecond();
|
||||
}
|
||||
|
||||
public Flux<Tuple3<String, SaltedTokenHash, Long>> getE164AssociatedRegistrationRecoveryPasswords(final int segments, final Scheduler scheduler) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> asyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.filterExpression("begins_with(#key, :e164Prefix)")
|
||||
.expressionAttributeNames(Map.of("#key", KEY_E164))
|
||||
.expressionAttributeValues(Map.of(":e164Prefix", AttributeValue.fromS("+")))
|
||||
.build())
|
||||
.items()
|
||||
.map(item -> Tuples.of(item.get(KEY_E164).s(), saltedTokenHashFromItem(item), Long.parseLong(item.get(ATTR_EXP).n()))))
|
||||
.sequential();
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> insertPniRecord(final String phoneNumber,
|
||||
final UUID phoneNumberIdentifier,
|
||||
final SaltedTokenHash saltedTokenHash,
|
||||
final long expirationSeconds) {
|
||||
|
||||
// We try to write both the old and new record inside a transaction, but with different conditions. For the
|
||||
// E164-based record, we insist that the record be entirely unchanged. This prevents us from writing an out-of-sync
|
||||
// record if we read one thing in the `Scan` pass, but then somebody updated the record before we tried to write
|
||||
// the PNI-based record. We refresh and retry if this happens.
|
||||
//
|
||||
// For the PNI-based record, we only want to write the record if one doesn't already exist for the given PNI. If one
|
||||
// already exists, we'll just leave it alone.
|
||||
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
|
||||
.transactItems(
|
||||
TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_E164, AttributeValues.fromString(phoneNumber),
|
||||
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
|
||||
ATTR_SALT, AttributeValues.fromString(saltedTokenHash.salt()),
|
||||
ATTR_HASH, AttributeValues.fromString(saltedTokenHash.hash())))
|
||||
.conditionExpression("#key = :key AND #expiration = :expiration AND #salt = :salt AND #hash = :hash")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#key", KEY_E164,
|
||||
"#expiration", ATTR_EXP,
|
||||
"#salt", ATTR_SALT,
|
||||
"#hash", ATTR_HASH))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":key", AttributeValues.fromString(phoneNumber),
|
||||
":expiration", AttributeValues.fromLong(expirationSeconds),
|
||||
":salt", AttributeValues.fromString(saltedTokenHash.salt()),
|
||||
":hash", AttributeValues.fromString(saltedTokenHash.hash())))
|
||||
.build())
|
||||
.build(),
|
||||
|
||||
TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_E164, AttributeValues.fromString(phoneNumberIdentifier.toString()),
|
||||
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
|
||||
ATTR_SALT, AttributeValues.fromString(saltedTokenHash.salt()),
|
||||
ATTR_HASH, AttributeValues.fromString(saltedTokenHash.hash())))
|
||||
.conditionExpression("attribute_not_exists(#key)")
|
||||
.expressionAttributeNames(Map.of("#key", KEY_E164))
|
||||
.build())
|
||||
.build())
|
||||
.build())
|
||||
.thenApply(ignored -> true)
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException transactionCanceledException) {
|
||||
if ("ConditionalCheckFailed".equals(transactionCanceledException.cancellationReasons().get(1).code())) {
|
||||
// A PNI-associated record has already been stored; we can just treat this as success
|
||||
return false;
|
||||
}
|
||||
|
||||
if ("ConditionalCheckFailed".equals(transactionCanceledException.cancellationReasons().get(0).code())) {
|
||||
// No PNI-associated record is present, but the original record has changed
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
});
|
||||
}
|
||||
|
||||
private static SaltedTokenHash saltedTokenHashFromItem(final Map<String, AttributeValue> item) {
|
||||
return new SaltedTokenHash(item.get(ATTR_HASH).s(), item.get(ATTR_SALT).s());
|
||||
}
|
||||
|
||||
+19
-65
@@ -15,10 +15,6 @@ import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple3;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
|
||||
|
||||
public class RegistrationRecoveryPasswordsManager {
|
||||
@@ -26,17 +22,13 @@ public class RegistrationRecoveryPasswordsManager {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
|
||||
|
||||
private final RegistrationRecoveryPasswords registrationRecoveryPasswords;
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
|
||||
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers) {
|
||||
|
||||
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords) {
|
||||
this.registrationRecoveryPasswords = requireNonNull(registrationRecoveryPasswords);
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -46,65 +38,27 @@ 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 phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
|
||||
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswords.addOrReplace(number, phoneNumberIdentifier, tokenHash)
|
||||
.whenComplete((result, error) -> {
|
||||
if (error != null) {
|
||||
logger.warn("Failed to store Registration Recovery Password", error);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> removeForNumber(final String number) {
|
||||
return phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
|
||||
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswords.removeEntry(number, phoneNumberIdentifier)
|
||||
.whenComplete((ignored, error) -> {
|
||||
if (error instanceof ResourceNotFoundException) {
|
||||
// These will naturally happen if a recovery password is already deleted. Since we can remove
|
||||
// the recovery password through many flows, we avoid creating log messages for these exceptions
|
||||
} else if (error != null) {
|
||||
logger.warn("Failed to remove Registration Recovery Password", error);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public Flux<Tuple3<String, SaltedTokenHash, Long>> getE164AssociatedRegistrationRecoveryPasswords(final int segments, final Scheduler scheduler) {
|
||||
return registrationRecoveryPasswords.getE164AssociatedRegistrationRecoveryPasswords(segments, scheduler);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> migrateE164Record(final String number, final SaltedTokenHash saltedTokenHash, final long expirationSeconds) {
|
||||
return phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
|
||||
.thenCompose(phoneNumberIdentifier -> migrateE164Record(number, phoneNumberIdentifier, saltedTokenHash, expirationSeconds, 10));
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> migrateE164Record(final String number,
|
||||
final UUID phoneNumberIdentifier,
|
||||
final SaltedTokenHash saltedTokenHash,
|
||||
final long expirationSeconds,
|
||||
final int remainingAttempts) {
|
||||
|
||||
if (remainingAttempts <= 0) {
|
||||
return CompletableFuture.failedFuture(new ContestedOptimisticLockException());
|
||||
}
|
||||
|
||||
return registrationRecoveryPasswords.insertPniRecord(number, phoneNumberIdentifier, saltedTokenHash, expirationSeconds)
|
||||
.exceptionallyCompose(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException) {
|
||||
// Something about the original record changed; refresh and retry
|
||||
return registrationRecoveryPasswords.lookupWithExpiration(number)
|
||||
.thenCompose(maybePair -> maybePair
|
||||
.map(pair -> migrateE164Record(number, phoneNumberIdentifier, pair.first(), pair.second(), remainingAttempts - 1))
|
||||
.orElseGet(() -> {
|
||||
// The original record was deleted, and we can declare victory
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}));
|
||||
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash)
|
||||
.whenComplete((result, error) -> {
|
||||
if (error != null) {
|
||||
logger.warn("Failed to store Registration Recovery Password", error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return CompletableFuture.failedFuture(throwable);
|
||||
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
|
||||
// the recovery password through many flows, we avoid creating log messages for these exceptions
|
||||
} else if (error != null) {
|
||||
logger.warn("Failed to remove Registration Recovery Password", error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+8
-2
@@ -65,10 +65,16 @@ public class SubscriptionException extends Exception {
|
||||
}
|
||||
}
|
||||
|
||||
public static class AmountTooSmall extends InvalidArguments {
|
||||
public static class InvalidAmount extends InvalidArguments {
|
||||
private String errorCode;
|
||||
|
||||
public AmountTooSmall() {
|
||||
public InvalidAmount(String errorCode) {
|
||||
super(null, null);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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),
|
||||
|
||||
+265
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+304
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+7
@@ -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 {}
|
||||
+7
@@ -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 {}
|
||||
+16
@@ -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);
|
||||
}
|
||||
}
|
||||
+7
@@ -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 {}
|
||||
+12
@@ -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);
|
||||
}
|
||||
}
|
||||
+7
@@ -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 {}
|
||||
+18
-3
@@ -89,7 +89,15 @@ class BraintreeGraphqlClient {
|
||||
{
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
|
||||
extractApolloResponse(httpResponse, mutation);
|
||||
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
|
||||
if (data.createPayPalOneTimePayment == null) {
|
||||
logger.warn(
|
||||
"createPayPalOneTimePayment requestId={} did not have any errors but data was null. response={}",
|
||||
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"), httpResponse.body());
|
||||
throw new ServiceUnavailableException();
|
||||
}
|
||||
return data.createPayPalOneTimePayment;
|
||||
});
|
||||
}
|
||||
@@ -287,7 +295,12 @@ class BraintreeGraphqlClient {
|
||||
* Verifies that the HTTP response has a {@code 200} status code and the GraphQL response has no errors, otherwise
|
||||
* throws a {@link ServiceUnavailableException}.
|
||||
*/
|
||||
private <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractData(
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractData(
|
||||
HttpResponse<String> httpResponse, T operation) {
|
||||
return assertSuccessAndExtractDataFromApolloResponse(extractApolloResponse(httpResponse, operation));
|
||||
}
|
||||
|
||||
private static <T extends Operation<U>, U extends Operation.Data> ApolloResponse<U> extractApolloResponse(
|
||||
HttpResponse<String> httpResponse, T operation) {
|
||||
|
||||
if (httpResponse.statusCode() != 200) {
|
||||
@@ -296,8 +309,10 @@ class BraintreeGraphqlClient {
|
||||
throw new ServiceUnavailableException();
|
||||
}
|
||||
|
||||
ApolloResponse<U> response = Operations.parseJsonResponse(operation, httpResponse.body());
|
||||
return Operations.parseJsonResponse(operation, httpResponse.body());
|
||||
}
|
||||
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(final ApolloResponse<U> response) {
|
||||
if (response.hasErrors() || response.data == null) {
|
||||
//noinspection ConstantConditions
|
||||
response.errors.forEach(
|
||||
|
||||
+25
-21
@@ -9,6 +9,8 @@ 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.InvalidRequestException;
|
||||
import com.stripe.exception.StripeException;
|
||||
import com.stripe.model.Charge;
|
||||
import com.stripe.model.Customer;
|
||||
@@ -170,6 +172,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
try {
|
||||
stripeClient.customers().update(customerId, params, commonOptions());
|
||||
return null;
|
||||
} catch (InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidArguments(e.getMessage()));
|
||||
} catch (StripeException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
@@ -197,8 +202,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment intent. May throw a
|
||||
* {@link SubscriptionException.AmountTooSmall} if the amount is too small.
|
||||
* Creates a payment intent. May throw a {@link SubscriptionException.InvalidAmount} if stripe rejects the
|
||||
* attempt if the amount is too large or too small
|
||||
*/
|
||||
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
|
||||
final long amount,
|
||||
@@ -219,10 +224,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
try {
|
||||
return stripeClient.paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (StripeException e) {
|
||||
if ("amount_too_small".equalsIgnoreCase(e.getCode())) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.AmountTooSmall());
|
||||
} else {
|
||||
throw new CompletionException(e);
|
||||
final String errorCode = e.getCode().toLowerCase(Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small","amount_too_large" ->
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidAmount(errorCode));
|
||||
default -> throw new CompletionException(e);
|
||||
}
|
||||
}
|
||||
}, executor);
|
||||
@@ -292,14 +298,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 +352,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()));
|
||||
}
|
||||
@@ -534,9 +538,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,6 +26,8 @@ import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class Util {
|
||||
@@ -101,6 +105,145 @@ public class Util {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
// 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) {
|
||||
byte[] result = new byte[length];
|
||||
System.arraycopy(element, 0, result, 0, result.length);
|
||||
|
||||
+23
-3
@@ -7,10 +7,15 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
@@ -31,7 +36,7 @@ import org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
* a random, temporary "provisioning address," which it transmits via the newly-opened WebSocket. From there, the new
|
||||
* device generally displays the provisioning address (and a public key) as a QR code. After that, the primary device
|
||||
* will scan the QR code and send an encrypted provisioning message to the new device via
|
||||
* {@link org.whispersystems.textsecuregcm.controllers.ProvisioningController#sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)}.
|
||||
* {@link ProvisioningController#sendProvisioningMessage(AuthenticatedDevice, String, ProvisioningMessage, String)}.
|
||||
* Once the server receives the message from the primary device, it sends the message to the new device via the open
|
||||
* WebSocket, then closes the WebSocket connection.
|
||||
*/
|
||||
@@ -39,9 +44,15 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
|
||||
|
||||
private final ProvisioningManager provisioningManager;
|
||||
private final OpenWebSocketCounter openWebSocketCounter;
|
||||
private final ScheduledExecutorService timeoutExecutor;
|
||||
private final Duration timeout;
|
||||
|
||||
public ProvisioningConnectListener(final ProvisioningManager provisioningManager) {
|
||||
public ProvisioningConnectListener(final ProvisioningManager provisioningManager,
|
||||
final ScheduledExecutorService timeoutExecutor,
|
||||
final Duration timeout) {
|
||||
this.provisioningManager = provisioningManager;
|
||||
this.timeoutExecutor = timeoutExecutor;
|
||||
this.timeout = timeout;
|
||||
this.openWebSocketCounter = new OpenWebSocketCounter(MetricsUtil.name(getClass(), "openWebsockets"),
|
||||
MetricsUtil.name(getClass(), "sessionDuration"));
|
||||
}
|
||||
@@ -50,8 +61,17 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
|
||||
public void onWebSocketConnect(WebSocketSessionContext context) {
|
||||
openWebSocketCounter.countOpenWebSocket(context);
|
||||
|
||||
final Optional<ScheduledFuture<?>> maybeTimeoutFuture = context.getClient().supportsProvisioningSocketTimeouts()
|
||||
? Optional.of(timeoutExecutor.schedule(() ->
|
||||
context.getClient().close(1000, "Timeout"), timeout.toSeconds(), TimeUnit.SECONDS))
|
||||
: Optional.empty();
|
||||
|
||||
final String provisioningAddress = generateProvisioningAddress();
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> provisioningManager.removeListener(provisioningAddress));
|
||||
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
|
||||
provisioningManager.removeListener(provisioningAddress);
|
||||
maybeTimeoutFuture.ifPresent(future -> future.cancel(false));
|
||||
});
|
||||
|
||||
provisioningManager.addListener(provisioningAddress, message -> {
|
||||
assert message.getType() == PubSubProtos.PubSubMessage.Type.DELIVER;
|
||||
|
||||
+22
-6
@@ -50,6 +50,7 @@ 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;
|
||||
@@ -87,8 +88,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,
|
||||
@@ -138,6 +141,8 @@ record CommandDependencies(
|
||||
.maxThreads(16).minThreads(16).build();
|
||||
ExecutorService clientEventExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(name, "clientEvent-%d"));
|
||||
ExecutorService asyncOperationQueueingExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
|
||||
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(name, "disconnectionRequest-%d"));
|
||||
|
||||
@@ -152,7 +157,7 @@ record CommandDependencies(
|
||||
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
ExternalServiceCredentialsGenerator secureValueRecovery2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
configuration.getSvr2Configuration());
|
||||
|
||||
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
|
||||
@@ -174,6 +179,7 @@ record CommandDependencies(
|
||||
new ClientPublicKeys(dynamoDbAsyncClient, configuration.getDynamoDbTables().getClientPublicKeys().getTableName());
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
clock,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getAccounts().getTableName(),
|
||||
@@ -202,7 +208,7 @@ record CommandDependencies(
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
|
||||
redisClientResourcesBuilder);
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
secureValueRecoveryCredentialsGenerator, secureValueRecoveryServiceExecutor,
|
||||
secureValueRecovery2CredentialsGenerator, secureValueRecoveryServiceExecutor,
|
||||
secureValueRecoveryServiceRetryExecutor,
|
||||
configuration.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
@@ -223,7 +229,7 @@ record CommandDependencies(
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers);
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
@@ -251,6 +257,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,
|
||||
@@ -263,7 +277,7 @@ record CommandDependencies(
|
||||
Clock.systemUTC());
|
||||
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager =
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor);
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(disconnectionRequestManager);
|
||||
@@ -286,8 +300,10 @@ record CommandDependencies(
|
||||
pushSchedulerCluster,
|
||||
redisClientResourcesBuilder,
|
||||
backupManager,
|
||||
issuedReceiptsManager,
|
||||
dynamicConfigurationManager,
|
||||
dynamoDbAsyncClient
|
||||
dynamoDbAsyncClient,
|
||||
phoneNumberIdentifiers
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
public class MigrateDeletedAccountsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private static final String RECORDS_INSPECTED_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateDeletedAccountsCommand.class, "recordsInspected");
|
||||
|
||||
private static final String RECORDS_MIGRATED_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateDeletedAccountsCommand.class, "recordsMigrated");
|
||||
|
||||
private static final String DRY_RUN_TAG = "dryRun";
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private static final String SEGMENT_COUNT_ARGUMENT = "segments";
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
private static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
private static final int DEFAULT_SEGMENT_COUNT = 1;
|
||||
private static final int DEFAULT_CONCURRENCY = 16;
|
||||
|
||||
public MigrateDeletedAccountsCommand() {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "migrate-deleted-accounts", "Migrates recently-deleted account records from E164 to PNI-keyed schema");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--segments")
|
||||
.type(Integer.class)
|
||||
.dest(SEGMENT_COUNT_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_SEGMENT_COUNT)
|
||||
.help("The total number of segments for a DynamoDB scan");
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_CONCURRENCY)
|
||||
.help("Max concurrency for migrations.");
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don’t actually migrate any deleted accounts records");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
final int segments = namespace.getInt(SEGMENT_COUNT_ARGUMENT);
|
||||
final int concurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final boolean dryRun = namespace.getBoolean(DRY_RUN_ARGUMENT);
|
||||
|
||||
final String deletedAccountsTableName = configuration.getDynamoDbTables().getDeletedAccounts().getTableName();
|
||||
logger.info("Crawling deleted accounts with {} segments and {} processors",
|
||||
segments,
|
||||
Runtime.getRuntime().availableProcessors());
|
||||
|
||||
final Counter recordsInspectedCounter =
|
||||
Metrics.counter(RECORDS_INSPECTED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final Counter recordsMigratedCounter =
|
||||
Metrics.counter(RECORDS_MIGRATED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final AccountsManager accounts = commandDependencies.accountsManager();
|
||||
|
||||
accounts.getE164KeyedDeletedAccounts(segments, Schedulers.parallel())
|
||||
.doOnNext(tuple -> recordsInspectedCounter.increment())
|
||||
.flatMap(
|
||||
tuple -> dryRun
|
||||
? Mono.just(false)
|
||||
: Mono.fromFuture(
|
||||
accounts.migrateDeletedAccount(
|
||||
tuple.getT1(), tuple.getT2(), tuple.getT3())),
|
||||
concurrency)
|
||||
.filter(migrated -> migrated)
|
||||
.doOnNext(ignored -> recordsMigratedCounter.increment())
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.function.Tuple3;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class MigrateRegistrationRecoveryPasswordsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
private static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
private static final String SEGMENTS_ARGUMENT = "segments";
|
||||
private static final String BUFFER_ARGUMENT = "buffer";
|
||||
|
||||
private static final String RECORDS_INSPECTED_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateRegistrationRecoveryPasswordsCommand.class, "recordsInspected");
|
||||
|
||||
private static final String RECORDS_MIGRATED_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateRegistrationRecoveryPasswordsCommand.class, "recordsMigrated");
|
||||
|
||||
private static final String DRY_RUN_TAG = "dryRun";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MigrateRegistrationRecoveryPasswordsCommand.class);
|
||||
|
||||
public MigrateRegistrationRecoveryPasswordsCommand() {
|
||||
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "migrate-registration-recovery-passwords", "Migrate e164-based registration recovery passwords to PNI-based records");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don’t actually modify accounts with expired linked devices");
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(16)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--segments")
|
||||
.type(Integer.class)
|
||||
.dest(SEGMENTS_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(1)
|
||||
.help("The total number of segments for a DynamoDB scan");
|
||||
|
||||
subparser.addArgument("--buffer")
|
||||
.type(Integer.class)
|
||||
.dest(BUFFER_ARGUMENT)
|
||||
.setDefault(16_384)
|
||||
.help("Records to buffer");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
|
||||
final boolean dryRun = namespace.getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final int segments = namespace.getInt(SEGMENTS_ARGUMENT);
|
||||
final int bufferSize = namespace.getInt(BUFFER_ARGUMENT);
|
||||
|
||||
final Counter recordsInspectedCounter =
|
||||
Metrics.counter(RECORDS_INSPECTED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final Counter recordsMigratedCounter =
|
||||
Metrics.counter(RECORDS_MIGRATED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
commandDependencies.registrationRecoveryPasswordsManager();
|
||||
|
||||
registrationRecoveryPasswordsManager.getE164AssociatedRegistrationRecoveryPasswords(segments, Schedulers.parallel())
|
||||
.buffer(bufferSize)
|
||||
.map(source -> {
|
||||
final List<Tuple3<String, SaltedTokenHash, Long>> shuffled = new ArrayList<>(source);
|
||||
Collections.shuffle(shuffled);
|
||||
return shuffled;
|
||||
})
|
||||
.limitRate(2)
|
||||
.flatMapIterable(Function.identity())
|
||||
.doOnNext(tuple -> recordsInspectedCounter.increment())
|
||||
.flatMap(tuple -> {
|
||||
final String e164 = tuple.getT1();
|
||||
final SaltedTokenHash saltedTokenHash = tuple.getT2();
|
||||
final long expiration = tuple.getT3();
|
||||
|
||||
return dryRun
|
||||
? Mono.just(false)
|
||||
: Mono.fromFuture(() -> registrationRecoveryPasswordsManager.migrateE164Record(e164, saltedTokenHash, expiration))
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to migrate record for {}", e164, throwable);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.filter(migrated -> migrated)
|
||||
.doOnNext(ignored -> recordsMigratedCounter.increment())
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
}
|
||||
@@ -49,11 +49,10 @@ service ExternalServiceCredentialsAnonymous {
|
||||
|
||||
enum ExternalServiceType {
|
||||
EXTERNAL_SERVICE_TYPE_UNSPECIFIED = 0;
|
||||
EXTERNAL_SERVICE_TYPE_ART = 1;
|
||||
EXTERNAL_SERVICE_TYPE_DIRECTORY = 2;
|
||||
EXTERNAL_SERVICE_TYPE_PAYMENTS = 3;
|
||||
EXTERNAL_SERVICE_TYPE_STORAGE = 4;
|
||||
EXTERNAL_SERVICE_TYPE_SVR = 5;
|
||||
EXTERNAL_SERVICE_TYPE_DIRECTORY = 1;
|
||||
EXTERNAL_SERVICE_TYPE_PAYMENTS = 2;
|
||||
EXTERNAL_SERVICE_TYPE_STORAGE = 3;
|
||||
EXTERNAL_SERVICE_TYPE_SVR = 4;
|
||||
}
|
||||
|
||||
message GetExternalServiceCredentialsRequest {
|
||||
|
||||
+14
@@ -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-----
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package org.whispersystems.textsecuregcm;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
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 static org.whispersystems.textsecuregcm.filters.RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.Configuration;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.testing.junit5.DropwizardAppExtension;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.ServletRegistration;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.WebsocketHeaders;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
import org.whispersystems.websocket.messages.InvalidMessageException;
|
||||
import org.whispersystems.websocket.messages.WebSocketMessage;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
public class ProvisioningTimeoutIntegrationTest {
|
||||
|
||||
private static final DropwizardAppExtension<Configuration> DROPWIZARD_APP_EXTENSION =
|
||||
new DropwizardAppExtension<>(TestApplication.class);
|
||||
|
||||
|
||||
private WebSocketClient client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
client = new WebSocketClient();
|
||||
client.start();
|
||||
final TestApplication testApplication = DROPWIZARD_APP_EXTENSION.getApplication();
|
||||
reset(testApplication.scheduler);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
client.stop();
|
||||
}
|
||||
|
||||
public static class TestProvisioningListener extends TestWebsocketListener {
|
||||
CompletableFuture<String> provisioningAddressFuture = new CompletableFuture<>();
|
||||
|
||||
@Override
|
||||
public void onWebSocketBinary(final byte[] payload, final int offset, final int length) {
|
||||
try {
|
||||
WebSocketMessage webSocketMessage = messageFactory.parseMessage(payload, offset, length);
|
||||
if (Objects.requireNonNull(webSocketMessage.getType()) == WebSocketMessage.Type.REQUEST_MESSAGE
|
||||
&& webSocketMessage.getRequestMessage().getPath().equals("/v1/address")) {
|
||||
MessageProtos.ProvisioningAddress provisioningAddress =
|
||||
MessageProtos.ProvisioningAddress.parseFrom(webSocketMessage.getRequestMessage().getBody().orElseThrow());
|
||||
provisioningAddressFuture.complete(provisioningAddress.getAddress());
|
||||
return;
|
||||
}
|
||||
} catch (InvalidMessageException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
super.onWebSocketBinary(payload, offset, length);
|
||||
}
|
||||
}
|
||||
|
||||
public static class TestApplication extends Application<Configuration> {
|
||||
|
||||
ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
|
||||
|
||||
@Override
|
||||
public void run(final Configuration configuration, final Environment environment) throws Exception {
|
||||
final WebSocketConfiguration webSocketConfiguration = new WebSocketConfiguration();
|
||||
final WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment =
|
||||
new WebSocketEnvironment<>(environment, webSocketConfiguration);
|
||||
|
||||
environment.servlets()
|
||||
.addFilter("RemoteAddressFilter", new RemoteAddressFilter())
|
||||
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new ProvisioningConnectListener(mock(ProvisioningManager.class), scheduler, Duration.ofSeconds(5)));
|
||||
|
||||
final WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet =
|
||||
new WebSocketResourceProviderFactory<>(webSocketEnvironment, AuthenticatedDevice.class,
|
||||
webSocketConfiguration, REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
|
||||
final ServletRegistration.Dynamic websocketServlet = environment.servlets()
|
||||
.addServlet("WebSocket", webSocketServlet);
|
||||
websocketServlet.addMapping("/websocket");
|
||||
websocketServlet.setAsyncSupported(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void websocketTimeoutWithHeader() throws IOException {
|
||||
final TestProvisioningListener testWebsocketListener = new TestProvisioningListener();
|
||||
|
||||
final TestApplication testApplication = DROPWIZARD_APP_EXTENSION.getApplication();
|
||||
when(testApplication.scheduler.schedule(any(Runnable.class), anyLong(), any()))
|
||||
.thenReturn(mock(ScheduledFuture.class));
|
||||
|
||||
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
|
||||
upgradeRequest.setHeader(WebsocketHeaders.X_SIGNAL_WEBSOCKET_TIMEOUT_HEADER, "");
|
||||
try (Session ignored = client.connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
|
||||
upgradeRequest).join()) {
|
||||
|
||||
assertThat(testWebsocketListener.provisioningAddressFuture.join()).isNotNull();
|
||||
assertThat(testWebsocketListener.closeFuture()).isNotDone();
|
||||
|
||||
final ArgumentCaptor<Runnable> closeFunctionCaptor = ArgumentCaptor.forClass(Runnable.class);
|
||||
verify(testApplication.scheduler).schedule(closeFunctionCaptor.capture(), anyLong(), any());
|
||||
closeFunctionCaptor.getValue().run();
|
||||
|
||||
assertThat(testWebsocketListener.closeFuture())
|
||||
.succeedsWithin(Duration.ofSeconds(1))
|
||||
.isEqualTo(1000);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void websocketTimeoutNoHeader() throws IOException {
|
||||
final TestProvisioningListener testWebsocketListener = new TestProvisioningListener();
|
||||
|
||||
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
|
||||
try (Session ignored = client.connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
|
||||
upgradeRequest).join()) {
|
||||
assertThat(testWebsocketListener.closeFuture()).isNotDone();
|
||||
|
||||
final TestApplication testApplication = DROPWIZARD_APP_EXTENSION.getApplication();
|
||||
verify(testApplication.scheduler, never()).schedule(any(Runnable.class), anyLong(), any());
|
||||
assertThat(testWebsocketListener.closeFuture()).isNotDone();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void websocketTimeoutCancelled() throws IOException {
|
||||
final TestProvisioningListener testWebsocketListener = new TestProvisioningListener();
|
||||
|
||||
final TestApplication testApplication = DROPWIZARD_APP_EXTENSION.getApplication();
|
||||
@SuppressWarnings("unchecked") final ScheduledFuture<Void> scheduled = mock(ScheduledFuture.class);
|
||||
doReturn(scheduled).when(testApplication.scheduler).schedule(any(Runnable.class), anyLong(), any());
|
||||
|
||||
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
|
||||
upgradeRequest.setHeader(WebsocketHeaders.X_SIGNAL_WEBSOCKET_TIMEOUT_HEADER, "");
|
||||
final Session session = client.connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://127.0.0.1:%d/websocket", DROPWIZARD_APP_EXTENSION.getLocalPort())),
|
||||
upgradeRequest).join();
|
||||
|
||||
// Close the websocket, make sure the timeout is cancelled.
|
||||
session.close();
|
||||
assertThat(testWebsocketListener.closeFuture()).succeedsWithin(Duration.ofSeconds(1));
|
||||
verify(scheduled, times(1)).cancel(anyBoolean());
|
||||
}
|
||||
}
|
||||
+14
-12
@@ -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;
|
||||
@@ -49,15 +49,13 @@ class RegistrationLockVerificationManagerTest {
|
||||
private final DisconnectionRequestManager disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialsGenerator = mock(
|
||||
ExternalServiceCredentialsGenerator.class);
|
||||
private final ExternalServiceCredentialsGenerator svr3CredentialsGenerator = mock(
|
||||
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,
|
||||
svr3CredentialsGenerator, registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
|
||||
pushNotificationManager, rateLimiters);
|
||||
|
||||
private final RateLimiter pinLimiter = mock(RateLimiter.class);
|
||||
|
||||
@@ -103,14 +101,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 +125,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 +169,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());
|
||||
}
|
||||
|
||||
|
||||
+10
-10
@@ -125,18 +125,18 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testParsePreRegistrationExperiments() throws JsonProcessingException {
|
||||
void testParseE164Experiments() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true");
|
||||
final DynamicConfiguration emptyConfig =
|
||||
DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
assertFalse(emptyConfig.getPreRegistrationEnrollmentConfiguration("test").isPresent());
|
||||
assertFalse(emptyConfig.getE164ExperimentEnrollmentConfiguration("test").isPresent());
|
||||
}
|
||||
|
||||
{
|
||||
final String experimentConfigYaml = REQUIRED_CONFIG.concat("""
|
||||
preRegistrationExperiments:
|
||||
e164Experiments:
|
||||
percentageOnly:
|
||||
enrollmentPercentage: 17
|
||||
e164sCountryCodesAndPercentage:
|
||||
@@ -161,11 +161,11 @@ class DynamicConfigurationTest {
|
||||
final DynamicConfiguration config =
|
||||
DynamicConfigurationManager.parseConfiguration(experimentConfigYaml, DynamicConfiguration.class).orElseThrow();
|
||||
|
||||
assertFalse(config.getPreRegistrationEnrollmentConfiguration("unconfigured").isPresent());
|
||||
assertFalse(config.getE164ExperimentEnrollmentConfiguration("unconfigured").isPresent());
|
||||
|
||||
{
|
||||
final Optional<DynamicPreRegistrationExperimentEnrollmentConfiguration> percentageOnly = config
|
||||
.getPreRegistrationEnrollmentConfiguration("percentageOnly");
|
||||
final Optional<DynamicE164ExperimentEnrollmentConfiguration> percentageOnly = config
|
||||
.getE164ExperimentEnrollmentConfiguration("percentageOnly");
|
||||
assertTrue(percentageOnly.isPresent());
|
||||
assertEquals(17,
|
||||
percentageOnly.get().getEnrollmentPercentage());
|
||||
@@ -176,8 +176,8 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final Optional<DynamicPreRegistrationExperimentEnrollmentConfiguration> e164sCountryCodesAndPercentage = config
|
||||
.getPreRegistrationEnrollmentConfiguration("e164sCountryCodesAndPercentage");
|
||||
final Optional<DynamicE164ExperimentEnrollmentConfiguration> e164sCountryCodesAndPercentage = config
|
||||
.getE164ExperimentEnrollmentConfiguration("e164sCountryCodesAndPercentage");
|
||||
|
||||
assertTrue(e164sCountryCodesAndPercentage.isPresent());
|
||||
assertEquals(46,
|
||||
@@ -193,8 +193,8 @@ class DynamicConfigurationTest {
|
||||
}
|
||||
|
||||
{
|
||||
final Optional<DynamicPreRegistrationExperimentEnrollmentConfiguration> e164sAndExcludedCodes = config
|
||||
.getPreRegistrationEnrollmentConfiguration("e164sAndExcludedCodes");
|
||||
final Optional<DynamicE164ExperimentEnrollmentConfiguration> e164sAndExcludedCodes = config
|
||||
.getE164ExperimentEnrollmentConfiguration("e164sAndExcludedCodes");
|
||||
assertTrue(e164sAndExcludedCodes.isPresent());
|
||||
assertEquals(0, e164sAndExcludedCodes.get().getEnrollmentPercentage());
|
||||
assertEquals(Set.of("+120255551212"),
|
||||
|
||||
+29
-6
@@ -42,6 +42,7 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Stream;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
@@ -66,6 +67,7 @@ import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.ConfirmUsernameHashRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceName;
|
||||
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
|
||||
import org.whispersystems.textsecuregcm.entities.Entitlements;
|
||||
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashRequest;
|
||||
@@ -82,6 +84,7 @@ import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -321,17 +324,37 @@ class AccountControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/v1/accounts/whoami", "/v1/accounts/me"})
|
||||
void testWhoAmI(final String path) {
|
||||
@Test
|
||||
void testWhoAmI() {
|
||||
final Instant expiration = Instant.now().plus(Duration.ofHours(1)).plusMillis(101);
|
||||
final Instant truncatedExpiration = Instant.ofEpochSecond(expiration.getEpochSecond());
|
||||
final AccountBadge badge1 = new AccountBadge("badge1", expiration, true);
|
||||
final AccountBadge badge2 = new AccountBadge("badge2", expiration, true);
|
||||
|
||||
when(AuthHelper.VALID_ACCOUNT.getBackupVoucher())
|
||||
.thenReturn(new Account.BackupVoucher(100, expiration));
|
||||
when(AuthHelper.VALID_ACCOUNT.getBadges()).thenReturn(List.of(badge1, badge2));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target(path)
|
||||
.target("/v1/accounts/whoami")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.readEntity(AccountIdentityResponse.class).uuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
final AccountIdentityResponse identityResponse = response.readEntity(AccountIdentityResponse.class);
|
||||
assertThat(identityResponse.uuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
|
||||
final BiConsumer<Entitlements.BadgeEntitlement, AccountBadge> compareBadge = (actual, expected) -> {
|
||||
assertThat(actual.expiration()).isEqualTo(truncatedExpiration);
|
||||
assertThat(actual.id()).isEqualTo(expected.id());
|
||||
assertThat(actual.visible()).isEqualTo(expected.visible());
|
||||
};
|
||||
compareBadge.accept(identityResponse.entitlements().badges().getFirst(), badge1);
|
||||
compareBadge.accept(identityResponse.entitlements().badges().getLast(), badge2);
|
||||
|
||||
assertThat(identityResponse.entitlements().backup().backupLevel()).isEqualTo(100);
|
||||
assertThat(identityResponse.entitlements().backup().expiration()).isEqualTo(truncatedExpiration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -786,7 +809,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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-2
@@ -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();
|
||||
|
||||
@@ -401,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()))
|
||||
@@ -443,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));
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 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.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.Entitlements;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
class AccountIdentityResponseBuilderTest {
|
||||
|
||||
@Test
|
||||
void expiredBackupEntitlement() {
|
||||
final Instant expiration = Instant.ofEpochSecond(101);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(6, expiration));
|
||||
|
||||
Entitlements.BackupEntitlement backup = new AccountIdentityResponseBuilder(account)
|
||||
.clock(TestClock.pinned(Instant.ofEpochSecond(101)))
|
||||
.build().entitlements().backup();
|
||||
assertThat(backup).isNull();
|
||||
|
||||
backup = new AccountIdentityResponseBuilder(account)
|
||||
.clock(TestClock.pinned(Instant.ofEpochSecond(100)))
|
||||
.build().entitlements().backup();
|
||||
assertThat(backup).isNotNull();
|
||||
assertThat(backup.expiration()).isEqualTo(expiration);
|
||||
assertThat(backup.backupLevel()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredBadgeEntitlement() {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getBadges()).thenReturn(List.of(
|
||||
new AccountBadge("badge1", Instant.ofEpochSecond(10), false),
|
||||
new AccountBadge("badge2", Instant.ofEpochSecond(11), true)));
|
||||
|
||||
// all should be expired
|
||||
assertThat(new AccountIdentityResponseBuilder(account)
|
||||
.clock(TestClock.pinned(Instant.ofEpochSecond(11)))
|
||||
.build().entitlements().badges()).isEmpty();
|
||||
|
||||
// first badge should be expired
|
||||
assertThat(new AccountIdentityResponseBuilder(account).clock(TestClock.pinned(Instant.ofEpochSecond(10))).build()
|
||||
.entitlements()
|
||||
.badges()
|
||||
.stream().map(Entitlements.BadgeEntitlement::id).toList())
|
||||
.containsExactly("badge2");
|
||||
|
||||
// no badges should be expired
|
||||
assertThat(new AccountIdentityResponseBuilder(account).clock(TestClock.pinned(Instant.ofEpochSecond(9))).build()
|
||||
.entitlements()
|
||||
.badges()
|
||||
.stream().map(Entitlements.BadgeEntitlement::id).toList())
|
||||
.containsExactly("badge1", "badge2");
|
||||
}
|
||||
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
|
||||
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.time.Duration;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class ArtControllerTest {
|
||||
private static final ArtServiceConfiguration ART_SERVICE_CONFIGURATION = new ArtServiceConfiguration(
|
||||
randomSecretBytes(32), randomSecretBytes(32), Duration.ofDays(1));
|
||||
private static final ExternalServiceCredentialsGenerator artCredentialsGenerator = ArtController.credentialsGenerator(ART_SERVICE_CONFIGURATION);
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new ArtController(rateLimiters, artCredentialsGenerator))
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void testGetAuthToken() {
|
||||
MockUtils.updateRateLimiterResponseToAllow(rateLimiters, RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS, AuthHelper.VALID_UUID);
|
||||
final ExternalServiceCredentials token =
|
||||
resources.getJerseyTest()
|
||||
.target("/v1/art/auth")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(ExternalServiceCredentials.class);
|
||||
|
||||
assertThat(token.password()).isNotEmpty();
|
||||
assertThat(token.username()).isNotEmpty();
|
||||
}
|
||||
}
|
||||
+225
@@ -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));
|
||||
}
|
||||
}
|
||||
+62
-2
@@ -53,6 +53,7 @@ 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.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -66,6 +67,7 @@ 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;
|
||||
@@ -81,7 +83,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;
|
||||
@@ -113,7 +114,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();
|
||||
|
||||
@@ -180,6 +180,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")
|
||||
@@ -1316,4 +1347,33 @@ class DeviceControllerTest {
|
||||
assertEquals(400, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
@ValueSource(strings = {""})
|
||||
void linkDeviceMissingVerificationCode(final String verificationCode) {
|
||||
final AccountAttributes accountAttributes = new AccountAttributes(true, 1234, 5678, null,
|
||||
null, true, Set.of());
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest(verificationCode,
|
||||
accountAttributes,
|
||||
new DeviceActivationRequest(
|
||||
KeysHelper.signedECPreKey(1, aciIdentityKeyPair),
|
||||
KeysHelper.signedECPreKey(2, pniIdentityKeyPair),
|
||||
KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair),
|
||||
KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/link")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE))) {
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
-23
@@ -19,7 +19,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.anyBoolean;
|
||||
import static org.mockito.Mockito.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
@@ -121,6 +120,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;
|
||||
@@ -131,7 +131,7 @@ import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.websocket.Stories;
|
||||
import org.whispersystems.websocket.WebsocketHeaders;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
@@ -182,6 +182,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 +206,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 +287,7 @@ class MessageControllerTest {
|
||||
rateLimiters,
|
||||
rateLimiter,
|
||||
cardinalityEstimator,
|
||||
phoneNumberIdentifiers,
|
||||
pushNotificationManager,
|
||||
reportMessageManager
|
||||
);
|
||||
@@ -672,7 +674,7 @@ class MessageControllerTest {
|
||||
resources.getJerseyTest().target("/v1/messages/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header(Stories.X_SIGNAL_RECEIVE_STORIES, receiveStories ? "true" : "false")
|
||||
.header(WebsocketHeaders.X_SIGNAL_RECEIVE_STORIES, receiveStories ? "true" : "false")
|
||||
.header(HttpHeaders.USER_AGENT, userAgent)
|
||||
.accept(MediaType.APPLICATION_JSON_TYPE)
|
||||
.get(OutgoingMessageEntityList.class);
|
||||
@@ -807,7 +809,6 @@ class MessageControllerTest {
|
||||
|
||||
@Test
|
||||
void testReportMessageByE164() {
|
||||
|
||||
final String senderNumber = "+12125550001";
|
||||
final UUID senderAci = UUID.randomUUID();
|
||||
final UUID senderPni = UUID.randomUUID();
|
||||
@@ -820,8 +821,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 +834,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 +873,6 @@ class MessageControllerTest {
|
||||
|
||||
@Test
|
||||
void testReportMessageByAci() {
|
||||
|
||||
final String senderNumber = "+12125550001";
|
||||
final UUID senderAci = UUID.randomUUID();
|
||||
final UUID senderPni = UUID.randomUUID();
|
||||
@@ -872,8 +885,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 +899,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 +952,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 +972,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 +1015,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()
|
||||
|
||||
+11
-2
@@ -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));
|
||||
|
||||
-182
@@ -1,182 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
|
||||
|
||||
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.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckResponseV3;
|
||||
import org.whispersystems.textsecuregcm.entities.SetShareSetRequest;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
public class SecureValueRecovery3ControllerTest extends SecureValueRecoveryControllerBaseTest {
|
||||
|
||||
private static final SecureValueRecovery3Configuration CFG = new SecureValueRecovery3Configuration(
|
||||
"",
|
||||
randomSecretBytes(32),
|
||||
randomSecretBytes(32),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
|
||||
private static final MutableClock CLOCK = new MutableClock();
|
||||
|
||||
private static final ExternalServiceCredentialsGenerator CREDENTIAL_GENERATOR =
|
||||
SecureValueRecovery3Controller.credentialsGenerator(CFG, CLOCK);
|
||||
|
||||
private static final AccountsManager ACCOUNTS_MANAGER = mock(AccountsManager.class);
|
||||
private static final SecureValueRecovery3Controller CONTROLLER =
|
||||
new SecureValueRecovery3Controller(CREDENTIAL_GENERATOR, ACCOUNTS_MANAGER);
|
||||
|
||||
private static final ResourceExtension RESOURCES = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(CONTROLLER)
|
||||
.build();
|
||||
|
||||
protected SecureValueRecovery3ControllerTest() {
|
||||
super("/v3", ACCOUNTS_MANAGER, CLOCK, RESOURCES, CREDENTIAL_GENERATOR);
|
||||
}
|
||||
|
||||
@Override
|
||||
Map<String, CheckStatus> parseCheckResponse(final Response response) {
|
||||
final AuthCheckResponseV3 authCheckResponse = response.readEntity(AuthCheckResponseV3.class);
|
||||
|
||||
assertFalse(authCheckResponse.matches()
|
||||
.values().stream()
|
||||
.anyMatch(r -> r.status() == AuthCheckResponseV3.CredentialStatus.MATCH && r.shareSet() == null),
|
||||
"SVR3 matches must contain a non-empty share-set");
|
||||
|
||||
return authCheckResponse.matches().entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey, e -> switch (e.getValue().status()) {
|
||||
case MATCH -> CheckStatus.MATCH;
|
||||
case INVALID -> CheckStatus.INVALID;
|
||||
case NO_MATCH -> CheckStatus.NO_MATCH;
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
public static Stream<Arguments> checkShareSet() {
|
||||
byte[] shareSet = TestRandomUtil.nextBytes(100);
|
||||
return Stream.of(
|
||||
Arguments.of(shareSet, AuthCheckResponseV3.Result.match(shareSet)),
|
||||
Arguments.of(null, AuthCheckResponseV3.Result.match(null)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void checkShareSet(@Nullable byte[] shareSet, AuthCheckResponseV3.Result expectedResult) {
|
||||
final String e164 = "+18005550101";
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final String token = token(uuid, day(10));
|
||||
CLOCK.setTimeMillis(day(11));
|
||||
|
||||
final Account a = mock(Account.class);
|
||||
when(a.getUuid()).thenReturn(uuid);
|
||||
when(a.getSvr3ShareSet()).thenReturn(shareSet);
|
||||
when(ACCOUNTS_MANAGER.getByE164(e164)).thenReturn(Optional.of(a));
|
||||
|
||||
final AuthCheckRequest in = new AuthCheckRequest(e164, Collections.singletonList(token));
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v3/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity(in, MediaType.APPLICATION_JSON));
|
||||
|
||||
try (response) {
|
||||
assertEquals(200, response.getStatus());
|
||||
AuthCheckResponseV3 checkResponse = response.readEntity(AuthCheckResponseV3.class);
|
||||
assertEquals(checkResponse.matches().size(), 1);
|
||||
assertEquals(checkResponse.matches().get(token).status(), expectedResult.status());
|
||||
assertArrayEquals(checkResponse.matches().get(token).shareSet(), expectedResult.shareSet());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setShareSet() {
|
||||
final Account a = mock(Account.class);
|
||||
when(ACCOUNTS_MANAGER.update(any(), any())).thenAnswer(invocation -> {
|
||||
final Consumer<Account> updater = invocation.getArgument(1);
|
||||
updater.accept(a);
|
||||
return null;
|
||||
});
|
||||
|
||||
byte[] shareSet = TestRandomUtil.nextBytes(SetShareSetRequest.SHARE_SET_SIZE);
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v3/backup/share-set")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new SetShareSetRequest(shareSet), MediaType.APPLICATION_JSON));
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(a, times(1)).setSvr3ShareSet(eq(shareSet));
|
||||
}
|
||||
|
||||
static Stream<Arguments> requestParsing() {
|
||||
return Stream.of(
|
||||
Arguments.of("", 422),
|
||||
Arguments.of(null, 422),
|
||||
Arguments.of("abc**", 400), // bad base64
|
||||
Arguments.of(Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(SetShareSetRequest.SHARE_SET_SIZE - 1)), 422),
|
||||
Arguments.of(Base64.getEncoder().encodeToString(TestRandomUtil.nextBytes(SetShareSetRequest.SHARE_SET_SIZE)), 204));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void requestParsing(String shareSet, int responseCode) {
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v3/backup/share-set")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity("""
|
||||
{"shareSet": "%s"}
|
||||
""".formatted(shareSet), MediaType.APPLICATION_JSON));
|
||||
assertEquals(responseCode, response.getStatus());
|
||||
}
|
||||
}
|
||||
-1
@@ -319,7 +319,6 @@ abstract class SecureValueRecoveryControllerBaseTest {
|
||||
private static Account account(final UUID uuid) {
|
||||
final Account a = new Account();
|
||||
a.setUuid(uuid);
|
||||
a.setSvr3ShareSet(TestRandomUtil.nextBytes(100));
|
||||
return a;
|
||||
}
|
||||
}
|
||||
+54
-6
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-21
@@ -29,7 +29,7 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPreRegistrationExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicE164ExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
@@ -37,7 +37,7 @@ class ExperimentEnrollmentManagerTest {
|
||||
|
||||
private DynamicExperimentEnrollmentConfiguration.UuidSelector uuidSelector;
|
||||
private DynamicExperimentEnrollmentConfiguration experimentEnrollmentConfiguration;
|
||||
private DynamicPreRegistrationExperimentEnrollmentConfiguration preRegistrationExperimentEnrollmentConfiguration;
|
||||
private DynamicE164ExperimentEnrollmentConfiguration e164ExperimentEnrollmentConfiguration;
|
||||
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
@@ -66,18 +66,18 @@ class ExperimentEnrollmentManagerTest {
|
||||
|
||||
experimentEnrollmentConfiguration = mock(DynamicExperimentEnrollmentConfiguration.class);
|
||||
when(experimentEnrollmentConfiguration.getUuidSelector()).thenReturn(uuidSelector);
|
||||
preRegistrationExperimentEnrollmentConfiguration = mock(
|
||||
DynamicPreRegistrationExperimentEnrollmentConfiguration.class);
|
||||
e164ExperimentEnrollmentConfiguration = mock(
|
||||
DynamicE164ExperimentEnrollmentConfiguration.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getExperimentEnrollmentConfiguration(UUID_EXPERIMENT_NAME))
|
||||
.thenReturn(Optional.of(experimentEnrollmentConfiguration));
|
||||
when(dynamicConfiguration.getPreRegistrationEnrollmentConfiguration(E164_EXPERIMENT_NAME))
|
||||
.thenReturn(Optional.of(preRegistrationExperimentEnrollmentConfiguration));
|
||||
when(dynamicConfiguration.getE164ExperimentEnrollmentConfiguration(E164_EXPERIMENT_NAME))
|
||||
.thenReturn(Optional.of(e164ExperimentEnrollmentConfiguration));
|
||||
when(dynamicConfiguration.getExperimentEnrollmentConfiguration(E164_AND_UUID_EXPERIMENT_NAME))
|
||||
.thenReturn(Optional.of(experimentEnrollmentConfiguration));
|
||||
when(dynamicConfiguration.getPreRegistrationEnrollmentConfiguration(E164_AND_UUID_EXPERIMENT_NAME))
|
||||
.thenReturn(Optional.of(preRegistrationExperimentEnrollmentConfiguration));
|
||||
when(dynamicConfiguration.getE164ExperimentEnrollmentConfiguration(E164_AND_UUID_EXPERIMENT_NAME))
|
||||
.thenReturn(Optional.of(e164ExperimentEnrollmentConfiguration));
|
||||
|
||||
account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(ACCOUNT_UUID);
|
||||
@@ -127,11 +127,11 @@ class ExperimentEnrollmentManagerTest {
|
||||
|
||||
@Test
|
||||
void testIsEnrolled_E164AndUuidExperiment() {
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getIncludedCountryCodes()).thenReturn(Set.of("1"));
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(0);
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getEnrolledE164s()).thenReturn(Collections.emptySet());
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getExcludedE164s()).thenReturn(Collections.emptySet());
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getExcludedCountryCodes()).thenReturn(Collections.emptySet());
|
||||
when(e164ExperimentEnrollmentConfiguration.getIncludedCountryCodes()).thenReturn(Set.of("1"));
|
||||
when(e164ExperimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(0);
|
||||
when(e164ExperimentEnrollmentConfiguration.getEnrolledE164s()).thenReturn(Collections.emptySet());
|
||||
when(e164ExperimentEnrollmentConfiguration.getExcludedE164s()).thenReturn(Collections.emptySet());
|
||||
when(e164ExperimentEnrollmentConfiguration.getExcludedCountryCodes()).thenReturn(Collections.emptySet());
|
||||
|
||||
// test UUID enrollment is prioritized
|
||||
when(uuidSelector.getUuids()).thenReturn(Set.of(ACCOUNT_UUID));
|
||||
@@ -151,30 +151,30 @@ class ExperimentEnrollmentManagerTest {
|
||||
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(0);
|
||||
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
|
||||
assertFalse(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(100);
|
||||
when(e164ExperimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(100);
|
||||
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
|
||||
assertTrue(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testIsEnrolled_PreRegistrationExperiment(final String e164, final String experimentName,
|
||||
void testIsEnrolled_E164Experiment(final String e164, final String experimentName,
|
||||
final Set<String> enrolledE164s, final Set<String> excludedE164s, final Set<String> includedCountryCodes,
|
||||
final Set<String> excludedCountryCodes,
|
||||
final int enrollmentPercentage,
|
||||
final boolean expectEnrolled, final String message) {
|
||||
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getEnrolledE164s()).thenReturn(enrolledE164s);
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getExcludedE164s()).thenReturn(excludedE164s);
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(enrollmentPercentage);
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getIncludedCountryCodes()).thenReturn(includedCountryCodes);
|
||||
when(preRegistrationExperimentEnrollmentConfiguration.getExcludedCountryCodes()).thenReturn(excludedCountryCodes);
|
||||
when(e164ExperimentEnrollmentConfiguration.getEnrolledE164s()).thenReturn(enrolledE164s);
|
||||
when(e164ExperimentEnrollmentConfiguration.getExcludedE164s()).thenReturn(excludedE164s);
|
||||
when(e164ExperimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(enrollmentPercentage);
|
||||
when(e164ExperimentEnrollmentConfiguration.getIncludedCountryCodes()).thenReturn(includedCountryCodes);
|
||||
when(e164ExperimentEnrollmentConfiguration.getExcludedCountryCodes()).thenReturn(excludedCountryCodes);
|
||||
|
||||
assertEquals(expectEnrolled, experimentEnrollmentManager.isEnrolled(e164, experimentName), message);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
static Stream<Arguments> testIsEnrolled_PreRegistrationExperiment() {
|
||||
static Stream<Arguments> testIsEnrolled_E164Experiment() {
|
||||
return Stream.of(
|
||||
Arguments.of(ENROLLED_164, E164_EXPERIMENT_NAME, Collections.emptySet(), Collections.emptySet(),
|
||||
Collections.emptySet(), Collections.emptySet(), 0, false, "default configuration expects no enrollment"),
|
||||
|
||||
+6
-7
@@ -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
|
||||
|
||||
+7
-7
@@ -43,7 +43,7 @@ import reactor.core.publisher.Mono;
|
||||
public class ExternalServiceCredentialsGrpcServiceTest
|
||||
extends SimpleBaseGrpcTest<ExternalServiceCredentialsGrpcService, ExternalServiceCredentialsGrpc.ExternalServiceCredentialsBlockingStub> {
|
||||
|
||||
private static final ExternalServiceCredentialsGenerator ART_CREDENTIALS_GENERATOR = Mockito.spy(ExternalServiceCredentialsGenerator
|
||||
private static final ExternalServiceCredentialsGenerator DIRECTORY_CREDENTIALS_GENERATOR = Mockito.spy(ExternalServiceCredentialsGenerator
|
||||
.builder(TestRandomUtil.nextBytes(32))
|
||||
.withUserDerivationKey(TestRandomUtil.nextBytes(32))
|
||||
.prependUsername(false)
|
||||
@@ -62,14 +62,14 @@ public class ExternalServiceCredentialsGrpcServiceTest
|
||||
@Override
|
||||
protected ExternalServiceCredentialsGrpcService createServiceBeforeEachTest() {
|
||||
return new ExternalServiceCredentialsGrpcService(Map.of(
|
||||
ExternalServiceType.EXTERNAL_SERVICE_TYPE_ART, ART_CREDENTIALS_GENERATOR,
|
||||
ExternalServiceType.EXTERNAL_SERVICE_TYPE_DIRECTORY, DIRECTORY_CREDENTIALS_GENERATOR,
|
||||
ExternalServiceType.EXTERNAL_SERVICE_TYPE_PAYMENTS, PAYMENTS_CREDENTIALS_GENERATOR
|
||||
), rateLimiters);
|
||||
}
|
||||
|
||||
static Stream<Arguments> testSuccess() {
|
||||
return Stream.of(
|
||||
Arguments.of(ExternalServiceType.EXTERNAL_SERVICE_TYPE_ART, ART_CREDENTIALS_GENERATOR),
|
||||
Arguments.of(ExternalServiceType.EXTERNAL_SERVICE_TYPE_DIRECTORY, DIRECTORY_CREDENTIALS_GENERATOR),
|
||||
Arguments.of(ExternalServiceType.EXTERNAL_SERVICE_TYPE_PAYMENTS, PAYMENTS_CREDENTIALS_GENERATOR)
|
||||
);
|
||||
}
|
||||
@@ -111,14 +111,14 @@ public class ExternalServiceCredentialsGrpcServiceTest
|
||||
public void testRateLimitExceeded() throws Exception {
|
||||
final Duration retryAfter = MockUtils.updateRateLimiterResponseToFail(
|
||||
rateLimiters, RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS, AUTHENTICATED_ACI, Duration.ofSeconds(100));
|
||||
Mockito.reset(ART_CREDENTIALS_GENERATOR);
|
||||
Mockito.reset(DIRECTORY_CREDENTIALS_GENERATOR);
|
||||
assertRateLimitExceeded(
|
||||
retryAfter,
|
||||
() -> authenticatedServiceStub().getExternalServiceCredentials(
|
||||
GetExternalServiceCredentialsRequest.newBuilder()
|
||||
.setExternalService(ExternalServiceType.EXTERNAL_SERVICE_TYPE_ART)
|
||||
.setExternalService(ExternalServiceType.EXTERNAL_SERVICE_TYPE_DIRECTORY)
|
||||
.build()),
|
||||
ART_CREDENTIALS_GENERATOR
|
||||
DIRECTORY_CREDENTIALS_GENERATOR
|
||||
);
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ public class ExternalServiceCredentialsGrpcServiceTest
|
||||
public void testUnauthenticatedCall() throws Exception {
|
||||
assertStatusUnauthenticated(() -> unauthenticatedServiceStub().getExternalServiceCredentials(
|
||||
GetExternalServiceCredentialsRequest.newBuilder()
|
||||
.setExternalService(ExternalServiceType.EXTERNAL_SERVICE_TYPE_ART)
|
||||
.setExternalService(ExternalServiceType.EXTERNAL_SERVICE_TYPE_DIRECTORY)
|
||||
.build()));
|
||||
}
|
||||
|
||||
|
||||
+24
-5
@@ -36,21 +36,21 @@ class MetricsUtilTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void lettuceTagRejection(final boolean enableLettuceRemoteTag) {
|
||||
DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(enableLettuceRemoteTag);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(enableLettuceRemoteTag, false);
|
||||
when(dynamicConfiguration.getMetricsConfiguration()).thenReturn(metricsConfiguration);
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
MeterRegistry registry = new SimpleMeterRegistry();
|
||||
final MeterRegistry registry = new SimpleMeterRegistry();
|
||||
MetricsUtil.configureMeterFilters(registry.config(), dynamicConfigurationManager);
|
||||
|
||||
registry.counter("lettuce.command.completion.max", "command", "hello", "remote", "world", "allowed", "!").increment();
|
||||
final List<Meter> meters = registry.getMeters();
|
||||
assertThat(meters).hasSize(1);
|
||||
|
||||
Meter meter = meters.get(0);
|
||||
final Meter meter = meters.getFirst();
|
||||
assertThat(meter.getId().getName()).isEqualTo("chat.lettuce.command.completion.max");
|
||||
assertThat(meter.getId().getTag("command")).isNull();
|
||||
AbstractStringAssert<?> remoteTag = assertThat(meter.getId().getTag("remote"));
|
||||
@@ -62,4 +62,23 @@ class MetricsUtilTest {
|
||||
}
|
||||
assertThat(meter.getId().getTag("allowed")).isNotNull();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void awsSdkMetricRejection(final boolean enableAwsSdkMetrics) {
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, enableAwsSdkMetrics);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getMetricsConfiguration()).thenReturn(metricsConfiguration);
|
||||
|
||||
final MeterRegistry registry = new SimpleMeterRegistry();
|
||||
MetricsUtil.configureMeterFilters(registry.config(), dynamicConfigurationManager);
|
||||
registry.counter("chat.MicrometerAwsSdkMetricPublisher.days_since_last_incident").increment();
|
||||
|
||||
assertThat(registry.getMeters()).hasSize(enableAwsSdkMetrics ? 1 : 0);
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -51,6 +51,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
private WebSocketConnectionEventManager remoteEventManager;
|
||||
|
||||
private static ExecutorService webSocketConnectionEventExecutor;
|
||||
private static ExecutorService asyncOperationQueueingExecutor;
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
@@ -73,6 +74,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
webSocketConnectionEventExecutor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
asyncOperationQueueingExecutor = Executors.newSingleThreadExecutor();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@@ -80,12 +82,14 @@ class WebSocketConnectionEventManagerTest {
|
||||
localEventManager = new WebSocketConnectionEventManager(mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
webSocketConnectionEventExecutor);
|
||||
webSocketConnectionEventExecutor,
|
||||
asyncOperationQueueingExecutor);
|
||||
|
||||
remoteEventManager = new WebSocketConnectionEventManager(mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
webSocketConnectionEventExecutor);
|
||||
webSocketConnectionEventExecutor,
|
||||
asyncOperationQueueingExecutor);
|
||||
|
||||
localEventManager.start();
|
||||
remoteEventManager.start();
|
||||
@@ -100,6 +104,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() {
|
||||
webSocketConnectionEventExecutor.shutdown();
|
||||
asyncOperationQueueingExecutor.shutdown();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -242,6 +247,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
clusterClient,
|
||||
Runnable::run,
|
||||
Runnable::run);
|
||||
|
||||
eventManager.start();
|
||||
@@ -309,6 +315,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
mock(AccountsManager.class),
|
||||
mock(PushNotificationManager.class),
|
||||
clusterClient,
|
||||
Runnable::run,
|
||||
Runnable::run);
|
||||
|
||||
eventManager.start();
|
||||
@@ -366,6 +373,7 @@ class WebSocketConnectionEventManagerTest {
|
||||
accountsManager,
|
||||
pushNotificationManager,
|
||||
clusterClient,
|
||||
Runnable::run,
|
||||
Runnable::run);
|
||||
|
||||
eventManager.start();
|
||||
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user