mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 05:26:47 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a4a55c245 | ||
|
|
f4a243861c | ||
|
|
68209f270e | ||
|
|
8af939d320 | ||
|
|
16a50935ea | ||
|
|
24ea10c451 | ||
|
|
95abda4870 | ||
|
|
c8993c4da8 | ||
|
|
d096798340 | ||
|
|
f2f5e0e26f | ||
|
|
9121032114 | ||
|
|
541bf968e5 | ||
|
|
8c3ebdcbab | ||
|
|
0593e9e89f | ||
|
|
0d412c88fd | ||
|
|
8280106493 | ||
|
|
a3e106fe04 | ||
|
|
981a04f33b | ||
|
|
26025e5abd | ||
|
|
4839a5ba70 | ||
|
|
85a1550485 | ||
|
|
77658415b2 | ||
|
|
68f27be7cd |
No files matched your search
@@ -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=
|
||||
|
||||
|
||||
@@ -219,37 +219,6 @@ svr2:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
svr3:
|
||||
backend1Uri: backend1.example.com
|
||||
backend2Uri: backend2.example.com
|
||||
backend3Uri: backend3.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:
|
||||
@@ -362,10 +331,6 @@ paymentsService:
|
||||
coinMarketCapCurrencyIds:
|
||||
MOB: 7878
|
||||
|
||||
artService:
|
||||
userAuthenticationTokenSharedSecret: secret://artService.userAuthenticationTokenSharedSecret
|
||||
userAuthenticationTokenUserIdSecret: secret://artService.userAuthenticationTokenUserIdSecret
|
||||
|
||||
badges:
|
||||
badges:
|
||||
- id: TEST
|
||||
|
||||
-18
@@ -17,7 +17,6 @@ import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
@@ -52,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;
|
||||
@@ -157,10 +155,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private SecureValueRecovery2Configuration svr2;
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private SecureValueRecovery3Configuration svr3;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -222,11 +216,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ArtServiceConfiguration artService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -410,9 +399,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public SecureValueRecovery2Configuration getSvr2Configuration() {
|
||||
return svr2;
|
||||
}
|
||||
public SecureValueRecovery3Configuration getSvr3Configuration() {
|
||||
return svr3;
|
||||
}
|
||||
|
||||
public DirectoryV2Configuration getDirectoryV2Configuration() {
|
||||
return directoryV2;
|
||||
@@ -477,10 +463,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return paymentsService;
|
||||
}
|
||||
|
||||
public ArtServiceConfiguration getArtServiceConfiguration() {
|
||||
return artService;
|
||||
}
|
||||
|
||||
public ZkConfig getZkConfig() {
|
||||
return zkConfig;
|
||||
}
|
||||
|
||||
@@ -108,7 +108,6 @@ 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;
|
||||
@@ -131,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;
|
||||
@@ -177,6 +175,7 @@ import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMa
|
||||
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
@@ -206,7 +205,6 @@ import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
@@ -216,9 +214,6 @@ import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountPrincipalSupplier;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientPublicKeys;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
|
||||
@@ -246,6 +241,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;
|
||||
@@ -481,8 +479,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.maxThreads(32).minThreads(32).workQueue(fcmSenderQueue).build();
|
||||
ExecutorService secureValueRecovery2ServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "secureValueRecoveryService2-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService secureValueRecovery3ServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "secureValueRecoveryService3-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService virtualThreadEventLoggerExecutor = environment.lifecycle()
|
||||
@@ -569,6 +565,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())
|
||||
@@ -584,12 +582,8 @@ 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);
|
||||
@@ -608,8 +602,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
keyTransparencyCallbackExecutor);
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
|
||||
secureValueRecovery2ServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
SecureValueRecovery3Client secureValueRecovery3Client = new SecureValueRecovery3Client(svr3CredentialsGenerator,
|
||||
secureValueRecovery3ServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr3Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
@@ -630,7 +622,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, secureValueRecovery3Client, disconnectionRequestManager,
|
||||
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
|
||||
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
@@ -665,8 +657,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);
|
||||
@@ -1107,7 +1099,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
usernameHashZkProofVerifier),
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters),
|
||||
new ArtController(rateLimiters, artCredentialsGenerator),
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager),
|
||||
new ArchiveController(backupAuthManager, backupManager),
|
||||
@@ -1142,7 +1133,6 @@ 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()),
|
||||
@@ -1171,7 +1161,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());
|
||||
@@ -1223,6 +1213,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ServerRejectedExceptionMapper(),
|
||||
new ImpossiblePhoneNumberExceptionMapper(),
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new ObsoletePhoneNumberFormatExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
|
||||
+1
-12
@@ -22,7 +22,6 @@ 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;
|
||||
@@ -56,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;
|
||||
@@ -65,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;
|
||||
@@ -174,7 +170,7 @@ public class RegistrationLockVerificationManager {
|
||||
.entity(new RegistrationLockFailure(
|
||||
existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount),
|
||||
svr3FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
null))
|
||||
.build());
|
||||
}
|
||||
|
||||
@@ -188,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());
|
||||
}
|
||||
}
|
||||
-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));
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +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 backend1Uri,
|
||||
@NotBlank String backend2Uri,
|
||||
@NotBlank String backend3Uri,
|
||||
@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) {
|
||||
}
|
||||
-8
@@ -263,14 +263,6 @@ public class AccountController {
|
||||
registrationRecoveryPasswordsManager.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/me")
|
||||
@Deprecated() // use whoami
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse getMe(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return AccountIdentityResponseBuilder.fromAccount(auth.getAccount());
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/whoami")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
+2
-1
@@ -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;
|
||||
|
||||
@@ -220,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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+12
-4
@@ -6,12 +6,13 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Clock;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -48,9 +49,16 @@ public class DirectoryV2Controller {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAuthToken(final @ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
@Operation(
|
||||
summary = "Generate credentials for Contact Discovery Service",
|
||||
description = """
|
||||
Generate Contact Discovery Service credentials. Generated credentials have an expiration time of 24 hours\s
|
||||
(however, the TTL is fully controlled by the server and may change even for already generated credentials).
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
public ExternalServiceCredentials getAuthToken(final @ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
final ExternalServiceCredentials credentials = directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
return Response.ok().entity(credentials).build();
|
||||
return directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
}
|
||||
}
|
||||
+20
-3
@@ -130,7 +130,7 @@ 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;
|
||||
@@ -177,6 +177,7 @@ public class MessageController {
|
||||
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
|
||||
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
|
||||
private static final String LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "largeMessage");
|
||||
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
|
||||
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
|
||||
@@ -208,6 +209,12 @@ public class MessageController {
|
||||
|
||||
@VisibleForTesting
|
||||
static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
|
||||
private static final long LARGE_MESSAGE_SIZE = DataSize.kibibytes(8).toBytes();
|
||||
|
||||
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
|
||||
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
// for additional details.
|
||||
public static final long MAX_TIMESTAMP = 86_400_000L * 100_000_000L;
|
||||
|
||||
private static final Duration NOTIFY_FOR_REMAINING_MESSAGES_DELAY = Duration.ofMinutes(1);
|
||||
|
||||
@@ -554,6 +561,10 @@ public class MessageController {
|
||||
|
||||
@Context ContainerRequestContext context) throws RateLimitExceededException {
|
||||
|
||||
if (timestamp < 0 || timestamp > MAX_TIMESTAMP) {
|
||||
throw new BadRequestException("Illegal timestamp");
|
||||
}
|
||||
|
||||
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty(), Optional.empty());
|
||||
if (spamCheck instanceof final SpamChecker.Spam spam) {
|
||||
return spam.response();
|
||||
@@ -749,10 +760,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);
|
||||
|
||||
@@ -993,6 +1004,12 @@ public class MessageController {
|
||||
.increment();
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
if (contentLength > LARGE_MESSAGE_SIZE) {
|
||||
Metrics.counter(
|
||||
LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(multiRecipientMessage))))
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
|
||||
private void validateEnvelopeType(final int type, final String userAgent) {
|
||||
|
||||
+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,
|
||||
|
||||
+12
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
@@ -52,6 +54,16 @@ public class RemoteConfigController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Fetch remote configuration",
|
||||
description = """
|
||||
Remote configuration is a list of namespaced keys that clients may use for consistent configuration or behavior.
|
||||
|
||||
Configuration values change over time, and the list should be refreshed periodically, typically at client
|
||||
launch and every few hours thereafter.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "Remote configuration values for the authenticated user", useReturnTypeSchema = true)
|
||||
public UserRemoteConfigList getAll(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
|
||||
+10
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
@@ -37,6 +39,14 @@ public class SecureStorageController {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Generate credentials for Storage Service",
|
||||
description = """
|
||||
Generate Storage Service credentials. Generated credentials have an expiration time of 24 hours\s
|
||||
(however, the TTL is fully controlled by the server and may change even for already generated credentials).
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
public ExternalServiceCredentials getAuth(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return storageServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
-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);
|
||||
}
|
||||
)));
|
||||
}
|
||||
}
|
||||
+113
-9
@@ -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;
|
||||
@@ -87,6 +95,7 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -152,8 +161,20 @@ public class VerificationController {
|
||||
@Path("/session")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid CreateVerificationSessionRequest request)
|
||||
throws RateLimitExceededException {
|
||||
@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, ObsoletePhoneNumberFormatException {
|
||||
|
||||
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
|
||||
request.getUpdateVerificationSessionRequest());
|
||||
@@ -200,12 +221,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);
|
||||
|
||||
@@ -216,7 +253,7 @@ public class VerificationController {
|
||||
VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
final VerificationCheck verificationCheck = registrationFraudChecker.checkVerificationAttempt(
|
||||
context,
|
||||
requestContext,
|
||||
verificationSession,
|
||||
registrationServiceSession.number(),
|
||||
updateVerificationSessionRequest);
|
||||
@@ -433,6 +470,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);
|
||||
@@ -445,10 +491,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);
|
||||
@@ -550,8 +631,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 {
|
||||
|
||||
|
||||
+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
|
||||
|
||||
+13
-2
@@ -9,6 +9,8 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
@@ -19,8 +21,17 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record IncomingMessageList(@NotNull @Valid List<@NotNull IncomingMessage> messages,
|
||||
boolean online, boolean urgent, long timestamp) {
|
||||
public record IncomingMessageList(@NotNull
|
||||
@Valid
|
||||
List<@NotNull @Valid IncomingMessage> messages,
|
||||
|
||||
boolean online,
|
||||
|
||||
boolean urgent,
|
||||
|
||||
@PositiveOrZero
|
||||
@Max(MessageController.MAX_TIMESTAMP)
|
||||
long timestamp) {
|
||||
|
||||
private static final Counter REJECT_DUPLICATE_RECIPIENT_COUNTER =
|
||||
Metrics.counter(
|
||||
|
||||
@@ -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) {
|
||||
}
|
||||
-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) {}
|
||||
+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")
|
||||
|
||||
+10
-5
@@ -6,24 +6,29 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
public class UserRemoteConfig {
|
||||
|
||||
@JsonProperty
|
||||
private String name;
|
||||
@Schema(description = "Name of the configuration", example = "android.exampleFeature")
|
||||
private String name;
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "Whether the configuration is enabled for the user")
|
||||
private boolean enabled;
|
||||
|
||||
@JsonProperty
|
||||
private String value;
|
||||
@Schema(description = "The value to be used for the configuration, if it is a non-boolean type")
|
||||
private String value;
|
||||
|
||||
public UserRemoteConfig() {}
|
||||
public UserRemoteConfig() {
|
||||
}
|
||||
|
||||
public UserRemoteConfig(String name, boolean enabled, String value) {
|
||||
this.name = name;
|
||||
this.name = name;
|
||||
this.enabled = enabled;
|
||||
this.value = value;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
|
||||
+6
@@ -10,16 +10,22 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.InstantAdapter;
|
||||
|
||||
public class UserRemoteConfigList {
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "List of remote configurations applicable to the user")
|
||||
private List<UserRemoteConfig> config;
|
||||
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
@Schema(description = """
|
||||
Timestamp when the configuration was generated. Deprecated in favor of `X-Signal-Timestamp` response header.
|
||||
""", deprecated = true)
|
||||
@Deprecated
|
||||
private Instant serverEpochTime;
|
||||
|
||||
public UserRemoteConfigList() {}
|
||||
|
||||
+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 -> {
|
||||
|
||||
|
||||
-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
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
|
||||
|
||||
public class ObsoletePhoneNumberFormatExceptionMapper implements ExceptionMapper<ObsoletePhoneNumberFormatException> {
|
||||
|
||||
private static final String COUNTER_NAME = MetricsUtil.name(ObsoletePhoneNumberFormatExceptionMapper.class, "errors");
|
||||
|
||||
@Override
|
||||
public Response toResponse(final ObsoletePhoneNumberFormatException exception) {
|
||||
Metrics.counter(COUNTER_NAME, "regionCode", exception.getRegionCode()).increment();
|
||||
return Response.status(499).build();
|
||||
}
|
||||
}
|
||||
+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) {
|
||||
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.securevaluerecovery;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicAuthHeader;
|
||||
|
||||
/**
|
||||
* A client for sending requests to Signal's secure value recovery v3 service on behalf of authenticated users.
|
||||
*/
|
||||
public class SecureValueRecovery3Client {
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator;
|
||||
private final URI backend1Uri;
|
||||
private final URI backend2Uri;
|
||||
private final URI backend3Uri;
|
||||
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/delete";
|
||||
|
||||
public SecureValueRecovery3Client(final ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator,
|
||||
final Executor executor, final ScheduledExecutorService retryExecutor,
|
||||
final SecureValueRecovery3Configuration configuration)
|
||||
throws CertificateException {
|
||||
this.secureValueRecoveryCredentialsGenerator = secureValueRecoveryCredentialsGenerator;
|
||||
this.backend1Uri = URI.create(configuration.backend1Uri()).resolve(DELETE_PATH);
|
||||
this.backend2Uri = URI.create(configuration.backend2Uri()).resolve(DELETE_PATH);
|
||||
this.backend3Uri = URI.create(configuration.backend3Uri()).resolve(DELETE_PATH);
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(configuration.circuitBreaker())
|
||||
.withRetry(configuration.retry())
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_1_1)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withRedirect(HttpClient.Redirect.NEVER)
|
||||
.withExecutor(executor)
|
||||
.withName("secure-value-recovery3")
|
||||
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_2)
|
||||
.withTrustedServerCertificates(configuration.svrCaCertificates().toArray(String[]::new))
|
||||
.build();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) {
|
||||
final ExternalServiceCredentials credentials = secureValueRecoveryCredentialsGenerator.generateForUuid(accountUuid);
|
||||
final List<CompletableFuture<HttpResponse<String>>> futures = Stream.of(backend1Uri, backend2Uri, backend3Uri)
|
||||
.map(uri -> HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.DELETE()
|
||||
.header(HttpHeaders.AUTHORIZATION, basicAuthHeader(credentials))
|
||||
.build())
|
||||
.map(request -> httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()))
|
||||
.toList();
|
||||
|
||||
return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new))
|
||||
.thenApply(ignored -> futures.stream().map(CompletableFuture::join).toList())
|
||||
.thenAccept(responses -> responses.forEach(response -> {
|
||||
if (!HttpUtils.isSuccessfulResponse(response.statusCode())) {
|
||||
throw new SecureValueRecoveryException(String.format("Failed to delete backup in %s", response.uri()), String.valueOf(response.statusCode()));
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
|
||||
@@ -315,10 +315,6 @@ public class Accounts {
|
||||
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
|
||||
|
||||
@@ -82,7 +82,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
@@ -126,7 +125,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final ProfilesManager profilesManager;
|
||||
private final SecureStorageClient secureStorageClient;
|
||||
private final SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
private final SecureValueRecovery3Client secureValueRecovery3Client;
|
||||
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
@@ -210,7 +208,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final ProfilesManager profilesManager,
|
||||
final SecureStorageClient secureStorageClient,
|
||||
final SecureValueRecovery2Client secureValueRecovery2Client,
|
||||
final SecureValueRecovery3Client secureValueRecovery3Client,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
@@ -229,7 +226,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
this.profilesManager = profilesManager;
|
||||
this.secureStorageClient = secureStorageClient;
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
this.secureValueRecovery3Client = secureValueRecovery3Client;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
@@ -1264,16 +1260,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
throw new CompletionException(exception);
|
||||
}));
|
||||
|
||||
final CompletableFuture<Void> svr3DeleteBackupFuture = secureValueRecovery3Client.deleteBackups(account.getUuid())
|
||||
.exceptionally(exception -> {
|
||||
// We don't care about errors from SVR3 because we're not currently using it
|
||||
return null;
|
||||
});
|
||||
|
||||
return CompletableFuture.allOf(
|
||||
secureStorageClient.deleteStoredData(account.getUuid()),
|
||||
svr2DeleteBackupFuture,
|
||||
svr3DeleteBackupFuture,
|
||||
keysManager.deleteSingleUsePreKeys(account.getUuid()),
|
||||
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
|
||||
messagesManager.clear(account.getUuid()),
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+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(
|
||||
|
||||
+7
-6
@@ -202,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,
|
||||
@@ -224,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);
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
public class ObsoletePhoneNumberFormatException extends Exception {
|
||||
|
||||
private final String regionCode;
|
||||
|
||||
public ObsoletePhoneNumberFormatException(final String regionCode) {
|
||||
super("The provided format is obsolete in %s".formatted(regionCode));
|
||||
this.regionCode = regionCode;
|
||||
}
|
||||
|
||||
public String getRegionCode() {
|
||||
return regionCode;
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@ 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 {
|
||||
@@ -125,7 +124,7 @@ public class Util {
|
||||
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
|
||||
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
if ("BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber))) {
|
||||
final String nationalSignificantNumber = PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
|
||||
final String alternateE164;
|
||||
@@ -176,7 +175,7 @@ public class Util {
|
||||
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
|
||||
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
// We prefer the longest form for long-term stability
|
||||
return e164s.stream().sorted(Comparator.comparingInt(String::length).reversed()).findFirst();
|
||||
}
|
||||
@@ -217,7 +216,7 @@ public class Util {
|
||||
}
|
||||
|
||||
/**
|
||||
* Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024.
|
||||
* Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
*
|
||||
* @param phoneNumber the phone number to check.
|
||||
* @return whether the provided phone number is an old-format Benin phone number
|
||||
@@ -235,11 +234,9 @@ public class Util {
|
||||
* @return the canonical phone number if applicable, otherwise the original phone number.
|
||||
*/
|
||||
public static Phonenumber.PhoneNumber canonicalizePhoneNumber(final Phonenumber.PhoneNumber phoneNumber)
|
||||
throws NumberParseException {
|
||||
throws NumberParseException, ObsoletePhoneNumberFormatException {
|
||||
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);
|
||||
throw new ObsoletePhoneNumberFormatException("bj");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
+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;
|
||||
|
||||
+1
-9
@@ -32,7 +32,6 @@ import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery3Controller;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
@@ -45,7 +44,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -161,8 +159,6 @@ record CommandDependencies(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator secureValueRecovery2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
configuration.getSvr2Configuration());
|
||||
ExternalServiceCredentialsGenerator secureValueRecovery3CredentialsGenerator = SecureValueRecovery3Controller.credentialsGenerator(
|
||||
configuration.getSvr3Configuration());
|
||||
|
||||
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(MetricRegistry.name(CommandDependencies.class, "awsSdkMetrics-%d"));
|
||||
@@ -215,10 +211,6 @@ record CommandDependencies(
|
||||
secureValueRecovery2CredentialsGenerator, secureValueRecoveryServiceExecutor,
|
||||
secureValueRecoveryServiceRetryExecutor,
|
||||
configuration.getSvr2Configuration());
|
||||
SecureValueRecovery3Client secureValueRecovery3Client = new SecureValueRecovery3Client(
|
||||
secureValueRecovery3CredentialsGenerator, secureValueRecoveryServiceExecutor,
|
||||
secureValueRecoveryServiceRetryExecutor,
|
||||
configuration.getSvr3Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
@@ -240,7 +232,7 @@ record CommandDependencies(
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, secureValueRecovery3Client, disconnectionRequestManager,
|
||||
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, messagePollExecutor,
|
||||
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(configuration.getLimitsConfiguration(),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -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 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);
|
||||
|
||||
|
||||
+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"),
|
||||
|
||||
+3
-4
@@ -324,9 +324,8 @@ 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);
|
||||
@@ -337,7 +336,7 @@ class AccountControllerTest {
|
||||
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()) {
|
||||
|
||||
-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();
|
||||
}
|
||||
}
|
||||
+30
@@ -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;
|
||||
@@ -1346,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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -37,11 +37,11 @@ class DirectoryControllerV2Test {
|
||||
final UUID uuid = UUID.fromString("11111111-1111-1111-1111-111111111111");
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
|
||||
final ExternalServiceCredentials credentials = (ExternalServiceCredentials) controller.getAuthToken(
|
||||
new AuthenticatedDevice(account, mock(Device.class))).getEntity();
|
||||
final ExternalServiceCredentials credentials = controller.getAuthToken(
|
||||
new AuthenticatedDevice(account, mock(Device.class)));
|
||||
|
||||
assertEquals(credentials.username(), "d369bc712e2e0dd36258");
|
||||
assertEquals(credentials.password(), "1633738643:4433b0fab41f25f79dd4");
|
||||
assertEquals("d369bc712e2e0dd36258", credentials.username());
|
||||
assertEquals("1633738643:4433b0fab41f25f79dd4", credentials.password());
|
||||
}
|
||||
|
||||
}
|
||||
+101
-5
@@ -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;
|
||||
@@ -132,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;
|
||||
@@ -486,6 +485,43 @@ class MessageControllerTest {
|
||||
Arguments.of(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), true, true, 400));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"-1, 422",
|
||||
"0, 200",
|
||||
"1, 200",
|
||||
"8640000000000000, 200",
|
||||
"8640000000000001, 422",
|
||||
|
||||
// This is something of a quirk; because this failure is happening at the parsing layer (we can't parse it as a
|
||||
// `long`) instead of the validation layer, we get a 400 instead of a 422
|
||||
"99999999999999999999999999999999999, 400"
|
||||
})
|
||||
void testSingleDeviceExtremeTimestamp(final String timestamp, final int expectedStatus) throws JsonProcessingException {
|
||||
final String jsonTemplate = """
|
||||
{
|
||||
"timestamp" : %s,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
""";
|
||||
|
||||
final String json = String.format(jsonTemplate, timestamp);
|
||||
|
||||
try (final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(json))) {
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(expectedStatus)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendBadAuth() throws Exception {
|
||||
try (final Response response =
|
||||
@@ -675,7 +711,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);
|
||||
@@ -1059,7 +1095,7 @@ class MessageControllerTest {
|
||||
.request()
|
||||
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
|
||||
.put(Entity.entity(new IncomingMessageList(
|
||||
List.of(new IncomingMessage(1, (byte) 1, 1, new String(contentBytes))), false, true,
|
||||
List.of(new IncomingMessage(1, (byte) 1, 1, Base64.getEncoder().encodeToString(contentBytes))), false, true,
|
||||
System.currentTimeMillis()),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
@@ -1167,7 +1203,7 @@ class MessageControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testManyRecipientMessage() throws Exception {
|
||||
void testManyRecipientMessage() {
|
||||
|
||||
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
|
||||
.thenReturn(new byte[]{1});
|
||||
@@ -1561,6 +1597,66 @@ class MessageControllerTest {
|
||||
checkBadMultiRecipientResponse(response, 400);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"-1, 400",
|
||||
"0, 200",
|
||||
"1, 200",
|
||||
"8640000000000000, 200",
|
||||
"8640000000000001, 400",
|
||||
|
||||
// 404 here is a weird quirk of controller pattern matching; this value doesn't get interpreted as `long`, and so
|
||||
// it doesn't match the "send multi-recipient message" endpoint
|
||||
"99999999999999999999999999999999999, 404"
|
||||
})
|
||||
void testMultiRecipientExtremeTimestamp(final String timestamp, final int expectedStatus) {
|
||||
|
||||
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
|
||||
.thenReturn(new byte[]{1});
|
||||
|
||||
final int nRecipients = 999;
|
||||
final int devicesPerRecipient = 5;
|
||||
final List<Recipient> recipients = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < nRecipients; i++) {
|
||||
final List<Device> devices =
|
||||
IntStream.range(1, devicesPerRecipient + 1)
|
||||
.mapToObj(
|
||||
d -> generateTestDevice(
|
||||
(byte) d, 100 + d, 10 * d, true))
|
||||
.collect(Collectors.toList());
|
||||
final UUID aci = new UUID(0L, i);
|
||||
final UUID pni = new UUID(1L, i);
|
||||
final String e164 = String.format("+1408555%04d", i);
|
||||
final Account account = AccountsHelper.generateTestAccount(e164, aci, pni, devices, UNIDENTIFIED_ACCESS_BYTES);
|
||||
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
when(accountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(pni)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
devices.forEach(d -> recipients.add(new Recipient(new AciServiceIdentifier(aci), d.getId(), d.getRegistrationId(), new byte[48])));
|
||||
}
|
||||
|
||||
byte[] buffer = new byte[1048576];
|
||||
InputStream stream = initializeMultiPayload(recipients, buffer, true);
|
||||
Entity<InputStream> entity = Entity.entity(stream, MultiRecipientMessageProvider.MEDIA_TYPE);
|
||||
try (final Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/messages/multi_recipient")
|
||||
.queryParam("online", true)
|
||||
.queryParam("story", true)
|
||||
.queryParam("urgent", false)
|
||||
.queryParam("ts", timestamp)
|
||||
.request()
|
||||
.header(HttpHeaders.USER_AGENT, "test")
|
||||
.put(entity)) {
|
||||
|
||||
assertThat(response.readEntity(String.class), response.getStatus(), is(equalTo(expectedStatus)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendStoryToUnknownAccount() throws Exception {
|
||||
String accessBytes = Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES);
|
||||
|
||||
-184
@@ -1,184 +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;
|
||||
}
|
||||
}
|
||||
+27
-3
@@ -66,6 +66,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -117,6 +118,7 @@ class VerificationControllerTest {
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
|
||||
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
|
||||
.addProvider(new ObsoletePhoneNumberFormatExceptionMapper())
|
||||
.addProvider(new RegistrationServiceSenderExceptionMapper())
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
@@ -220,7 +222,7 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
when(verificationSessionManager.insert(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -245,14 +247,36 @@ class VerificationControllerTest {
|
||||
// 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)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createBeninSessionFailure() {
|
||||
// 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", "");
|
||||
|
||||
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(oldFormatBeninE164, "token", "fcm")))) {
|
||||
assertEquals(499, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void createSessionSuccess(final String pushToken, final String pushTokenType,
|
||||
|
||||
+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"),
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -107,13 +107,13 @@ class FaultTolerantRedisClusterClientTest {
|
||||
cluster = buildCluster(null, ClientResources.builder());
|
||||
|
||||
final ExecutionException asyncException = assertThrows(ExecutionException.class,
|
||||
() -> cluster.withCluster(connection -> connection.async().blpop(2 * TIMEOUT.toMillis() / 1000d, "key"))
|
||||
() -> cluster.withCluster(connection -> connection.async().blpop(10 * TIMEOUT.toMillis() / 1000d, "key"))
|
||||
.get());
|
||||
|
||||
assertInstanceOf(RedisCommandTimeoutException.class, asyncException.getCause());
|
||||
|
||||
assertThrows(RedisCommandTimeoutException.class,
|
||||
() -> cluster.withCluster(connection -> connection.sync().blpop(2 * TIMEOUT.toMillis() / 1000d, "key")));
|
||||
() -> cluster.withCluster(connection -> connection.sync().blpop(10 * TIMEOUT.toMillis() / 1000d, "key")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-196
@@ -1,196 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.securevaluerecovery;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
|
||||
|
||||
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
|
||||
|
||||
class SecureValueRecovery3ClientTest {
|
||||
|
||||
private UUID accountUuid;
|
||||
private ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private ExecutorService httpExecutor;
|
||||
private ScheduledExecutorService retryExecutor;
|
||||
|
||||
private SecureValueRecovery3Client secureValueRecovery3Client;
|
||||
|
||||
@RegisterExtension
|
||||
private static final WireMockExtension backend1WireMock = WireMockExtension.newInstance()
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
|
||||
@RegisterExtension
|
||||
private static final WireMockExtension backend2WireMock = WireMockExtension.newInstance()
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
|
||||
@RegisterExtension
|
||||
private static final WireMockExtension backend3WireMock = WireMockExtension.newInstance()
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws CertificateException {
|
||||
accountUuid = UUID.randomUUID();
|
||||
credentialsGenerator = mock(ExternalServiceCredentialsGenerator.class);
|
||||
httpExecutor = Executors.newSingleThreadExecutor();
|
||||
retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
final SecureValueRecovery3Configuration config = new SecureValueRecovery3Configuration(
|
||||
"http://localhost:" + backend1WireMock.getPort(),
|
||||
"http://localhost:" + backend2WireMock.getPort(),
|
||||
"http://localhost:" + backend3WireMock.getPort(),
|
||||
randomSecretBytes(32),
|
||||
randomSecretBytes(32),
|
||||
// This is a randomly-generated, throwaway certificate that's not actually connected to anything
|
||||
List.of("""
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIICZDCCAc2gAwIBAgIBADANBgkqhkiG9w0BAQ0FADBPMQswCQYDVQQGEwJ1czEL
|
||||
MAkGA1UECAwCVVMxHjAcBgNVBAoMFVNpZ25hbCBNZXNzZW5nZXIsIExMQzETMBEG
|
||||
A1UEAwwKc2lnbmFsLm9yZzAeFw0yMDEyMjMyMjQ3NTlaFw0zMDEyMjEyMjQ3NTla
|
||||
ME8xCzAJBgNVBAYTAnVzMQswCQYDVQQIDAJVUzEeMBwGA1UECgwVU2lnbmFsIE1l
|
||||
c3NlbmdlciwgTExDMRMwEQYDVQQDDApzaWduYWwub3JnMIGfMA0GCSqGSIb3DQEB
|
||||
AQUAA4GNADCBiQKBgQCfSLcZNHYqbxSsgWp4JvbPRHjQTrlsrKrgD2q7f/OY6O3Y
|
||||
/X0QNcNSOJpliN8rmzwslfsrXHO3q1diGRw4xHogUJZ/7NQrHiP/zhN0VTDh49pD
|
||||
ZpjXVyUbayLS/6qM5arKxBspzEFBb5v8cF6bPr76SO/rpGXiI0j6yJKX6fRiKwID
|
||||
AQABo1AwTjAdBgNVHQ4EFgQU6Jrs/Fmj0z4dA3wvdq/WqA4P49IwHwYDVR0jBBgw
|
||||
FoAU6Jrs/Fmj0z4dA3wvdq/WqA4P49IwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
|
||||
AQ0FAAOBgQB+5d5+NtzLILfrc9QmJdIO1YeDP64JmFwTER0kEUouRsb9UwknVWZa
|
||||
y7MTM4NoBV1k0zb5LAk89SIDPr/maW5AsLtEomzjnEiomjoMBUdNe3YCgQReoLnr
|
||||
R/QaUNbrCjTGYfBsjGbIzmkWPUyTec2ZdRyJ8JiVl386+6CZkxnndQ==
|
||||
-----END CERTIFICATE-----
|
||||
""", """
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEpDCCAowCCQC43PUTWSADVjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls
|
||||
b2NhbGhvc3QwHhcNMjIxMDE3MjA0NTM0WhcNMjMxMDE3MjA0NTM0WjAUMRIwEAYD
|
||||
VQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDV
|
||||
x1cdEd2ffQTlTXWRiCHGcrlYf4RJnctt9sw/BuHWTLXBu5LhyJSGn5LRszO/NCXK
|
||||
Z/cmGR7pLj366RtiwL+Qo3nhvDCK7T9xZeNIusM6XMcMK9D/DGCYPqtjQz8NXd9V
|
||||
ajBBe6nwTDTa+oqX8Mt89foWNkg5Il/lY62u9Dr18LRZ2W9zzYi3Q9/K0CbIX6pM
|
||||
yVlPIO5rITOR2IsbeyqsO9jufgX5lP4ZKLLBAP1b7usjC4YdvWacjQg/rK5aay1x
|
||||
jC2HCDgo/4N30QVXzSA9nFfSe6AE/xkStK4819JqOkY5JsJCbef1P3hOOdSLEjbp
|
||||
xq3MjOs6G6dOgteaAGs10vx7dHxDWETTIiD7BIZ9zRYgOF5bkCaIUO+JfySE1MHD
|
||||
KBAFLoRuvmRev5Ln5R0MCHpUMSmMNgJqz+RWZV3g/gpYbuWiHgJOwL1393eK50Bg
|
||||
W7SXQ8EjJj2yXZSH+1gPzN0DRoJZiaBoTPnCL2qUgvwFpW1PJsM5FDyUJFUoK5kK
|
||||
HLBBSKAPt6ZlSrUe2nBgJv7EF1GK+fTU08LXgW33OpLceGPa0zTShkukQUMtUtZ8
|
||||
GqhO12ohMzEupIu5Xurthq4VVUrzHUdj1ZZRMhAbfLU36sd03MMyL/xBqTN6dzCa
|
||||
GDGIPGpYjAllZ5xMRt2kZdv+Kr6oo3u2nLUIsqI7KQIDAQABMA0GCSqGSIb3DQEB
|
||||
CwUAA4ICAQCB5s43YF35ssf5YONW5iAaifGpi1o0866xfeOybtohFGvQ7V2W34i9
|
||||
TYBCt8+0hgatMcvZ08f0vqig1i7nrvYcE1hnhL7JNkU8qm0s9ytHZt6j62nB0kd/
|
||||
uqE2hOEQalTf/2TGPV0CCgiqLyd8lEUQvQeA38wktwUeZpVnErlzHeMR2CvV3K8R
|
||||
u4vV6SnBcf+TAt56RKYZkPyvZj5llQPo14Glyoo8qZES7Ky1SHmM0GL+baPRBjRW
|
||||
3KgSt98Wyu4yr9qu21JpnbAnLhBfzfSKjSeCRgFElUE1GIaFGRZ7ypA74dUKeLnb
|
||||
/VUWrszmUhGaEjV9dpI6x6B/kSpQMtIQqBaKRY2ALUeEujS/rURi4iMDwSU+GkSH
|
||||
cyEvZKS97OA/dWeXfLXdo4beDBRG93bI4rQnDg5+VdlBOkQSLueb8x6/VThMoC5d
|
||||
vZiotFQHseljQAdTkNa6tBu6c4XDYPCKB3CfkMYOlCfTS7Acn5G6dxTPKBtLGBnL
|
||||
nQfYyzuwYkN09+2PVzt6auBHr3To7uoclkxX+hxyvPIwIZ0N6b4tQR1FCAkvg29Q
|
||||
WIOjZOKGW690ESKCKOnFjUHVO0HpuWnT81URTuY62FXsYdVc2wE4v0E04mEbqQ0P
|
||||
lY6ZKNA81Lm3YADYtObmK1IUrOPo9BeIaPy0UM08SmN880Vunqa91Q==
|
||||
-----END CERTIFICATE-----
|
||||
"""),
|
||||
null, null);
|
||||
|
||||
secureValueRecovery3Client = new SecureValueRecovery3Client(credentialsGenerator, httpExecutor, retryExecutor,
|
||||
config);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
retryExecutor.shutdown();
|
||||
retryExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStoredData() {
|
||||
final String username = RandomStringUtils.secure().nextAlphabetic(16);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
backend1WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(202)));
|
||||
|
||||
backend2WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(202)));
|
||||
|
||||
backend3WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(202)));
|
||||
|
||||
assertDoesNotThrow(() -> secureValueRecovery3Client.deleteBackups(accountUuid).join());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void deleteStoredDataFailure(final int backend1Status, final int backend2Status, final int backend3Status) {
|
||||
final String username = RandomStringUtils.secure().nextAlphabetic(16);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
backend1WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(backend1Status)));
|
||||
|
||||
backend2WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(backend2Status)));
|
||||
|
||||
backend3WireMock.stubFor(delete(urlEqualTo(SecureValueRecovery3Client.DELETE_PATH))
|
||||
.withBasicAuth(username, password)
|
||||
.willReturn(aResponse().withStatus(backend3Status)));
|
||||
|
||||
final CompletionException completionException = assertThrows(CompletionException.class,
|
||||
() -> secureValueRecovery3Client.deleteBackups(accountUuid).join());
|
||||
|
||||
assertInstanceOf(SecureValueRecoveryException.class, completionException.getCause());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> deleteStoredDataFailure() {
|
||||
return Stream.of(
|
||||
Arguments.of(400, 202, 202),
|
||||
Arguments.of(202, 400, 202),
|
||||
Arguments.of(202, 202, 400)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
-5
@@ -49,7 +49,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
|
||||
public class AccountCreationDeletionIntegrationTest {
|
||||
@@ -126,9 +125,6 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecovery3Client svr3Client = mock(SecureValueRecovery3Client.class);
|
||||
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.PNI.tableName());
|
||||
@@ -159,7 +155,6 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
svr3Client,
|
||||
disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
|
||||
-5
@@ -41,7 +41,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
@@ -118,9 +117,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecovery3Client svr3Client = mock(SecureValueRecovery3Client.class);
|
||||
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
@@ -149,7 +145,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
svr3Client,
|
||||
disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
|
||||
-2
@@ -54,7 +54,6 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.JsonHelpers;
|
||||
@@ -137,7 +136,6 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(SecureValueRecovery3Client.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
|
||||
+1
-2
@@ -21,7 +21,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -66,7 +66,6 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(SecureValueRecovery3Client.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
|
||||
-19
@@ -87,7 +87,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager.UsernameReservation;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
@@ -131,7 +130,6 @@ class AccountsManagerTest {
|
||||
private RedisAdvancedClusterAsyncCommands<String, String> asyncClusterCommands;
|
||||
private AccountsManager accountsManager;
|
||||
private SecureValueRecovery2Client svr2Client;
|
||||
private SecureValueRecovery3Client svr3Client;
|
||||
private DynamicConfiguration dynamicConfiguration;
|
||||
|
||||
private static final Answer<?> ACCOUNT_UPDATE_ANSWER = (answer) -> {
|
||||
@@ -195,9 +193,6 @@ class AccountsManagerTest {
|
||||
svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
svr3Client = mock(SecureValueRecovery3Client.class);
|
||||
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
phoneNumberIdentifiersByE164 = new HashMap<>();
|
||||
|
||||
@@ -259,7 +254,6 @@ class AccountsManagerTest {
|
||||
profilesManager,
|
||||
storageClient,
|
||||
svr2Client,
|
||||
svr3Client,
|
||||
disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
@@ -295,19 +289,6 @@ class AccountsManagerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"500", "429"})
|
||||
void testDeleteWithSvr3ErrorStatusCodes(final String statusCode) throws InterruptedException {
|
||||
when(svr3Client.deleteBackups(any())).thenReturn(
|
||||
CompletableFuture.failedFuture(new SecureValueRecoveryException("Failed to delete backup", statusCode)));
|
||||
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null);
|
||||
|
||||
final Account createdAccount = createAccount("+18005550123", attributes);
|
||||
|
||||
assertDoesNotThrow(() -> accountsManager.delete(createdAccount, AccountsManager.DeletionReason.USER_REQUEST).toCompletableFuture().join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetByServiceIdentifier() {
|
||||
final UUID aci = UUID.randomUUID();
|
||||
|
||||
-2
@@ -41,7 +41,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
@@ -151,7 +150,6 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
profileManager,
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(SecureValueRecovery3Client.class),
|
||||
disconnectionRequestManager,
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
|
||||
@@ -467,7 +467,6 @@ class AccountsTest {
|
||||
|
||||
// the backup credential request and share-set are always preserved across account reclaims
|
||||
existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
|
||||
existingAccount.setSvr3ShareSet(TestRandomUtil.nextBytes(100));
|
||||
createAccount(existingAccount);
|
||||
final Account secondAccount =
|
||||
generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
|
||||
@@ -479,7 +478,6 @@ class AccountsTest {
|
||||
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).get());
|
||||
assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MEDIA).get())
|
||||
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).get());
|
||||
assertThat(reclaimed.getSvr3ShareSet()).isEqualTo(existingAccount.getSvr3ShareSet());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-5
@@ -41,7 +41,6 @@ import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery3Client;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -126,9 +125,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecovery3Client svr3Client = mock(SecureValueRecovery3Client.class);
|
||||
when(svr3Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.PNI.tableName());
|
||||
@@ -161,7 +157,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
svr3Client,
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
clientPublicKeysManager,
|
||||
|
||||
+11
-1
@@ -24,8 +24,9 @@ public class TestWebsocketListener implements WebSocketListener {
|
||||
|
||||
private final AtomicLong requestId = new AtomicLong();
|
||||
private final CompletableFuture<Session> started = new CompletableFuture<>();
|
||||
private final CompletableFuture<Integer> closed = new CompletableFuture<>();
|
||||
private final ConcurrentHashMap<Long, CompletableFuture<WebSocketResponseMessage>> responseFutures = new ConcurrentHashMap<>();
|
||||
private final WebSocketMessageFactory messageFactory;
|
||||
protected final WebSocketMessageFactory messageFactory;
|
||||
|
||||
public TestWebsocketListener() {
|
||||
this.messageFactory = new ProtobufWebSocketMessageFactory();
|
||||
@@ -38,6 +39,15 @@ public class TestWebsocketListener implements WebSocketListener {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWebSocketClose(int statusCode, String reason) {
|
||||
closed.complete(statusCode);
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> closeFuture() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
public CompletableFuture<WebSocketResponseMessage> doGet(final String requestPath) {
|
||||
return sendRequest(requestPath, "GET", List.of("Accept: application/json"), Optional.empty());
|
||||
}
|
||||
|
||||
@@ -7,15 +7,17 @@ package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.stream.Stream;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
@@ -93,9 +95,13 @@ class UtilTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber)
|
||||
throws NumberParseException {
|
||||
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
|
||||
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber, @Nullable Class<? extends Throwable> exception)
|
||||
throws Exception {
|
||||
if (exception == null) {
|
||||
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
|
||||
} else {
|
||||
assertThrows(exception, () -> Util.canonicalizePhoneNumber(beninNumber));
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> normalizeBeninPhoneNumber() throws NumberParseException {
|
||||
@@ -103,9 +109,9 @@ class UtilTest {
|
||||
final Phonenumber.PhoneNumber newFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
|
||||
final Phonenumber.PhoneNumber usPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("US");
|
||||
return Stream.of(
|
||||
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
|
||||
Arguments.of(oldFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
|
||||
Arguments.of(usPhoneNumber, usPhoneNumber)
|
||||
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber, null),
|
||||
Arguments.of(oldFormatBeninPhoneNumber, null, ObsoletePhoneNumberFormatException.class),
|
||||
Arguments.of(usPhoneNumber, usPhoneNumber, null)
|
||||
);
|
||||
}
|
||||
}
|
||||
+69
-9
@@ -1,6 +1,24 @@
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -9,23 +27,20 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class ProvisioningConnectListenerTest {
|
||||
|
||||
private ProvisioningManager provisioningManager;
|
||||
private ProvisioningConnectListener provisioningConnectListener;
|
||||
private ScheduledExecutorService scheduledExecutorService;
|
||||
|
||||
private static Duration TIMEOUT = Duration.ofSeconds(5);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
provisioningManager = mock(ProvisioningManager.class);
|
||||
provisioningConnectListener = new ProvisioningConnectListener(provisioningManager);
|
||||
scheduledExecutorService = mock(ScheduledExecutorService.class);
|
||||
provisioningConnectListener =
|
||||
new ProvisioningConnectListener(provisioningManager, scheduledExecutorService, TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -60,4 +75,49 @@ class ProvisioningConnectListenerTest {
|
||||
assertEquals(addListenerProvisioningAddressCaptor.getValue(), removeListenerProvisioningAddressCaptor.getValue());
|
||||
assertEquals(addListenerProvisioningAddressCaptor.getValue(), sentProvisioningAddress);
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulesTimeout() {
|
||||
final WebSocketClient webSocketClient = mock(WebSocketClient.class);
|
||||
final WebSocketSessionContext context = new WebSocketSessionContext(webSocketClient);
|
||||
|
||||
when(webSocketClient.supportsProvisioningSocketTimeouts()).thenReturn(true);
|
||||
final ScheduledFuture<?> scheduledFuture = mock(ScheduledFuture.class);
|
||||
doReturn(scheduledFuture).when(scheduledExecutorService).schedule(any(Runnable.class), anyLong(), any());
|
||||
|
||||
final ArgumentCaptor<Runnable> scheduleCaptor = ArgumentCaptor.forClass(Runnable.class);
|
||||
provisioningConnectListener.onWebSocketConnect(context);
|
||||
verify(scheduledExecutorService).schedule(scheduleCaptor.capture(), eq(TIMEOUT.getSeconds()), eq(TimeUnit.SECONDS));
|
||||
|
||||
verify(webSocketClient, never()).close(anyInt(), any());
|
||||
scheduleCaptor.getValue().run();
|
||||
verify(webSocketClient, times(1)).close(eq(1000), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelsTimeout() {
|
||||
final WebSocketClient webSocketClient = mock(WebSocketClient.class);
|
||||
final WebSocketSessionContext context = new WebSocketSessionContext(webSocketClient);
|
||||
|
||||
when(webSocketClient.supportsProvisioningSocketTimeouts()).thenReturn(true);
|
||||
final ScheduledFuture<?> scheduledFuture = mock(ScheduledFuture.class);
|
||||
doReturn(scheduledFuture).when(scheduledExecutorService).schedule(any(Runnable.class), anyLong(), any());
|
||||
|
||||
provisioningConnectListener.onWebSocketConnect(context);
|
||||
verify(scheduledExecutorService).schedule(any(Runnable.class), eq(TIMEOUT.getSeconds()), eq(TimeUnit.SECONDS));
|
||||
|
||||
context.notifyClosed(1000, "Test");
|
||||
|
||||
verify(scheduledFuture).cancel(false);
|
||||
verify(webSocketClient, never()).close(anyInt(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsTimeoutIfUnsupported() {
|
||||
final WebSocketClient webSocketClient = mock(WebSocketClient.class);
|
||||
final WebSocketSessionContext context = new WebSocketSessionContext(webSocketClient);
|
||||
provisioningConnectListener.onWebSocketConnect(context);
|
||||
verify(scheduledExecutorService, never())
|
||||
.schedule(any(Runnable.class), eq(TIMEOUT.getSeconds()), eq(TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
@@ -53,9 +53,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=
|
||||
|
||||
# The below private key was key generated exclusively for testing purposes. Do not use it in any other context.
|
||||
@@ -162,9 +159,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=
|
||||
|
||||
|
||||
@@ -217,37 +217,6 @@ svr2:
|
||||
9Kxq0DY7RCEpdHMCKcOL
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
svr3:
|
||||
backend1Uri: backend1.example.com
|
||||
backend2Uri: backend2.example.com
|
||||
backend3Uri: backend3.example.com
|
||||
userAuthenticationTokenSharedSecret: secret://svr3.userAuthenticationTokenSharedSecret
|
||||
userIdTokenSharedSecret: secret://svr3.userIdTokenSharedSecret
|
||||
svrCaCertificates:
|
||||
# This is a randomly generated test certificate
|
||||
- |
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDazCCAlOgAwIBAgIUW5lcNWkuynRVc8Rq5pO6mHQBuZAwDQYJKoZIhvcNAQEL
|
||||
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
|
||||
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDAzMjUwMzE4MTNaFw0yOTAz
|
||||
MjQwMzE4MTNaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw
|
||||
HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB
|
||||
AQUAA4IBDwAwggEKAoIBAQCfH4Um+fv2r4KudhD37/UXp8duRLTmp4XvpBTpDHpD
|
||||
2HF8p2yThVKlJnMkP/9Ey1Rb0vhxO7DCltLdW8IYcxJuHoyMvyhGUEtxxkOZbrk8
|
||||
ciUR9jTZ37x7vXRGj/RxcdlS6iD0MeF0D/LAkImt4T/kiKwDbENrVEnYWJmipCKP
|
||||
ribxWky7HqxDCoYMQr0zatxB3A9mx5stH+H3kbw3CZcm+ugF9ZIKDEVHb0lf28gq
|
||||
llmD120q/vs9YV3rzVL7sBGDqf6olkulvHQJKElZg2rdcHWFcngSlU2BjR04oyuH
|
||||
c/SSiLSB3YB0tdFGta5uorXyV1y7RElPeBfOfvEjsG3TAgMBAAGjUzBRMB0GA1Ud
|
||||
DgQWBBQX+xlgSWWbDjv0SrJ+h67xauJ80zAfBgNVHSMEGDAWgBQX+xlgSWWbDjv0
|
||||
SrJ+h67xauJ80zAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAw
|
||||
ZG2MCCjscn6h/QOoJU+IDfa68OqLq0I37gMnLMde4yEhAmm//miePIq4Uz9GRJ+h
|
||||
rAmdEnspKgyQ93PjF7Xpk/JdJA4B1bIrsOl/cSwqx2sFhRt8Kt1DHGlGWXqOaHRP
|
||||
UkZ86MyRL3sXly6WkxEYxZJeQaOzMy2XmQh7grzrlTBuSI+0xf7vsRRDipxr6LVQ
|
||||
6qGWyGODLLc2JD1IXj/1HpRVT2LoGGlKMuyxACQAm4oak1vvJ9mGxgfd9AU+eo58
|
||||
O/esB2Eaf+QqMPELdFSZQfG2jvp+3WQTZK8fDKHyLr076G3UetEMy867F6fzTSZd
|
||||
9Kxq0DY7RCEpdHMCKcOL
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
cluster:
|
||||
@@ -357,10 +326,6 @@ paymentsService:
|
||||
externalClients:
|
||||
type: stub
|
||||
|
||||
artService:
|
||||
userAuthenticationTokenSharedSecret: secret://artService.userAuthenticationTokenSharedSecret
|
||||
userAuthenticationTokenUserIdSecret: secret://artService.userAuthenticationTokenUserIdSecret
|
||||
|
||||
badges:
|
||||
badges:
|
||||
- id: TEST
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 333,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,20 +1,18 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 4,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 333,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"destinationRegistrationId" : 444,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,26 +1,24 @@
|
||||
{
|
||||
"urgent": false,
|
||||
"timestamp": 1234,
|
||||
"messages": [
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 1,
|
||||
"destinationRegistrationId": 222,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 2,
|
||||
"destinationRegistrationId": 333,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 3,
|
||||
"destinationRegistrationId": 444,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 2222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 3333,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"destinationRegistrationId" : 4444,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [ {
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}, null ]
|
||||
}
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 999,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"destinationRegistrationId" : 444,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 7,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"urgent": false,
|
||||
"timestamp": 1234,
|
||||
"messages": [
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 1,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
}
|
||||
]
|
||||
}
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"timestamp": 1234,
|
||||
"messages": [
|
||||
{
|
||||
"type": 5,
|
||||
"destinationDeviceId": 1,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package org.whispersystems.websocket;
|
||||
|
||||
/**
|
||||
* Class containing constants and shared logic for handling stories.
|
||||
* <p>
|
||||
* In particular, it defines the way we interpret the X-Signal-Receive-Stories header
|
||||
* which is used by both WebSockets and by the REST API.
|
||||
*/
|
||||
public class Stories {
|
||||
public final static String X_SIGNAL_RECEIVE_STORIES = "X-Signal-Receive-Stories";
|
||||
|
||||
public static boolean parseReceiveStoriesHeader(String s) {
|
||||
return "true".equals(s);
|
||||
}
|
||||
}
|
||||
@@ -98,8 +98,12 @@ public class WebSocketClient {
|
||||
}
|
||||
|
||||
public boolean shouldDeliverStories() {
|
||||
String value = session.getUpgradeRequest().getHeader(Stories.X_SIGNAL_RECEIVE_STORIES);
|
||||
return Stories.parseReceiveStoriesHeader(value);
|
||||
String value = session.getUpgradeRequest().getHeader(WebsocketHeaders.X_SIGNAL_RECEIVE_STORIES);
|
||||
return WebsocketHeaders.parseReceiveStoriesHeader(value);
|
||||
}
|
||||
|
||||
public boolean supportsProvisioningSocketTimeouts() {
|
||||
return session.getUpgradeRequest().getHeader(WebsocketHeaders.X_SIGNAL_WEBSOCKET_TIMEOUT_HEADER) != null;
|
||||
}
|
||||
|
||||
private long generateRequestId() {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package org.whispersystems.websocket;
|
||||
|
||||
/**
|
||||
* Class containing constants and shared logic for headers used in websocket upgrade requests.
|
||||
*/
|
||||
public class WebsocketHeaders {
|
||||
public final static String X_SIGNAL_RECEIVE_STORIES = "X-Signal-Receive-Stories";
|
||||
public static final String X_SIGNAL_WEBSOCKET_TIMEOUT_HEADER = "X-Signal-Websocket-Timeout";
|
||||
|
||||
public static boolean parseReceiveStoriesHeader(String s) {
|
||||
return "true".equals(s);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user