mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:26:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
378b32d44d | ||
|
|
e1fcd3e3f6 | ||
|
|
d7ad8dd448 | ||
|
|
859f2302a9 | ||
|
|
a6d11789e9 | ||
|
|
43f83076fa | ||
|
|
71c0fc8d4a | ||
|
|
d2f723de12 | ||
|
|
1f4f926ce6 | ||
|
|
35286f838e | ||
|
|
e1ea3795bb | ||
|
|
95237a22a9 | ||
|
|
11c93c5f53 | ||
|
|
b59b8621c5 | ||
|
|
44c61d9a58 | ||
|
|
63a17bc14b | ||
|
|
f4f93bb24d | ||
|
|
7561622bc8 | ||
|
|
b041566aba | ||
|
|
cb72158abc | ||
|
|
5c432d094f | ||
|
|
24ac48b3b1 | ||
|
|
c03060fe3c | ||
|
|
3ebd5141ae | ||
|
|
c16006dc4b | ||
|
|
8fc465b3e8 | ||
|
|
ce689bdff3 | ||
|
|
e23386ddc7 | ||
|
|
0f17d63774 | ||
|
|
4fc3949367 | ||
|
|
e19c04377b | ||
|
|
7c3f429c56 | ||
|
|
7558489ad0 |
No files matched your search
@@ -150,7 +150,7 @@
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-bom</artifactId>
|
||||
<version>2020.0.24</version> <!-- 3.4.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<version>2022.0.3</version> <!-- 3.5.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -296,7 +296,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.21.1</version>
|
||||
<version>0.22.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
|
||||
@@ -72,6 +72,9 @@ dynamoDbTables:
|
||||
redeemedReceipts:
|
||||
tableName: Example_RedeemedReceipts
|
||||
expiration: P30D # Duration of time until rows expire
|
||||
registrationRecovery:
|
||||
tableName: Example_RegistrationRecovery
|
||||
expiration: P300D # Duration of time until rows expire
|
||||
remoteConfig:
|
||||
tableName: Example_RemoteConfig
|
||||
reportMessage:
|
||||
@@ -80,9 +83,8 @@ dynamoDbTables:
|
||||
tableName: Example_ReservedUsernames
|
||||
subscriptions:
|
||||
tableName: Example_Subscriptions
|
||||
registrationRecovery:
|
||||
tableName: Example_RegistrationRecovery
|
||||
expiration: P300D # Duration of time until rows expire
|
||||
verificationSessions:
|
||||
tableName: Example_VerificationSessions
|
||||
|
||||
cacheCluster: # Redis server configuration for cache cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
+22
-1
@@ -381,6 +381,10 @@
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-core-micrometer</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
@@ -413,7 +417,14 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>1.20.0</version>
|
||||
<version>1.21.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.ganadist.sqlite4java</groupId>
|
||||
<artifactId>libsqlite4java-osx-aarch64</artifactId>
|
||||
<version>1.0.392</version>
|
||||
<type>dylib</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -560,6 +571,16 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M7</version>
|
||||
<configuration>
|
||||
<!-- work around PATCH not being a supported method on HttpUrlConnection -->
|
||||
<argLine>--add-opens=java.base/java.net=ALL-UNNAMED</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
|
||||
@@ -27,8 +27,6 @@ import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import io.dropwizard.setup.Bootstrap;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.metrics.MicrometerCommandLatencyRecorder;
|
||||
import io.lettuce.core.metrics.MicrometerOptions;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Meter.Id;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -76,6 +74,7 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.WebsocketRefreshApplicationEventListener;
|
||||
@@ -84,9 +83,11 @@ import org.whispersystems.textsecuregcm.badges.ResourceBundleLevelTranslator;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArtController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV3;
|
||||
@@ -109,6 +110,7 @@ import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
|
||||
import org.whispersystems.textsecuregcm.controllers.VerificationController;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
@@ -128,6 +130,7 @@ import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressException
|
||||
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.ApplicationShutdownMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.BufferPoolGauges;
|
||||
@@ -135,7 +138,6 @@ import org.whispersystems.textsecuregcm.metrics.CpuUsageGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.FileDescriptorGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.FreeMemoryGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.GarbageCollectionGauges;
|
||||
import org.whispersystems.textsecuregcm.metrics.LettuceMetricsMeterFilter;
|
||||
import org.whispersystems.textsecuregcm.metrics.MaxFileDescriptorGauge;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsRequestEventListener;
|
||||
@@ -208,11 +210,14 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import org.whispersystems.textsecuregcm.util.HostnameUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
import org.whispersystems.textsecuregcm.util.logging.LoggingUnhandledExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
@@ -230,7 +235,6 @@ import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
@@ -286,7 +290,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.ANDROID_REQUEST_COUNTER_NAME))
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.DESKTOP_REQUEST_COUNTER_NAME))
|
||||
.meterFilter(MeterFilter.denyNameStartsWith(MetricsRequestEventListener.IOS_REQUEST_COUNTER_NAME))
|
||||
.meterFilter(new LettuceMetricsMeterFilter())
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Id id, final DistributionStatisticConfig config) {
|
||||
@@ -379,17 +382,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
dynamoDbAsyncClient
|
||||
);
|
||||
|
||||
reactor.util.Metrics.MicrometerConfiguration.useRegistry(Metrics.globalRegistry);
|
||||
Schedulers.enableMetrics();
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getVerificationSessions().getTableName(), clock);
|
||||
|
||||
RedisClientFactory pubSubClientFactory = new RedisClientFactory("pubsub_cache",
|
||||
config.getPubsubCacheConfiguration().getUrl(), config.getPubsubCacheConfiguration().getReplicaUrls(),
|
||||
config.getPubsubCacheConfiguration().getCircuitBreakerConfiguration());
|
||||
ReplicatedJedisPool pubsubClient = pubSubClientFactory.getRedisClientPool();
|
||||
|
||||
MicrometerOptions options = MicrometerOptions.builder().build();
|
||||
ClientResources redisClientResources = ClientResources.builder()
|
||||
.commandLatencyRecorder(new MicrometerCommandLatencyRecorder(Metrics.globalRegistry, options)).build();
|
||||
ClientResources redisClientResources = ClientResources.builder().build();
|
||||
ConnectionEventLogger.logConnectionEvents(redisClientResources);
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", config.getCacheClusterConfiguration(), redisClientResources);
|
||||
@@ -475,6 +476,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
|
||||
RegistrationServiceClient registrationServiceClient = new RegistrationServiceClient(config.getRegistrationServiceConfiguration().getHost(), config.getRegistrationServiceConfiguration().getPort(), config.getRegistrationServiceConfiguration().getApiKey(), config.getRegistrationServiceConfiguration().getRegistrationCaCertificate(), registrationCallbackExecutor);
|
||||
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, backupServiceExecutor, config.getSecureBackupServiceConfiguration());
|
||||
@@ -522,16 +524,22 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, clientPresenceManager, backupCredentialsGenerator, rateLimiters);
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
registrationServiceClient, registrationRecoveryPasswordsManager);
|
||||
|
||||
ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(accountsManager);
|
||||
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
|
||||
accountsManager);
|
||||
reportMessageManager.addListener(reportedMessageMetricsListener);
|
||||
|
||||
AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
|
||||
DisabledPermittedAccountAuthenticator disabledPermittedAccountAuthenticator = new DisabledPermittedAccountAuthenticator(accountsManager);
|
||||
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
|
||||
final DisabledPermittedAccountAuthenticator disabledPermittedAccountAuthenticator = new DisabledPermittedAccountAuthenticator(
|
||||
accountsManager);
|
||||
|
||||
MessageSender messageSender = new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager, pushLatencyManager);
|
||||
ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
|
||||
TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager);
|
||||
final MessageSender messageSender = new MessageSender(clientPresenceManager, messagesManager,
|
||||
pushNotificationManager,
|
||||
pushLatencyManager);
|
||||
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager);
|
||||
|
||||
RecaptchaClient recaptchaClient = new RecaptchaClient(
|
||||
config.getRecaptchaConfiguration().getProjectPath(),
|
||||
@@ -622,11 +630,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(directoryQueue);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
|
||||
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker,
|
||||
rateLimiters, config.getTestDevices(), dynamicConfigurationManager);
|
||||
|
||||
StaticCredentialsProvider cdnCredentialsProvider = StaticCredentialsProvider
|
||||
.create(AwsBasicCredentials.create(
|
||||
config.getCdnConfiguration().getAccessKey(),
|
||||
config.getCdnConfiguration().getAccessSecret()));
|
||||
S3Client cdnS3Client = S3Client.builder()
|
||||
S3Client cdnS3Client = S3Client.builder()
|
||||
.credentialsProvider(cdnCredentialsProvider)
|
||||
.region(Region.of(config.getCdnConfiguration().getRegion()))
|
||||
.build();
|
||||
@@ -677,9 +688,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// these should be common, but use @Auth DisabledPermittedAccount, which isn’t supported yet on websocket
|
||||
environment.jersey().register(
|
||||
new AccountController(pendingAccountsManager, accountsManager, rateLimiters,
|
||||
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator, config.getTestDevices(),
|
||||
captchaChecker, pushNotificationManager, changeNumberManager, registrationLockVerificationManager,
|
||||
registrationRecoveryPasswordsManager, clock));
|
||||
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator,
|
||||
registrationCaptchaManager, pushNotificationManager, changeNumberManager,
|
||||
registrationLockVerificationManager, registrationRecoveryPasswordsManager, usernameHashZkProofVerifier, clock));
|
||||
|
||||
environment.jersey().register(new KeysController(rateLimiters, keys, accountsManager));
|
||||
|
||||
@@ -725,10 +736,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
}
|
||||
|
||||
if (reportSpamTokenProvider == null) {
|
||||
log.warn("No spam-reporting token providers found; using default (no-op) provider as a default");
|
||||
reportSpamTokenProvider = ReportSpamTokenProvider.noop();
|
||||
}
|
||||
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters),
|
||||
new ArtController(rateLimiters, artCredentialsGenerator),
|
||||
new AttachmentControllerV2(rateLimiters, config.getAwsAttachmentsConfiguration().getAccessKey(), config.getAwsAttachmentsConfiguration().getAccessSecret(), config.getAwsAttachmentsConfiguration().getRegion(), config.getAwsAttachmentsConfiguration().getBucket()),
|
||||
new AttachmentControllerV3(rateLimiters, config.getGcpAttachmentsConfiguration().getDomain(), config.getGcpAttachmentsConfiguration().getEmail(), config.getGcpAttachmentsConfiguration().getMaxSizeInBytes(), config.getGcpAttachmentsConfiguration().getPathPrefix(), config.getGcpAttachmentsConfiguration().getRsaSigningKey()),
|
||||
@@ -746,7 +760,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
|
||||
config.getCdnConfiguration().getBucket(), zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, registrationServiceClient, registrationLockVerificationManager,
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters),
|
||||
new RemoteConfigController(remoteConfigsManager, adminEventLogger,
|
||||
config.getRemoteConfigConfiguration().getAuthorizedTokens(),
|
||||
@@ -756,7 +770,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator),
|
||||
new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(),
|
||||
config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(),
|
||||
config.getCdnConfiguration().getBucket())
|
||||
config.getCdnConfiguration().getBucket()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters,
|
||||
clock)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
@@ -833,6 +850,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ServerRejectedExceptionMapper(),
|
||||
new ImpossiblePhoneNumberExceptionMapper(),
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
environment.jersey().register(exceptionMapper);
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.ForbiddenException;
|
||||
import javax.ws.rs.NotAuthorizedException;
|
||||
import javax.ws.rs.ServerErrorException;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
|
||||
public class PhoneVerificationTokenManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PhoneVerificationTokenManager.class);
|
||||
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
private static final long VERIFICATION_TIMEOUT_SECONDS = REGISTRATION_RPC_TIMEOUT.plusSeconds(1).getSeconds();
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
|
||||
public PhoneVerificationTokenManager(final RegistrationServiceClient registrationServiceClient,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager) {
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a {@link PhoneVerificationRequest} has a token that verifies the caller has confirmed access to the e164
|
||||
* number
|
||||
*
|
||||
* @param number the e164 presented for verification
|
||||
* @param request the request with exactly one verification token (RegistrationService sessionId or registration
|
||||
* recovery password)
|
||||
* @return if verification was successful, returns the verification type
|
||||
* @throws BadRequestException if the number does not match the sessionId’s number, or the remote service rejects
|
||||
* the session ID as invalid
|
||||
* @throws NotAuthorizedException if the session is not verified
|
||||
* @throws ForbiddenException if the recovery password is not valid
|
||||
* @throws InterruptedException if verification did not complete before a timeout
|
||||
*/
|
||||
public PhoneVerificationRequest.VerificationType verify(final String number, final PhoneVerificationRequest request)
|
||||
throws InterruptedException {
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType = request.verificationType();
|
||||
switch (verificationType) {
|
||||
case SESSION -> verifyBySessionId(number, request.decodeSessionId());
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(number, request.recoveryPassword());
|
||||
}
|
||||
|
||||
return verificationType;
|
||||
}
|
||||
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId) throws InterruptedException {
|
||||
try {
|
||||
final RegistrationServiceSession session = registrationServiceClient
|
||||
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
|
||||
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
|
||||
|
||||
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
|
||||
throw new BadRequestException("number does not match session");
|
||||
}
|
||||
if (!session.verified()) {
|
||||
throw new NotAuthorizedException("session not verified");
|
||||
}
|
||||
} catch (final ExecutionException e) {
|
||||
|
||||
if (e.getCause() instanceof StatusRuntimeException grpcRuntimeException) {
|
||||
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
}
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
|
||||
} catch (final CancellationException | TimeoutException e) {
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyByRecoveryPassword(final String number, final byte[] recoveryPassword)
|
||||
throws InterruptedException {
|
||||
try {
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(number, recoveryPassword)
|
||||
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!verified) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
}
|
||||
} catch (final ExecutionException | TimeoutException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -10,9 +10,9 @@ import java.time.Duration;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public record StoredVerificationCode(String code,
|
||||
public record StoredVerificationCode(@Nullable String code,
|
||||
long timestamp,
|
||||
String pushCode,
|
||||
@Nullable String pushCode,
|
||||
@Nullable byte[] sessionId) {
|
||||
|
||||
public static final Duration EXPIRATION = Duration.ofMinutes(10);
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class RegistrationCaptchaManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RegistrationCaptchaManager.class);
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Meter countryFilteredHostMeter = metricRegistry.meter(
|
||||
name(AccountController.class, "country_limited_host"));
|
||||
private final Meter rateLimitedHostMeter = metricRegistry.meter(name(AccountController.class, "rate_limited_host"));
|
||||
private final Meter rateLimitedPrefixMeter = metricRegistry.meter(
|
||||
name(AccountController.class, "rate_limited_prefix"));
|
||||
|
||||
private final CaptchaChecker captchaChecker;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final Map<String, Integer> testDevices;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
|
||||
public RegistrationCaptchaManager(final CaptchaChecker captchaChecker, final RateLimiters rateLimiters,
|
||||
final Map<String, Integer> testDevices,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.captchaChecker = captchaChecker;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.testDevices = testDevices;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public Optional<AssessmentResult> assessCaptcha(final Optional<String> captcha, final String sourceHost)
|
||||
throws IOException {
|
||||
return captcha.isPresent()
|
||||
? Optional.of(captchaChecker.verify(captcha.get(), sourceHost))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
public boolean requiresCaptcha(final String number, final String forwardedFor, String sourceHost,
|
||||
final boolean pushChallengeMatch) {
|
||||
if (testDevices.containsKey(number)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!pushChallengeMatch) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final String countryCode = Util.getCountryCode(number);
|
||||
final String region = Util.getRegion(number);
|
||||
|
||||
DynamicCaptchaConfiguration captchaConfig = dynamicConfigurationManager.getConfiguration()
|
||||
.getCaptchaConfiguration();
|
||||
|
||||
boolean countryFiltered = captchaConfig.getSignupCountryCodes().contains(countryCode) ||
|
||||
captchaConfig.getSignupRegions().contains(region);
|
||||
|
||||
try {
|
||||
rateLimiters.getSmsVoiceIpLimiter().validate(sourceHost);
|
||||
} catch (RateLimitExceededException e) {
|
||||
logger.info("Rate limit exceeded: {}, {} ({})", number, sourceHost, forwardedFor);
|
||||
rateLimitedHostMeter.mark();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
rateLimiters.getSmsVoicePrefixLimiter().validate(Util.getNumberPrefix(number));
|
||||
} catch (RateLimitExceededException e) {
|
||||
logger.info("Prefix rate limit exceeded: {}, {} ({})", number, sourceHost, forwardedFor);
|
||||
rateLimitedPrefixMeter.mark();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (countryFiltered) {
|
||||
countryFilteredHostMeter.mark();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+14
-5
@@ -58,11 +58,12 @@ public class DynamoDbTables {
|
||||
private final Table profiles;
|
||||
private final Table pushChallenge;
|
||||
private final TableWithExpiration redeemedReceipts;
|
||||
private final TableWithExpiration registrationRecovery;
|
||||
private final Table remoteConfig;
|
||||
private final Table reportMessage;
|
||||
private final Table reservedUsernames;
|
||||
private final Table subscriptions;
|
||||
private final TableWithExpiration registrationRecovery;
|
||||
private final Table verificationSessions;
|
||||
|
||||
public DynamoDbTables(
|
||||
@JsonProperty("accounts") final AccountsTableConfiguration accounts,
|
||||
@@ -77,11 +78,12 @@ public class DynamoDbTables {
|
||||
@JsonProperty("profiles") final Table profiles,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
|
||||
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
|
||||
@JsonProperty("remoteConfig") final Table remoteConfig,
|
||||
@JsonProperty("reportMessage") final Table reportMessage,
|
||||
@JsonProperty("reservedUsernames") final Table reservedUsernames,
|
||||
@JsonProperty("subscriptions") final Table subscriptions,
|
||||
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery) {
|
||||
@JsonProperty("verificationSessions") final Table verificationSessions) {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.deletedAccounts = deletedAccounts;
|
||||
@@ -95,11 +97,12 @@ public class DynamoDbTables {
|
||||
this.profiles = profiles;
|
||||
this.pushChallenge = pushChallenge;
|
||||
this.redeemedReceipts = redeemedReceipts;
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.remoteConfig = remoteConfig;
|
||||
this.reportMessage = reportMessage;
|
||||
this.reservedUsernames = reservedUsernames;
|
||||
this.subscriptions = subscriptions;
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.verificationSessions = verificationSessions;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@@ -174,6 +177,12 @@ public class DynamoDbTables {
|
||||
return redeemedReceipts;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getRegistrationRecovery() {
|
||||
return registrationRecovery;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getRemoteConfig() {
|
||||
@@ -200,7 +209,7 @@ public class DynamoDbTables {
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getRegistrationRecovery() {
|
||||
return registrationRecovery;
|
||||
public Table getVerificationSessions() {
|
||||
return verificationSessions;
|
||||
}
|
||||
}
|
||||
+14
@@ -29,6 +29,12 @@ public class RateLimitsConfiguration {
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration verifyPin = new RateLimitConfiguration(10, 1 / (24.0 * 60.0));
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration verificationCaptcha = new RateLimitConfiguration(10, 2);
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration verificationPushChallenge = new RateLimitConfiguration(5, 2);
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration registration = new RateLimitConfiguration(2, 2);
|
||||
|
||||
@@ -122,6 +128,14 @@ public class RateLimitsConfiguration {
|
||||
return verifyPin;
|
||||
}
|
||||
|
||||
public RateLimitConfiguration getVerificationCaptcha() {
|
||||
return verificationCaptcha;
|
||||
}
|
||||
|
||||
public RateLimitConfiguration getVerificationPushChallenge() {
|
||||
return verificationPushChallenge;
|
||||
}
|
||||
|
||||
public RateLimitConfiguration getRegistration() {
|
||||
return registration;
|
||||
}
|
||||
|
||||
+43
-70
@@ -28,7 +28,6 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -54,6 +53,7 @@ import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
@@ -66,8 +66,7 @@ import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
@@ -107,6 +106,7 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
|
||||
import org.whispersystems.textsecuregcm.util.Optionals;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@@ -116,9 +116,6 @@ public class AccountController {
|
||||
public static final int USERNAME_HASH_LENGTH = 32;
|
||||
private final Logger logger = LoggerFactory.getLogger(AccountController.class);
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Meter countryFilteredHostMeter = metricRegistry.meter(name(AccountController.class, "country_limited_host" ));
|
||||
private final Meter rateLimitedHostMeter = metricRegistry.meter(name(AccountController.class, "rate_limited_host" ));
|
||||
private final Meter rateLimitedPrefixMeter = metricRegistry.meter(name(AccountController.class, "rate_limited_prefix" ));
|
||||
private final Meter captchaRequiredMeter = metricRegistry.meter(name(AccountController.class, "captcha_required" ));
|
||||
|
||||
private static final String PUSH_CHALLENGE_COUNTER_NAME = name(AccountController.class, "pushChallenge");
|
||||
@@ -153,13 +150,13 @@ public class AccountController {
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final TurnTokenGenerator turnTokenGenerator;
|
||||
private final Map<String, Integer> testDevices;
|
||||
private final CaptchaChecker captchaChecker;
|
||||
private final RegistrationCaptchaManager registrationCaptchaManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
private final Clock clock;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -172,12 +169,12 @@ public class AccountController {
|
||||
RegistrationServiceClient registrationServiceClient,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
TurnTokenGenerator turnTokenGenerator,
|
||||
Map<String, Integer> testDevices,
|
||||
CaptchaChecker captchaChecker,
|
||||
RegistrationCaptchaManager registrationCaptchaManager,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ChangeNumberManager changeNumberManager,
|
||||
RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
Clock clock
|
||||
) {
|
||||
this.pendingAccounts = pendingAccounts;
|
||||
@@ -185,13 +182,13 @@ public class AccountController {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.testDevices = testDevices;
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.captchaChecker = captchaChecker;
|
||||
this.registrationCaptchaManager = registrationCaptchaManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -221,10 +218,28 @@ public class AccountController {
|
||||
throw new BadRequestException("Bad phone number");
|
||||
}
|
||||
|
||||
final String pushChallenge = generatePushChallenge();
|
||||
final byte[] sessionId = createRegistrationSession(phoneNumber);
|
||||
final StoredVerificationCode storedVerificationCode =
|
||||
new StoredVerificationCode(null, clock.millis(), pushChallenge, sessionId);
|
||||
final StoredVerificationCode storedVerificationCode;
|
||||
{
|
||||
final Optional<StoredVerificationCode> maybeStoredVerificationCode = pendingAccounts.getCodeForNumber(number);
|
||||
|
||||
if (maybeStoredVerificationCode.isPresent()) {
|
||||
final StoredVerificationCode existingStoredVerificationCode = maybeStoredVerificationCode.get();
|
||||
|
||||
if (StringUtils.isBlank(existingStoredVerificationCode.pushCode())) {
|
||||
storedVerificationCode = new StoredVerificationCode(
|
||||
existingStoredVerificationCode.code(),
|
||||
existingStoredVerificationCode.timestamp(),
|
||||
generatePushChallenge(),
|
||||
existingStoredVerificationCode.sessionId());
|
||||
} else {
|
||||
storedVerificationCode = existingStoredVerificationCode;
|
||||
}
|
||||
} else {
|
||||
final byte[] sessionId = createRegistrationSession(phoneNumber);
|
||||
storedVerificationCode = new StoredVerificationCode(null, clock.millis(), generatePushChallenge(), sessionId);
|
||||
new StoredVerificationCode(null, clock.millis(), generatePushChallenge(), sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
pendingAccounts.store(number, storedVerificationCode);
|
||||
pushNotificationManager.sendRegistrationChallengeNotification(pushToken, tokenType, storedVerificationCode.pushCode());
|
||||
@@ -256,9 +271,7 @@ public class AccountController {
|
||||
final String region = Util.getRegion(number);
|
||||
|
||||
// if there's a captcha, assess it, otherwise check if we need a captcha
|
||||
final Optional<AssessmentResult> assessmentResult = captcha.isPresent()
|
||||
? Optional.of(captchaChecker.verify(captcha.get(), sourceHost))
|
||||
: Optional.empty();
|
||||
final Optional<AssessmentResult> assessmentResult = registrationCaptchaManager.assessCaptcha(captcha, sourceHost);
|
||||
|
||||
assessmentResult.ifPresent(result ->
|
||||
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, Tags.of(
|
||||
@@ -278,7 +291,8 @@ public class AccountController {
|
||||
|
||||
final boolean requiresCaptcha = assessmentResult
|
||||
.map(result -> !result.valid())
|
||||
.orElseGet(() -> requiresCaptcha(number, transport, forwardedFor, sourceHost, pushChallengeMatch));
|
||||
.orElseGet(
|
||||
() -> registrationCaptchaManager.requiresCaptcha(number, forwardedFor, sourceHost, pushChallengeMatch));
|
||||
|
||||
if (requiresCaptcha) {
|
||||
captchaRequiredMeter.mark();
|
||||
@@ -335,8 +349,7 @@ public class AccountController {
|
||||
|
||||
final StoredVerificationCode storedVerificationCode = new StoredVerificationCode(null,
|
||||
clock.millis(),
|
||||
maybeStoredVerificationCode.map(StoredVerificationCode::pushCode).orElse(null),
|
||||
sessionId);
|
||||
maybeStoredVerificationCode.map(StoredVerificationCode::pushCode).orElse(null), sessionId);
|
||||
|
||||
pendingAccounts.store(number, storedVerificationCode);
|
||||
|
||||
@@ -406,8 +419,6 @@ public class AccountController {
|
||||
Account account = accounts.create(number, password, signalAgent, accountAttributes,
|
||||
existingAccount.map(Account::getBadges).orElseGet(ArrayList::new));
|
||||
|
||||
metricRegistry.meter(name(AccountController.class, "verify", Util.getCountryCode(number))).mark();
|
||||
|
||||
Metrics.counter(ACCOUNT_VERIFY_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
|
||||
Tag.of(REGION_TAG_NAME, Util.getRegion(number)),
|
||||
@@ -712,6 +723,12 @@ public class AccountController {
|
||||
@NotNull @Valid ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
|
||||
rateLimiters.getUsernameSetLimiter().validate(auth.getAccount().getUuid());
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
|
||||
} catch (final BaseUsernameException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
try {
|
||||
final Account account = accounts.confirmReservedUsernameHash(auth.getAccount(), confirmRequest.usernameHash());
|
||||
return account
|
||||
@@ -787,7 +804,7 @@ public class AccountController {
|
||||
// This shouldn't happen, so conservatively assume we're over the rate-limit
|
||||
// and indicate that the client should retry
|
||||
logger.error("Missing/bad Forwarded-For: {}", forwardedFor);
|
||||
return new RateLimitExceededException(Duration.ofHours(1));
|
||||
return new RateLimitExceededException(Duration.ofHours(1), true);
|
||||
});
|
||||
|
||||
rateLimiter.validate(mostRecentProxy);
|
||||
@@ -816,54 +833,10 @@ public class AccountController {
|
||||
return match;
|
||||
}
|
||||
|
||||
private boolean requiresCaptcha(String number, String transport, String forwardedFor, String sourceHost, boolean pushChallengeMatch) {
|
||||
if (testDevices.containsKey(number)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!pushChallengeMatch) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final String countryCode = Util.getCountryCode(number);
|
||||
final String region = Util.getRegion(number);
|
||||
|
||||
DynamicCaptchaConfiguration captchaConfig = dynamicConfigurationManager.getConfiguration()
|
||||
.getCaptchaConfiguration();
|
||||
|
||||
boolean countryFiltered = captchaConfig.getSignupCountryCodes().contains(countryCode) ||
|
||||
captchaConfig.getSignupRegions().contains(region);
|
||||
|
||||
try {
|
||||
rateLimiters.getSmsVoiceIpLimiter().validate(sourceHost);
|
||||
} catch (RateLimitExceededException e) {
|
||||
logger.info("Rate limit exceeded: {}, {}, {} ({})", transport, number, sourceHost, forwardedFor);
|
||||
rateLimitedHostMeter.mark();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
rateLimiters.getSmsVoicePrefixLimiter().validate(Util.getNumberPrefix(number));
|
||||
} catch (RateLimitExceededException e) {
|
||||
logger.info("Prefix rate limit exceeded: {}, {}, {} ({})", transport, number, sourceHost, forwardedFor);
|
||||
rateLimitedPrefixMeter.mark();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (countryFiltered) {
|
||||
countryFilteredHostMeter.mark();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
public void deleteAccount(@Auth AuthenticatedAccount auth) throws InterruptedException {
|
||||
public void deleteAccount(@Auth DisabledPermittedAuthenticatedAccount auth) throws InterruptedException {
|
||||
accounts.delete(auth.getAccount(), AccountsManager.DeletionReason.USER_REQUEST);
|
||||
}
|
||||
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.Optional;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.ForbiddenException;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
|
||||
@Path("/v2/accounts")
|
||||
public class AccountControllerV2 {
|
||||
|
||||
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
|
||||
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public AccountControllerV2(final AccountsManager accountsManager, final ChangeNumberManager changeNumberManager,
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager, final RateLimiters rateLimiters) {
|
||||
this.accountsManager = accountsManager;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/number")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedAccount authenticatedAccount,
|
||||
@NotNull @Valid final ChangeNumberRequest request, @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent)
|
||||
throws RateLimitExceededException, InterruptedException {
|
||||
|
||||
if (!authenticatedAccount.getAuthenticatedDevice().isMaster()) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
final String number = request.number();
|
||||
|
||||
// Only verify and check reglock if there's a data change to be made...
|
||||
if (!authenticatedAccount.getAccount().getNumber().equals(number)) {
|
||||
|
||||
RateLimiter.adaptLegacyException(() -> rateLimiters.getRegistrationLimiter().validate(number));
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(number,
|
||||
request);
|
||||
|
||||
final Optional<Account> existingAccount = accountsManager.getByE164(number);
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock());
|
||||
}
|
||||
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
}
|
||||
|
||||
// ...but always attempt to make the change in case a client retries and needs to re-send messages
|
||||
try {
|
||||
final Account updatedAccount = changeNumberManager.changeNumber(
|
||||
authenticatedAccount.getAccount(),
|
||||
request.number(),
|
||||
request.pniIdentityKey(),
|
||||
request.devicePniSignedPrekeys(),
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds());
|
||||
|
||||
return new AccountIdentityResponse(
|
||||
updatedAccount.getUuid(),
|
||||
updatedAccount.getNumber(),
|
||||
updatedAccount.getPhoneNumberIdentifier(),
|
||||
updatedAccount.getUsernameHash().orElse(null),
|
||||
updatedAccount.isStorageSupported());
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/phone_number_discoverability")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public void setPhoneNumberDiscoverability(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability
|
||||
) {
|
||||
accountsManager.update(auth.getAccount(), a -> a.setDiscoverableByPhoneNumber(
|
||||
phoneNumberDiscoverability.discoverableByPhoneNumber()));
|
||||
}
|
||||
}
|
||||
-14
@@ -50,7 +50,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v2/keys")
|
||||
@@ -60,11 +59,8 @@ public class KeysController {
|
||||
private final Keys keys;
|
||||
private final AccountsManager accounts;
|
||||
|
||||
private static final String PREKEY_REQUEST_COUNTER_NAME = name(KeysController.class, "preKeyGet");
|
||||
private static final String IDENTITY_KEY_CHANGE_FORBIDDEN_COUNTER_NAME = name(KeysController.class, "identityKeyChangeForbidden");
|
||||
|
||||
private static final String SOURCE_COUNTRY_TAG_NAME = "sourceCountry";
|
||||
private static final String INTERNATIONAL_TAG_NAME = "international";
|
||||
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
|
||||
private static final String HAS_IDENTITY_KEY_TAG_NAME = "hasIdentityKey";
|
||||
|
||||
@@ -171,16 +167,6 @@ public class KeysController {
|
||||
target = maybeTarget.orElseThrow();
|
||||
}
|
||||
|
||||
{
|
||||
final String sourceCountryCode = account.map(a -> Util.getCountryCode(a.getNumber())).orElse("0");
|
||||
final String targetCountryCode = Util.getCountryCode(target.getNumber());
|
||||
|
||||
Metrics.counter(PREKEY_REQUEST_COUNTER_NAME, Tags.of(
|
||||
SOURCE_COUNTRY_TAG_NAME, sourceCountryCode,
|
||||
INTERNATIONAL_TAG_NAME, String.valueOf(!sourceCountryCode.equals(targetCountryCode))
|
||||
)).increment();
|
||||
}
|
||||
|
||||
if (account.isPresent()) {
|
||||
rateLimiters.getPreKeysLimiter().validate(
|
||||
account.get().getUuid() + "." + auth.get().getAuthenticatedDevice().getId() + "__" + targetUuid
|
||||
|
||||
+7
-4
@@ -603,7 +603,8 @@ public class MessageController {
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@PathParam("source") String source,
|
||||
@PathParam("messageGuid") UUID messageGuid,
|
||||
@Nullable @Valid SpamReport spamReport
|
||||
@Nullable @Valid SpamReport spamReport,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent
|
||||
) {
|
||||
|
||||
final Optional<String> sourceNumber;
|
||||
@@ -636,11 +637,13 @@ public class MessageController {
|
||||
|
||||
UUID spamReporterUuid = auth.getAccount().getUuid();
|
||||
|
||||
// spam report token is optional, but if provided ensure it is valid base64.
|
||||
// spam report token is optional, but if provided ensure it is valid base64 and non-empty.
|
||||
final Optional<byte[]> maybeSpamReportToken =
|
||||
spamReport != null ? Optional.of(spamReport.token()) : Optional.empty();
|
||||
Optional.ofNullable(spamReport)
|
||||
.flatMap(r -> Optional.ofNullable(r.token()))
|
||||
.filter(t -> t.length > 0);
|
||||
|
||||
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken);
|
||||
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent);
|
||||
|
||||
return Response.status(Status.ACCEPTED)
|
||||
.build();
|
||||
|
||||
+10
-8
@@ -64,7 +64,6 @@ import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -178,24 +177,27 @@ public class ProfileController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public Response setProfile(@Auth AuthenticatedAccount auth, @NotNull @Valid CreateProfileRequest request) {
|
||||
|
||||
final Optional<VersionedProfile> currentProfile = profilesManager.get(auth.getAccount().getUuid(),
|
||||
request.getVersion());
|
||||
|
||||
if (StringUtils.isNotBlank(request.getPaymentAddress())) {
|
||||
final boolean hasDisallowedPrefix =
|
||||
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
|
||||
.anyMatch(prefix -> auth.getAccount().getNumber().startsWith(prefix));
|
||||
|
||||
if (hasDisallowedPrefix) {
|
||||
return Response.status(Status.FORBIDDEN).build();
|
||||
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::getPaymentAddress).isEmpty()) {
|
||||
return Response.status(Response.Status.FORBIDDEN).build();
|
||||
}
|
||||
}
|
||||
|
||||
Optional<VersionedProfile> currentProfile = profilesManager.get(auth.getAccount().getUuid(), request.getVersion());
|
||||
|
||||
Optional<String> currentAvatar = Optional.empty();
|
||||
if (currentProfile.isPresent() && currentProfile.get().getAvatar() != null && currentProfile.get().getAvatar().startsWith("profiles/")) {
|
||||
if (currentProfile.isPresent() && currentProfile.get().getAvatar() != null && currentProfile.get().getAvatar()
|
||||
.startsWith("profiles/")) {
|
||||
currentAvatar = Optional.of(currentProfile.get().getAvatar());
|
||||
}
|
||||
|
||||
String avatar = switch (request.getAvatarChange()) {
|
||||
final String avatar = switch (request.getAvatarChange()) {
|
||||
case UNCHANGED -> currentAvatar.orElse(null);
|
||||
case CLEAR -> null;
|
||||
case UPDATE -> generateAvatarObjectName();
|
||||
@@ -218,7 +220,7 @@ public class ProfileController {
|
||||
.build()));
|
||||
}
|
||||
|
||||
List<AccountBadge> updatedBadges = request.getBadges()
|
||||
final List<AccountBadge> updatedBadges = request.getBadges()
|
||||
.map(badges -> mergeBadgeIdsWithExistingAccountBadges(badges, auth.getAccount().getBadges()))
|
||||
.orElseGet(() -> auth.getAccount().getBadges());
|
||||
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ public class ProvisioningController {
|
||||
rateLimiters.getMessagesLimiter().validate(auth.getAccount().getUuid());
|
||||
|
||||
if (!provisioningManager.sendProvisioningMessage(new ProvisioningAddress(destinationName, 0),
|
||||
Base64.getMimeDecoder().decode(message.getBody()))) {
|
||||
Base64.getMimeDecoder().decode(message.body()))) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
+10
-3
@@ -10,20 +10,27 @@ import javax.annotation.Nullable;
|
||||
|
||||
public class RateLimitExceededException extends Exception {
|
||||
|
||||
private final @Nullable
|
||||
Duration retryDuration;
|
||||
@Nullable
|
||||
private final Duration retryDuration;
|
||||
private final boolean legacy;
|
||||
|
||||
/**
|
||||
* Constructs a new exception indicating when it may become safe to retry
|
||||
*
|
||||
* @param retryDuration A duration to wait before retrying, null if no duration can be indicated
|
||||
* @param legacy whether to use a legacy status code when mapping the exception to an HTTP response
|
||||
*/
|
||||
public RateLimitExceededException(final @Nullable Duration retryDuration) {
|
||||
public RateLimitExceededException(@Nullable final Duration retryDuration, final boolean legacy) {
|
||||
super(null, null, true, false);
|
||||
this.retryDuration = retryDuration;
|
||||
this.legacy = legacy;
|
||||
}
|
||||
|
||||
public Optional<Duration> getRetryDuration() {
|
||||
return Optional.ofNullable(retryDuration);
|
||||
}
|
||||
|
||||
public boolean isLegacy() {
|
||||
return legacy;
|
||||
}
|
||||
}
|
||||
+11
-48
@@ -13,41 +13,31 @@ import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.ClientErrorException;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.NotAuthorizedException;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.ServerErrorException;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationSession;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
@@ -69,19 +59,16 @@ public class RegistrationController {
|
||||
private static final String REGION_CODE_TAG_NAME = "regionCode";
|
||||
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
|
||||
|
||||
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public RegistrationController(final AccountsManager accounts,
|
||||
final RegistrationServiceClient registrationServiceClient,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager, final RateLimiters rateLimiters) {
|
||||
this.accounts = accounts;
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
@@ -96,37 +83,13 @@ public class RegistrationController {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final RegistrationRequest registrationRequest) throws RateLimitExceededException, InterruptedException {
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(registrationRequest.sessionId());
|
||||
|
||||
final byte[] sessionId;
|
||||
try {
|
||||
sessionId = Base64.getDecoder().decode(registrationRequest.sessionId());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new ClientErrorException("Malformed session ID", HttpStatus.SC_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
final String number = authorizationHeader.getUsername();
|
||||
final String password = authorizationHeader.getPassword();
|
||||
|
||||
final String verificationType = "phoneNumberVerification";
|
||||
try {
|
||||
final Optional<RegistrationSession> maybeSession = registrationServiceClient.getSession(sessionId,
|
||||
REGISTRATION_RPC_TIMEOUT)
|
||||
.get(REGISTRATION_RPC_TIMEOUT.plusSeconds(1).getSeconds(), TimeUnit.SECONDS);
|
||||
RateLimiter.adaptLegacyException(() -> rateLimiters.getRegistrationLimiter().validate(number));
|
||||
|
||||
final RegistrationSession session = maybeSession.orElseThrow(
|
||||
() -> new NotAuthorizedException("session not verified"));
|
||||
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
|
||||
throw new BadRequestException("number does not match session");
|
||||
}
|
||||
if (!session.verified()) {
|
||||
throw new NotAuthorizedException("session not verified");
|
||||
}
|
||||
|
||||
} catch (final CancellationException | ExecutionException | TimeoutException e) {
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(number,
|
||||
registrationRequest);
|
||||
|
||||
final Optional<Account> existingAccount = accounts.getByE164(number);
|
||||
|
||||
@@ -153,7 +116,7 @@ public class RegistrationController {
|
||||
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(number)),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType)))
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
|
||||
return new AccountIdentityResponse(account.getUuid(),
|
||||
|
||||
+14
-5
@@ -16,6 +16,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.stripe.exception.StripeException;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.math.BigDecimal;
|
||||
import java.security.InvalidKeyException;
|
||||
@@ -51,6 +52,7 @@ import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
import javax.ws.rs.ForbiddenException;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.InternalServerErrorException;
|
||||
import javax.ws.rs.NotFoundException;
|
||||
import javax.ws.rs.POST;
|
||||
@@ -947,7 +949,9 @@ public class SubscriptionController {
|
||||
@Path("/boost/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createBoostReceiptCredentials(@NotNull @Valid CreateBoostReceiptCredentialsRequest request) {
|
||||
public CompletableFuture<Response> createBoostReceiptCredentials(
|
||||
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
|
||||
final SubscriptionProcessorManager manager = getManagerForProcessor(request.processor);
|
||||
|
||||
@@ -1006,8 +1010,10 @@ public class SubscriptionController {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
|
||||
PROCESSOR_TAG_NAME, manager.getProcessor().toString(),
|
||||
TYPE_TAG_NAME, "boost")
|
||||
Tags.of(
|
||||
Tag.of(PROCESSOR_TAG_NAME, manager.getProcessor().toString()),
|
||||
Tag.of(TYPE_TAG_NAME, "boost"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new CreateBoostReceiptCredentialsResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
@@ -1236,6 +1242,7 @@ public class SubscriptionController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createSubscriptionReceiptCredentials(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid GetReceiptCredentialsRequest request) {
|
||||
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
|
||||
@@ -1268,8 +1275,10 @@ public class SubscriptionController {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
|
||||
PROCESSOR_TAG_NAME, manager.getProcessor().toString(),
|
||||
TYPE_TAG_NAME, "subscription")
|
||||
Tags.of(
|
||||
Tag.of(PROCESSOR_TAG_NAME, manager.getProcessor().toString()),
|
||||
Tag.of(TYPE_TAG_NAME, "subscription"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
|
||||
+676
@@ -0,0 +1,676 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.ClientErrorException;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.ForbiddenException;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.NotFoundException;
|
||||
import javax.ws.rs.PATCH;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.ServerErrorException;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.entities.SubmitVerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotification;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.registration.ClientType;
|
||||
import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceException;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@Path("/v1/verification")
|
||||
public class VerificationController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VerificationController.class);
|
||||
|
||||
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
private static final Duration DYNAMODB_TIMEOUT = Duration.ofSeconds(5);
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private static final String PUSH_CHALLENGE_COUNTER_NAME = name(VerificationController.class, "pushChallenge");
|
||||
private static final String CHALLENGE_PRESENT_TAG_NAME = "present";
|
||||
private static final String CHALLENGE_MATCH_TAG_NAME = "matches";
|
||||
private static final String CAPTCHA_ATTEMPT_COUNTER_NAME = name(VerificationController.class, "captcha");
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
private static final String REGION_CODE_TAG_NAME = "regionCode";
|
||||
private static final String SCORE_TAG_NAME = "score";
|
||||
private static final String CODE_REQUESTED_COUNTER_NAME = name(VerificationController.class, "codeRequested");
|
||||
private static final String VERIFICATION_TRANSPORT_TAG_NAME = "transport";
|
||||
private static final String VERIFIED_COUNTER_NAME = name(VerificationController.class, "verified");
|
||||
private static final String SUCCESS_TAG_NAME = "success";
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final VerificationSessionManager verificationSessionManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final RegistrationCaptchaManager registrationCaptchaManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
public VerificationController(final RegistrationServiceClient registrationServiceClient,
|
||||
final VerificationSessionManager verificationSessionManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RegistrationCaptchaManager registrationCaptchaManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager, final RateLimiters rateLimiters,
|
||||
final Clock clock) {
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.registrationCaptchaManager = registrationCaptchaManager;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/session")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid CreateVerificationSessionRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
|
||||
request.getUpdateVerificationSessionRequest());
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber;
|
||||
try {
|
||||
phoneNumber = PhoneNumberUtil.getInstance().parse(request.getNumber(), null);
|
||||
} catch (final NumberParseException e) {
|
||||
throw new ServerErrorException("could not parse already validated number", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession;
|
||||
try {
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSessionSession(phoneNumber,
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CancellationException e) {
|
||||
|
||||
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
|
||||
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException re) {
|
||||
RateLimiter.adaptLegacyException(() -> {
|
||||
throw re;
|
||||
});
|
||||
}
|
||||
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
|
||||
}
|
||||
|
||||
VerificationSession verificationSession = new VerificationSession(null, new ArrayList<>(),
|
||||
Collections.emptyList(), false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration());
|
||||
|
||||
verificationSession = handlePushToken(pushTokenAndType, verificationSession);
|
||||
// unconditionally request a captcha -- it will either be the only requested information, or a fallback
|
||||
// if a push challenge sent in `handlePushToken` doesn't arrive in time
|
||||
verificationSession.requestedInformation().add(VerificationSession.Information.CAPTCHA);
|
||||
|
||||
storeVerificationSession(registrationServiceSession, verificationSession);
|
||||
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@FilterSpam
|
||||
@PATCH
|
||||
@Path("/session/{sessionId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse updateSession(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(com.google.common.net.HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest) {
|
||||
|
||||
final String sourceHost = HeaderUtils.getMostRecentProxy(forwardedFor).orElseThrow();
|
||||
|
||||
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
|
||||
updateVerificationSessionRequest);
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
try {
|
||||
// these handle* methods ordered from least likely to fail to most, so take care when considering a change
|
||||
verificationSession = handlePushToken(pushTokenAndType, verificationSession);
|
||||
|
||||
verificationSession = handlePushChallenge(updateVerificationSessionRequest, registrationServiceSession,
|
||||
verificationSession);
|
||||
|
||||
verificationSession = handleCaptcha(sourceHost, updateVerificationSessionRequest, registrationServiceSession,
|
||||
verificationSession, userAgent);
|
||||
} catch (final RateLimitExceededException e) {
|
||||
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession, registrationServiceSession,
|
||||
e.getRetryDuration());
|
||||
throw new ClientErrorException(response);
|
||||
|
||||
} catch (final ForbiddenException e) {
|
||||
|
||||
throw new ClientErrorException(Response.status(Response.Status.FORBIDDEN)
|
||||
.entity(buildResponse(registrationServiceSession, verificationSession))
|
||||
.build());
|
||||
|
||||
} finally {
|
||||
// Each of the handle* methods may update requestedInformation, submittedInformation, and allowedToRequestCode,
|
||||
// and we want to be sure to store a changes, even if a later method throws
|
||||
updateStoredVerificationSession(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
private void storeVerificationSession(final RegistrationServiceSession registrationServiceSession,
|
||||
final VerificationSession verificationSession) {
|
||||
verificationSessionManager.insert(registrationServiceSession.encodedSessionId(), verificationSession)
|
||||
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
|
||||
.join();
|
||||
}
|
||||
|
||||
private void updateStoredVerificationSession(final RegistrationServiceSession registrationServiceSession,
|
||||
final VerificationSession verificationSession) {
|
||||
verificationSessionManager.update(registrationServiceSession.encodedSessionId(), verificationSession)
|
||||
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
|
||||
.join();
|
||||
}
|
||||
|
||||
/**
|
||||
* If {@code pushTokenAndType} values are not {@code null}, sends a push challenge. If there is no existing push
|
||||
* challenge in the session, one will be created, set on the returned session record, and
|
||||
* {@link VerificationSession#requestedInformation()} will be updated.
|
||||
*/
|
||||
private VerificationSession handlePushToken(
|
||||
final Pair<String, PushNotification.TokenType> pushTokenAndType, VerificationSession verificationSession) {
|
||||
|
||||
if (pushTokenAndType.first() != null) {
|
||||
|
||||
if (verificationSession.pushChallenge() == null) {
|
||||
|
||||
final List<VerificationSession.Information> requestedInformation = new ArrayList<>();
|
||||
requestedInformation.add(VerificationSession.Information.PUSH_CHALLENGE);
|
||||
requestedInformation.addAll(verificationSession.requestedInformation());
|
||||
|
||||
verificationSession = new VerificationSession(generatePushChallenge(), requestedInformation,
|
||||
verificationSession.submittedInformation(), verificationSession.allowedToRequestCode(),
|
||||
verificationSession.createdTimestamp(), clock.millis(), verificationSession.remoteExpirationSeconds()
|
||||
);
|
||||
}
|
||||
|
||||
pushNotificationManager.sendRegistrationChallengeNotification(pushTokenAndType.first(), pushTokenAndType.second(),
|
||||
verificationSession.pushChallenge());
|
||||
}
|
||||
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a push challenge value is present, compares against the stored value. If they match, then
|
||||
* {@link VerificationSession.Information#PUSH_CHALLENGE} is removed from requested information, added to submitted
|
||||
* information, and {@link VerificationSession#allowedToRequestCode()} is re-evaluated.
|
||||
*
|
||||
* @throws ForbiddenException if values to not match.
|
||||
* @throws RateLimitExceededException if too many push challenges have been submitted
|
||||
*/
|
||||
private VerificationSession handlePushChallenge(
|
||||
final UpdateVerificationSessionRequest updateVerificationSessionRequest,
|
||||
final RegistrationServiceSession registrationServiceSession,
|
||||
VerificationSession verificationSession) throws RateLimitExceededException {
|
||||
|
||||
if (verificationSession.submittedInformation()
|
||||
.contains(VerificationSession.Information.PUSH_CHALLENGE)) {
|
||||
// skip if a challenge has already been submitted
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
final boolean pushChallengePresent = updateVerificationSessionRequest.pushChallenge() != null;
|
||||
if (pushChallengePresent) {
|
||||
RateLimiter.adaptLegacyException(
|
||||
() -> rateLimiters.getVerificationPushChallengeLimiter()
|
||||
.validate(registrationServiceSession.encodedSessionId()));
|
||||
}
|
||||
|
||||
final boolean pushChallengeMatches;
|
||||
if (pushChallengePresent && verificationSession.pushChallenge() != null) {
|
||||
pushChallengeMatches = MessageDigest.isEqual(
|
||||
updateVerificationSessionRequest.pushChallenge().getBytes(StandardCharsets.UTF_8),
|
||||
verificationSession.pushChallenge().getBytes(StandardCharsets.UTF_8));
|
||||
} else {
|
||||
pushChallengeMatches = false;
|
||||
}
|
||||
|
||||
Metrics.counter(PUSH_CHALLENGE_COUNTER_NAME,
|
||||
COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number()),
|
||||
REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number()),
|
||||
CHALLENGE_PRESENT_TAG_NAME, Boolean.toString(pushChallengePresent),
|
||||
CHALLENGE_MATCH_TAG_NAME, Boolean.toString(pushChallengeMatches))
|
||||
.increment();
|
||||
|
||||
if (pushChallengeMatches) {
|
||||
final List<VerificationSession.Information> submittedInformation = new ArrayList<>(
|
||||
verificationSession.submittedInformation());
|
||||
submittedInformation.add(VerificationSession.Information.PUSH_CHALLENGE);
|
||||
|
||||
final List<VerificationSession.Information> requestedInformation = new ArrayList<>(
|
||||
verificationSession.requestedInformation());
|
||||
// a push challenge satisfies a requested captcha
|
||||
requestedInformation.remove(VerificationSession.Information.CAPTCHA);
|
||||
final boolean allowedToRequestCode = (verificationSession.allowedToRequestCode()
|
||||
|| requestedInformation.remove(VerificationSession.Information.PUSH_CHALLENGE))
|
||||
&& requestedInformation.isEmpty();
|
||||
|
||||
verificationSession = new VerificationSession(verificationSession.pushChallenge(), requestedInformation,
|
||||
submittedInformation, allowedToRequestCode, verificationSession.createdTimestamp(), clock.millis(),
|
||||
verificationSession.remoteExpirationSeconds());
|
||||
|
||||
} else if (pushChallengePresent) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a captcha value is present, it is assessed. If it is valid, then {@link VerificationSession.Information#CAPTCHA}
|
||||
* is removed from requested information, added to submitted information, and
|
||||
* {@link VerificationSession#allowedToRequestCode()} is re-evaluated.
|
||||
*
|
||||
* @throws ForbiddenException if assessment is not valid.
|
||||
* @throws RateLimitExceededException if too many captchas have been submitted
|
||||
*/
|
||||
private VerificationSession handleCaptcha(final String sourceHost,
|
||||
final UpdateVerificationSessionRequest updateVerificationSessionRequest,
|
||||
final RegistrationServiceSession registrationServiceSession,
|
||||
VerificationSession verificationSession,
|
||||
final String userAgent) throws RateLimitExceededException {
|
||||
|
||||
if (updateVerificationSessionRequest.captcha() == null) {
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
RateLimiter.adaptLegacyException(
|
||||
() -> rateLimiters.getVerificationCaptchaLimiter().validate(registrationServiceSession.encodedSessionId()));
|
||||
|
||||
final AssessmentResult assessmentResult;
|
||||
try {
|
||||
assessmentResult = registrationCaptchaManager.assessCaptcha(
|
||||
Optional.of(updateVerificationSessionRequest.captcha()), sourceHost)
|
||||
.orElseThrow(() -> new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR));
|
||||
|
||||
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, Tags.of(
|
||||
Tag.of(SUCCESS_TAG_NAME, String.valueOf(assessmentResult.valid())),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
|
||||
Tag.of(SCORE_TAG_NAME, assessmentResult.score())))
|
||||
.increment();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
if (assessmentResult.valid()) {
|
||||
final List<VerificationSession.Information> submittedInformation = new ArrayList<>(
|
||||
verificationSession.submittedInformation());
|
||||
submittedInformation.add(VerificationSession.Information.CAPTCHA);
|
||||
|
||||
final List<VerificationSession.Information> requestedInformation = new ArrayList<>(
|
||||
verificationSession.requestedInformation());
|
||||
// a captcha satisfies a push challenge, in case of push deliverability issues
|
||||
requestedInformation.remove(VerificationSession.Information.PUSH_CHALLENGE);
|
||||
final boolean allowedToRequestCode = (verificationSession.allowedToRequestCode()
|
||||
|| requestedInformation.remove(VerificationSession.Information.CAPTCHA))
|
||||
&& requestedInformation.isEmpty();
|
||||
|
||||
verificationSession = new VerificationSession(verificationSession.pushChallenge(), requestedInformation,
|
||||
submittedInformation, allowedToRequestCode, verificationSession.createdTimestamp(), clock.millis(),
|
||||
verificationSession.remoteExpirationSeconds());
|
||||
} else {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/session/{sessionId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse getSession(@PathParam("sessionId") final String encodedSessionId) {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
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 {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
throw new ClientErrorException(
|
||||
Response.status(Response.Status.CONFLICT)
|
||||
.entity(buildResponse(registrationServiceSession, verificationSession))
|
||||
.build());
|
||||
}
|
||||
|
||||
if (!verificationSession.allowedToRequestCode()) {
|
||||
final Response.Status status = verificationSession.requestedInformation().isEmpty()
|
||||
? Response.Status.TOO_MANY_REQUESTS
|
||||
: Response.Status.CONFLICT;
|
||||
|
||||
throw new ClientErrorException(
|
||||
Response.status(status)
|
||||
.entity(buildResponse(registrationServiceSession, verificationSession))
|
||||
.build());
|
||||
}
|
||||
|
||||
final MessageTransport messageTransport = verificationCodeRequest.transport().toMessageTransport();
|
||||
|
||||
final ClientType clientType = switch (verificationCodeRequest.client()) {
|
||||
case "ios" -> ClientType.IOS;
|
||||
case "android-2021-03" -> ClientType.ANDROID_WITH_FCM;
|
||||
default -> {
|
||||
if (StringUtils.startsWithIgnoreCase(verificationCodeRequest.client(), "android")) {
|
||||
yield ClientType.ANDROID_WITHOUT_FCM;
|
||||
}
|
||||
yield ClientType.UNKNOWN;
|
||||
}
|
||||
};
|
||||
|
||||
final RegistrationServiceSession resultSession;
|
||||
try {
|
||||
resultSession = registrationServiceClient.sendVerificationCode(registrationServiceSession.id(),
|
||||
messageTransport,
|
||||
clientType,
|
||||
acceptLanguage.orElse(null), REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CancellationException e) {
|
||||
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
|
||||
if (unwrappedException instanceof RateLimitExceededException rateLimitExceededException) {
|
||||
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession, ve.getRegistrationSession(),
|
||||
ve.getRetryDuration());
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
|
||||
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null), false);
|
||||
} else if (unwrappedException instanceof RegistrationServiceException registrationServiceException) {
|
||||
|
||||
throw registrationServiceException.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> new ClientErrorException(
|
||||
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
|
||||
.orElseGet(NotFoundException::new);
|
||||
|
||||
} else if (unwrappedException instanceof RegistrationServiceSenderException) {
|
||||
|
||||
throw unwrappedException;
|
||||
|
||||
} else {
|
||||
logger.error("Registration service failure", unwrappedException);
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(CODE_REQUESTED_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
|
||||
Tag.of(VERIFICATION_TRANSPORT_TAG_NAME, verificationCodeRequest.transport().toString())))
|
||||
.increment();
|
||||
|
||||
return buildResponse(resultSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
final VerificationSessionResponse verificationSessionResponse = buildResponse(registrationServiceSession,
|
||||
verificationSession);
|
||||
|
||||
throw new ClientErrorException(
|
||||
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build());
|
||||
}
|
||||
|
||||
final RegistrationServiceSession resultSession;
|
||||
try {
|
||||
resultSession = registrationServiceClient.checkVerificationCodeSession(registrationServiceSession.id(),
|
||||
submitVerificationCodeRequest.code(),
|
||||
REGISTRATION_RPC_TIMEOUT)
|
||||
.join();
|
||||
} catch (final CancellationException e) {
|
||||
logger.warn("Unexpected cancellation from registration service", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
|
||||
if (unwrappedException instanceof RateLimitExceededException rateLimitExceededException) {
|
||||
|
||||
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession, ve.getRegistrationSession(),
|
||||
ve.getRetryDuration());
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
|
||||
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null), false);
|
||||
|
||||
} else if (unwrappedException instanceof RegistrationServiceException registrationServiceException) {
|
||||
|
||||
throw registrationServiceException.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> new ClientErrorException(
|
||||
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
|
||||
.orElseGet(NotFoundException::new);
|
||||
|
||||
} else {
|
||||
logger.error("Registration service failure", unwrappedException);
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
if (resultSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
|
||||
}
|
||||
|
||||
Metrics.counter(VERIFIED_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
|
||||
Tag.of(SUCCESS_TAG_NAME, Boolean.toString(resultSession.verified()))))
|
||||
.increment();
|
||||
|
||||
return buildResponse(resultSession, verificationSession);
|
||||
}
|
||||
|
||||
private Response buildResponseForRateLimitExceeded(final VerificationSession verificationSession,
|
||||
final RegistrationServiceSession registrationServiceSession,
|
||||
final Optional<Duration> retryDuration) {
|
||||
|
||||
final Response.ResponseBuilder responseBuilder = Response.status(Response.Status.TOO_MANY_REQUESTS)
|
||||
.entity(buildResponse(registrationServiceSession, verificationSession));
|
||||
|
||||
retryDuration
|
||||
.filter(d -> !d.isNegative())
|
||||
.ifPresent(d -> responseBuilder.header(HttpHeaders.RETRY_AFTER, d.toSeconds()));
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ClientErrorException with {@code 422} status if the ID cannot be decoded
|
||||
* @throws javax.ws.rs.NotFoundException if the ID cannot be found
|
||||
*/
|
||||
private RegistrationServiceSession retrieveRegistrationServiceSession(final String encodedSessionId) {
|
||||
final byte[] sessionId;
|
||||
|
||||
try {
|
||||
sessionId = decodeSessionId(encodedSessionId);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new ClientErrorException("Malformed session ID", HttpStatus.SC_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
try {
|
||||
final RegistrationServiceSession registrationServiceSession = registrationServiceClient.getSession(sessionId,
|
||||
REGISTRATION_RPC_TIMEOUT).join()
|
||||
.orElseThrow(NotFoundException::new);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
|
||||
}
|
||||
|
||||
return registrationServiceSession;
|
||||
|
||||
} catch (final CompletionException | CancellationException e) {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(e);
|
||||
|
||||
if (unwrapped.getCause() instanceof StatusRuntimeException grpcRuntimeException) {
|
||||
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
}
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws NotFoundException if the session is has no record
|
||||
*/
|
||||
private VerificationSession retrieveVerificationSession(final RegistrationServiceSession registrationServiceSession) {
|
||||
|
||||
return verificationSessionManager.findForId(registrationServiceSession.encodedSessionId())
|
||||
.orTimeout(5, TimeUnit.SECONDS)
|
||||
.join().orElseThrow(NotFoundException::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ClientErrorException with {@code 422} status if the only one of token and type are present
|
||||
*/
|
||||
private Pair<String, PushNotification.TokenType> validateAndExtractPushToken(
|
||||
final UpdateVerificationSessionRequest request) {
|
||||
|
||||
final String pushToken;
|
||||
final PushNotification.TokenType pushTokenType;
|
||||
if (Objects.isNull(request.pushToken())
|
||||
!= Objects.isNull(request.pushTokenType())) {
|
||||
throw new WebApplicationException("must specify both pushToken and pushTokenType or neither",
|
||||
HttpStatus.SC_UNPROCESSABLE_ENTITY);
|
||||
} else {
|
||||
pushToken = request.pushToken();
|
||||
pushTokenType = pushToken == null
|
||||
? null
|
||||
: request.pushTokenType().toTokenType();
|
||||
}
|
||||
|
||||
return new Pair<>(pushToken, pushTokenType);
|
||||
}
|
||||
|
||||
private VerificationSessionResponse buildResponse(final RegistrationServiceSession registrationServiceSession,
|
||||
final VerificationSession verificationSession) {
|
||||
return new VerificationSessionResponse(registrationServiceSession.encodedSessionId(),
|
||||
registrationServiceSession.nextSms(),
|
||||
registrationServiceSession.nextVoiceCall(), registrationServiceSession.nextVerificationAttempt(),
|
||||
verificationSession.allowedToRequestCode(), verificationSession.requestedInformation(),
|
||||
registrationServiceSession.verified());
|
||||
}
|
||||
|
||||
public static byte[] decodeSessionId(final String sessionId) {
|
||||
return Base64.getUrlDecoder().decode(sessionId);
|
||||
}
|
||||
|
||||
private static String generatePushChallenge() {
|
||||
final byte[] challenge = new byte[16];
|
||||
RANDOM.nextBytes(challenge);
|
||||
|
||||
return HexFormat.of().formatHex(challenge);
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import java.time.Duration;
|
||||
|
||||
public class VerificationSessionRateLimitExceededException extends RateLimitExceededException {
|
||||
|
||||
private final RegistrationServiceSession registrationServiceSession;
|
||||
|
||||
/**
|
||||
* Constructs a new exception indicating when it may become safe to retry
|
||||
*
|
||||
* @param registrationServiceSession the associated registration session
|
||||
* @param retryDuration A duration to wait before retrying, null if no duration can be indicated
|
||||
* @param legacy whether to use a legacy status code when mapping the exception to an HTTP
|
||||
* response
|
||||
*/
|
||||
public VerificationSessionRateLimitExceededException(
|
||||
final RegistrationServiceSession registrationServiceSession, @Nullable final Duration retryDuration,
|
||||
final boolean legacy) {
|
||||
super(retryDuration, legacy);
|
||||
this.registrationServiceSession = registrationServiceSession;
|
||||
}
|
||||
|
||||
public RegistrationServiceSession getRegistrationSession() {
|
||||
return registrationServiceSession;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
public record ChangeNumberRequest(String sessionId,
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class) byte[] recoveryPassword,
|
||||
@NotBlank String number,
|
||||
@JsonProperty("reglock") @Nullable String registrationLock,
|
||||
@NotBlank String pniIdentityKey,
|
||||
@NotNull @Valid List<@NotNull @Valid IncomingMessage> deviceMessages,
|
||||
@NotNull @Valid Map<Long, @NotNull @Valid SignedPreKey> devicePniSignedPrekeys,
|
||||
@NotNull Map<Long, Integer> pniRegistrationIds) implements PhoneVerificationRequest {
|
||||
|
||||
}
|
||||
+5
-1
@@ -15,5 +15,9 @@ public record ConfirmUsernameHashRequest(
|
||||
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
|
||||
@ExactlySize(AccountController.USERNAME_HASH_LENGTH)
|
||||
byte[] usernameHash
|
||||
byte[] usernameHash,
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
|
||||
byte[] zkProof
|
||||
) {}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import org.whispersystems.textsecuregcm.util.E164;
|
||||
|
||||
// Not a record, because Jackson does not support @JsonUnwrapped with records
|
||||
// https://github.com/FasterXML/jackson-databind/issues/1497
|
||||
public final class CreateVerificationSessionRequest {
|
||||
|
||||
@E164
|
||||
@NotBlank
|
||||
@JsonProperty
|
||||
private String number;
|
||||
|
||||
@Valid
|
||||
@JsonUnwrapped
|
||||
private UpdateVerificationSessionRequest updateVerificationSessionRequest;
|
||||
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public UpdateVerificationSessionRequest getUpdateVerificationSessionRequest() {
|
||||
return updateVerificationSessionRequest;
|
||||
}
|
||||
|
||||
}
|
||||
+13
-5
@@ -13,7 +13,7 @@ import javax.annotation.Nullable;
|
||||
|
||||
public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullable UUID sourceUuid, int sourceDevice,
|
||||
UUID destinationUuid, @Nullable UUID updatedPni, byte[] content,
|
||||
long serverTimestamp, boolean urgent, boolean story) {
|
||||
long serverTimestamp, boolean urgent, boolean story, @Nullable byte[] reportSpamToken) {
|
||||
|
||||
public MessageProtos.Envelope toEnvelope() {
|
||||
final MessageProtos.Envelope.Builder builder = MessageProtos.Envelope.newBuilder()
|
||||
@@ -38,10 +38,15 @@ public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullab
|
||||
builder.setUpdatedPni(updatedPni().toString());
|
||||
}
|
||||
|
||||
if (reportSpamToken != null) {
|
||||
builder.setReportSpamToken(ByteString.copyFrom(reportSpamToken));
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public static OutgoingMessageEntity fromEnvelope(final MessageProtos.Envelope envelope) {
|
||||
ByteString token = envelope.getReportSpamToken();
|
||||
return new OutgoingMessageEntity(
|
||||
UUID.fromString(envelope.getServerGuid()),
|
||||
envelope.getType().getNumber(),
|
||||
@@ -53,7 +58,8 @@ public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullab
|
||||
envelope.getContent().toByteArray(),
|
||||
envelope.getServerTimestamp(),
|
||||
envelope.getUrgent(),
|
||||
envelope.getStory());
|
||||
envelope.getStory(),
|
||||
token.isEmpty() ? null : token.toByteArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -75,14 +81,16 @@ public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullab
|
||||
Arrays.equals(content, that.content) &&
|
||||
serverTimestamp == that.serverTimestamp &&
|
||||
urgent == that.urgent &&
|
||||
story == that.story;
|
||||
story == that.story &&
|
||||
Arrays.equals(reportSpamToken, that.reportSpamToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = Objects.hash(guid, type, timestamp, sourceUuid, sourceDevice, destinationUuid, updatedPni,
|
||||
serverTimestamp, urgent, story);
|
||||
int result = Objects.hash(
|
||||
guid, type, timestamp, sourceUuid, sourceDevice, destinationUuid, updatedPni, serverTimestamp, urgent, story);
|
||||
result = 31 * result + Arrays.hashCode(content);
|
||||
result = 71 * result + Arrays.hashCode(reportSpamToken);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public record PhoneNumberDiscoverabilityRequest(@NotNull Boolean discoverableByPhoneNumber) {}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.isNotBlank;
|
||||
|
||||
import java.util.Base64;
|
||||
import javax.validation.constraints.AssertTrue;
|
||||
import javax.ws.rs.ClientErrorException;
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
public interface PhoneVerificationRequest {
|
||||
|
||||
enum VerificationType {
|
||||
SESSION,
|
||||
RECOVERY_PASSWORD
|
||||
}
|
||||
|
||||
String sessionId();
|
||||
|
||||
byte[] recoveryPassword();
|
||||
|
||||
// for the @AssertTrue to work with bean validation, method name must follow 'isSmth()'/'getSmth()' naming convention
|
||||
@AssertTrue
|
||||
default boolean isValid() {
|
||||
// checking that exactly one of sessionId/recoveryPassword is non-empty
|
||||
return isNotBlank(sessionId()) ^ (recoveryPassword() != null && recoveryPassword().length > 0);
|
||||
}
|
||||
|
||||
default PhoneVerificationRequest.VerificationType verificationType() {
|
||||
return isNotBlank(sessionId()) ? PhoneVerificationRequest.VerificationType.SESSION
|
||||
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
|
||||
}
|
||||
|
||||
default byte[] decodeSessionId() {
|
||||
try {
|
||||
return Base64.getUrlDecoder().decode(sessionId());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new ClientErrorException("Malformed session ID", HttpStatus.SC_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-10
@@ -5,16 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public class ProvisioningMessage {
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private String body;
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
public record ProvisioningMessage(@NotEmpty String body) {
|
||||
}
|
||||
+6
-3
@@ -5,12 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
public record RegistrationRequest(@NotBlank String sessionId,
|
||||
public record RegistrationRequest(String sessionId,
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class) byte[] recoveryPassword,
|
||||
@NotNull @Valid AccountAttributes accountAttributes,
|
||||
boolean skipDeviceTransfer) {
|
||||
boolean skipDeviceTransfer) implements PhoneVerificationRequest {
|
||||
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import java.util.Base64;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.registration.rpc.RegistrationSessionMetadata;
|
||||
|
||||
public record RegistrationServiceSession(byte[] id, String number, boolean verified,
|
||||
@Nullable Long nextSms, @Nullable Long nextVoiceCall,
|
||||
@Nullable Long nextVerificationAttempt,
|
||||
long expiration) {
|
||||
|
||||
|
||||
public String encodedSessionId() {
|
||||
return encodeSessionId(id);
|
||||
}
|
||||
|
||||
public static String encodeSessionId(final byte[] sessionId) {
|
||||
return Base64.getUrlEncoder().encodeToString(sessionId);
|
||||
}
|
||||
|
||||
public RegistrationServiceSession(byte[] id, String number, RegistrationSessionMetadata remoteSession) {
|
||||
this(id, number, remoteSession.getVerified(),
|
||||
remoteSession.getMayRequestSms() ? remoteSession.getNextSmsSeconds() : null,
|
||||
remoteSession.getMayRequestVoiceCall() ? remoteSession.getNextVoiceCallSeconds() : null,
|
||||
remoteSession.getMayCheckCode() ? remoteSession.getNextCodeCheckSeconds() : null,
|
||||
remoteSession.getExpirationSeconds());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,9 +4,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public record SpamReport(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@NotEmpty byte[] token) {}
|
||||
@Nullable byte[] token) {}
|
||||
+3
-1
@@ -5,6 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
public record RegistrationSession(String number, boolean verified) {
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
public record SubmitVerificationCodeRequest(@NotBlank String code) {
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.annotation.Nullable;
|
||||
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 enum PushTokenType {
|
||||
@JsonProperty("apn")
|
||||
APN,
|
||||
@JsonProperty("fcm")
|
||||
FCM;
|
||||
|
||||
public PushNotification.TokenType toTokenType() {
|
||||
return switch (this) {
|
||||
|
||||
case APN -> PushNotification.TokenType.APN;
|
||||
case FCM -> PushNotification.TokenType.FCM;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
|
||||
public record VerificationCodeRequest(@NotNull Transport transport, @NotNull String client) {
|
||||
|
||||
public enum Transport {
|
||||
@JsonProperty("sms")
|
||||
SMS,
|
||||
@JsonProperty("voice")
|
||||
VOICE;
|
||||
|
||||
public MessageTransport toMessageTransport() {
|
||||
return switch (this) {
|
||||
case SMS -> MessageTransport.SMS;
|
||||
case VOICE -> MessageTransport.VOICE;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
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) {
|
||||
|
||||
}
|
||||
+7
-12
@@ -5,18 +5,9 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.http;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import org.glassfish.jersey.SslConfigurator;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
@@ -29,6 +20,11 @@ import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Supplier;
|
||||
import org.glassfish.jersey.SslConfigurator;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
|
||||
public class FaultTolerantHttpClient {
|
||||
|
||||
@@ -49,13 +45,12 @@ public class FaultTolerantHttpClient {
|
||||
this.retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
this.breaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
|
||||
MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
CircuitBreakerUtil.registerMetrics(metricRegistry, breaker, FaultTolerantHttpClient.class);
|
||||
CircuitBreakerUtil.registerMetrics(breaker, FaultTolerantHttpClient.class);
|
||||
|
||||
if (retryConfiguration != null) {
|
||||
RetryConfig retryConfig = retryConfiguration.<HttpResponse>toRetryConfigBuilder().retryOnResult(o -> o.statusCode() >= 500).build();
|
||||
this.retry = Retry.of(name + "-retry", retryConfig);
|
||||
CircuitBreakerUtil.registerMetrics(metricRegistry, retry, FaultTolerantHttpClient.class);
|
||||
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantHttpClient.class);
|
||||
} else {
|
||||
this.retry = null;
|
||||
}
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ public class LockingRateLimiter extends RateLimiter {
|
||||
public void validate(String key, int amount) throws RateLimitExceededException {
|
||||
if (!acquireLock(key)) {
|
||||
meter.mark();
|
||||
throw new RateLimitExceededException(Duration.ZERO);
|
||||
throw new RateLimitExceededException(Duration.ZERO, true);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
+2
-1
@@ -29,7 +29,8 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
private static final Logger logger = LoggerFactory.getLogger(RateLimitByIpFilter.class);
|
||||
|
||||
@VisibleForTesting
|
||||
static final RateLimitExceededException INVALID_HEADER_EXCEPTION = new RateLimitExceededException(Duration.ofHours(1));
|
||||
static final RateLimitExceededException INVALID_HEADER_EXCEPTION = new RateLimitExceededException(Duration.ofHours(1),
|
||||
true);
|
||||
|
||||
private static final ExceptionMapper<RateLimitExceededException> EXCEPTION_MAPPER = new RateLimitExceededExceptionMapper();
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ public class RateLimiter {
|
||||
setBucket(key, bucket);
|
||||
} else {
|
||||
meter.mark();
|
||||
throw new RateLimitExceededException(bucket.getTimeUntilSpaceAvailable(amount));
|
||||
throw new RateLimitExceededException(bucket.getTimeUntilSpaceAvailable(amount), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,4 +132,23 @@ public class RateLimiter {
|
||||
public boolean hasConfiguration(final RateLimitConfiguration configuration) {
|
||||
return bucketSize == configuration.getBucketSize() && leakRatePerMinute == configuration.getLeakRatePerMinute();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the wrapped {@code validate()} call throws a {@link RateLimitExceededException}, it will adapt it to ensure that
|
||||
* {@link RateLimitExceededException#isLegacy()} returns {@code true}
|
||||
*/
|
||||
public static void adaptLegacyException(final RateLimitValidator validator) throws RateLimitExceededException {
|
||||
try {
|
||||
validator.validate();
|
||||
} catch (final RateLimitExceededException e) {
|
||||
throw new RateLimitExceededException(e.getRetryDuration().orElse(null), false);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface RateLimitValidator {
|
||||
|
||||
void validate() throws RateLimitExceededException;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -42,6 +42,8 @@ public class RateLimiters {
|
||||
private final RateLimiter smsVoiceIpLimiter;
|
||||
private final RateLimiter smsVoicePrefixLimiter;
|
||||
private final RateLimiter verifyLimiter;
|
||||
private final RateLimiter verificationCaptchaLimiter;
|
||||
private final RateLimiter verificationPushChallengeLimiter;
|
||||
private final RateLimiter pinLimiter;
|
||||
private final RateLimiter registrationLimiter;
|
||||
private final RateLimiter attachmentLimiter;
|
||||
@@ -61,10 +63,14 @@ public class RateLimiters {
|
||||
public RateLimiters(final RateLimitsConfiguration config, final FaultTolerantRedisCluster cacheCluster) {
|
||||
this.smsDestinationLimiter = fromConfig("smsDestination", config.getSmsDestination(), cacheCluster);
|
||||
this.voiceDestinationLimiter = fromConfig("voxDestination", config.getVoiceDestination(), cacheCluster);
|
||||
this.voiceDestinationDailyLimiter = fromConfig("voxDestinationDaily", config.getVoiceDestinationDaily(), cacheCluster);
|
||||
this.voiceDestinationDailyLimiter = fromConfig("voxDestinationDaily", config.getVoiceDestinationDaily(),
|
||||
cacheCluster);
|
||||
this.smsVoiceIpLimiter = fromConfig("smsVoiceIp", config.getSmsVoiceIp(), cacheCluster);
|
||||
this.smsVoicePrefixLimiter = fromConfig("smsVoicePrefix", config.getSmsVoicePrefix(), cacheCluster);
|
||||
this.verifyLimiter = fromConfig("verify", config.getVerifyNumber(), cacheCluster);
|
||||
this.verificationCaptchaLimiter = fromConfig("verificationCaptcha", config.getVerificationCaptcha(), cacheCluster);
|
||||
this.verificationPushChallengeLimiter = fromConfig("verificationPushChallenge",
|
||||
config.getVerificationPushChallenge(), cacheCluster);
|
||||
this.pinLimiter = fromConfig("pin", config.getVerifyPin(), cacheCluster);
|
||||
this.registrationLimiter = fromConfig("registration", config.getRegistration(), cacheCluster);
|
||||
this.attachmentLimiter = fromConfig("attachmentCreate", config.getAttachments(), cacheCluster);
|
||||
@@ -134,6 +140,14 @@ public class RateLimiters {
|
||||
return verifyLimiter;
|
||||
}
|
||||
|
||||
public RateLimiter getVerificationCaptchaLimiter() {
|
||||
return verificationCaptchaLimiter;
|
||||
}
|
||||
|
||||
public RateLimiter getVerificationPushChallengeLimiter() {
|
||||
return verificationPushChallengeLimiter;
|
||||
}
|
||||
|
||||
public RateLimiter getPinLimiter() {
|
||||
return pinLimiter;
|
||||
}
|
||||
|
||||
+14
-9
@@ -4,36 +4,41 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.ExceptionMapper;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.ExceptionMapper;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
|
||||
@Provider
|
||||
public class RateLimitExceededExceptionMapper implements ExceptionMapper<RateLimitExceededException> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RateLimitExceededExceptionMapper.class);
|
||||
|
||||
private static final int LEGACY_STATUS_CODE = 413;
|
||||
private static final int STATUS_CODE = 429;
|
||||
|
||||
/**
|
||||
* Convert a RateLimitExceededException to a 413 response with a
|
||||
* Retry-After header.
|
||||
* Convert a RateLimitExceededException to a {@value STATUS_CODE} (or legacy {@value LEGACY_STATUS_CODE}) response
|
||||
* with a Retry-After header.
|
||||
*
|
||||
* @param e A RateLimitExceededException potentially containing a recommended retry duration
|
||||
* @return the response
|
||||
*/
|
||||
@Override
|
||||
public Response toResponse(RateLimitExceededException e) {
|
||||
final int statusCode = e.isLegacy() ? LEGACY_STATUS_CODE : STATUS_CODE;
|
||||
return e.getRetryDuration()
|
||||
.filter(d -> {
|
||||
if (d.isNegative()) {
|
||||
logger.warn("Encountered a negative retry duration: {}, will not include a Retry-After header in response", d);
|
||||
logger.warn("Encountered a negative retry duration: {}, will not include a Retry-After header in response",
|
||||
d);
|
||||
}
|
||||
// only include non-negative durations in retry headers
|
||||
return !d.isNegative();
|
||||
})
|
||||
.map(d -> Response.status(413).header("Retry-After", d.toSeconds()))
|
||||
.orElseGet(() -> Response.status(413)).build();
|
||||
.map(d -> Response.status(statusCode).header("Retry-After", d.toSeconds()))
|
||||
.orElseGet(() -> Response.status(statusCode)).build();
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
|
||||
|
||||
public class RegistrationServiceSenderExceptionMapper implements ExceptionMapper<RegistrationServiceSenderException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final RegistrationServiceSenderException exception) {
|
||||
return Response.status(Response.Status.BAD_GATEWAY)
|
||||
.entity(new SendVerificationCodeFailureResponse(exception.getReason(), exception.isPermanent()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public record SendVerificationCodeFailureResponse(RegistrationServiceSenderException.Reason reason,
|
||||
boolean permanentFailure) {
|
||||
|
||||
}
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
|
||||
public class LettuceMetricsMeterFilter implements MeterFilter {
|
||||
|
||||
private static final String METRIC_NAME_PREFIX = "lettuce.command";
|
||||
private static final String REMOTE_TAG = "remote";
|
||||
|
||||
// the `remote` tag is very high-cardinality, so we ignore it.
|
||||
// In the future, it would be nice to map a remote (address:port) to a logical cluster name
|
||||
private static final MeterFilter IGNORE_TAGS_FILTER = MeterFilter.ignoreTags(REMOTE_TAG);
|
||||
|
||||
@Override
|
||||
public Meter.Id map(final Meter.Id id) {
|
||||
|
||||
if (id.getName().startsWith(METRIC_NAME_PREFIX)) {
|
||||
return IGNORE_TAGS_FILTER.map(id);
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ public class MessageSender {
|
||||
private static final String URGENT_TAG_NAME = "urgent";
|
||||
private static final String STORY_TAG_NAME = "story";
|
||||
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
|
||||
private static final String HAS_SPAM_REPORTING_TOKEN_TAG_NAME = "hasSpamReportingToken";
|
||||
|
||||
public MessageSender(ClientPresenceManager clientPresenceManager,
|
||||
MessagesManager messagesManager,
|
||||
@@ -103,7 +104,8 @@ public class MessageSender {
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
|
||||
STORY_TAG_NAME, String.valueOf(message.getStory()),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceUuid()))
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceUuid()),
|
||||
HAS_SPAM_REPORTING_TOKEN_TAG_NAME, String.valueOf(message.getReportSpamToken() != null && !message.getReportSpamToken().isEmpty()))
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
+9
-4
@@ -14,8 +14,10 @@ import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
@@ -26,7 +28,9 @@ public class FaultTolerantPubSubConnection<K, V> {
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
private final Retry retry;
|
||||
|
||||
private final Timer executeTimer;
|
||||
@Deprecated
|
||||
private final Timer executeTimer;
|
||||
private final io.micrometer.core.instrument.Timer newExecuteTimer;
|
||||
|
||||
public FaultTolerantPubSubConnection(final String name, final StatefulRedisClusterPubSubConnection<K, V> pubSubConnection, final CircuitBreaker circuitBreaker, final Retry retry) {
|
||||
this.pubSubConnection = pubSubConnection;
|
||||
@@ -37,15 +41,16 @@ public class FaultTolerantPubSubConnection<K, V> {
|
||||
|
||||
final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
this.executeTimer = metricRegistry.timer(name(getClass(), name + "-pubsub", "execute"));
|
||||
this.newExecuteTimer = Metrics.timer(MetricsUtil.name(getClass(), "execute", "name", name + "-pubsub"));
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(metricRegistry, circuitBreaker, FaultTolerantPubSubConnection.class);
|
||||
CircuitBreakerUtil.registerMetrics(circuitBreaker, FaultTolerantPubSubConnection.class);
|
||||
}
|
||||
|
||||
public void usePubSubConnection(final Consumer<StatefulRedisClusterPubSubConnection<K, V>> consumer) {
|
||||
try {
|
||||
circuitBreaker.executeCheckedRunnable(() -> retry.executeRunnable(() -> {
|
||||
try (final Timer.Context ignored = executeTimer.time()) {
|
||||
consumer.accept(pubSubConnection);
|
||||
newExecuteTimer.record(() -> consumer.accept(pubSubConnection));
|
||||
}
|
||||
}));
|
||||
} catch (final Throwable t) {
|
||||
@@ -61,7 +66,7 @@ public class FaultTolerantPubSubConnection<K, V> {
|
||||
try {
|
||||
return circuitBreaker.executeCheckedSupplier(() -> retry.executeCallable(() -> {
|
||||
try (final Timer.Context ignored = executeTimer.time()) {
|
||||
return function.apply(pubSubConnection);
|
||||
return newExecuteTimer.record(() -> function.apply(pubSubConnection));
|
||||
}
|
||||
}));
|
||||
} catch (final Throwable t) {
|
||||
|
||||
+2
-6
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.reactor.circuitbreaker.operator.CircuitBreakerOperator;
|
||||
@@ -31,7 +30,6 @@ import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguratio
|
||||
import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
/**
|
||||
@@ -82,10 +80,8 @@ public class FaultTolerantRedisCluster {
|
||||
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder()
|
||||
.retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME), circuitBreaker,
|
||||
FaultTolerantRedisCluster.class);
|
||||
CircuitBreakerUtil.registerMetrics(SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME), retry,
|
||||
FaultTolerantRedisCluster.class);
|
||||
CircuitBreakerUtil.registerMetrics(circuitBreaker, FaultTolerantRedisCluster.class);
|
||||
CircuitBreakerUtil.registerMetrics(retry, FaultTolerantRedisCluster.class);
|
||||
}
|
||||
|
||||
void shutdown() {
|
||||
|
||||
+8
-14
@@ -5,21 +5,16 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.CircuitBreakerUtil;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.exceptions.JedisException;
|
||||
@@ -39,11 +34,10 @@ public class ReplicatedJedisPool {
|
||||
{
|
||||
if (replicas.size() < 1) throw new IllegalArgumentException("There must be at least one replica");
|
||||
|
||||
MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
CircuitBreakerConfig config = circuitBreakerConfiguration.toCircuitBreakerConfig();
|
||||
CircuitBreaker masterBreaker = CircuitBreaker.of(String.format("%s-master", name), config);
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(metricRegistry, masterBreaker, ReplicatedJedisPool.class);
|
||||
CircuitBreakerUtil.registerMetrics(masterBreaker, ReplicatedJedisPool.class);
|
||||
|
||||
this.master = CircuitBreaker.decorateSupplier(masterBreaker, master::getResource);
|
||||
this.replicas = new ArrayList<>(replicas.size());
|
||||
@@ -52,7 +46,7 @@ public class ReplicatedJedisPool {
|
||||
JedisPool replica = replicas.get(i);
|
||||
CircuitBreaker slaveBreaker = CircuitBreaker.of(String.format("%s-slave-%d", name, i), config);
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(metricRegistry, slaveBreaker, ReplicatedJedisPool.class);
|
||||
CircuitBreakerUtil.registerMetrics(slaveBreaker, ReplicatedJedisPool.class);
|
||||
this.replicas.add(CircuitBreaker.decorateSupplier(slaveBreaker, replica::getResource));
|
||||
}
|
||||
}
|
||||
|
||||
+92
-18
@@ -28,9 +28,11 @@ import org.signal.registration.rpc.CheckVerificationCodeRequest;
|
||||
import org.signal.registration.rpc.CreateRegistrationSessionRequest;
|
||||
import org.signal.registration.rpc.GetRegistrationSessionMetadataRequest;
|
||||
import org.signal.registration.rpc.RegistrationServiceGrpc;
|
||||
import org.signal.registration.rpc.RegistrationSessionMetadata;
|
||||
import org.signal.registration.rpc.SendVerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationSession;
|
||||
import org.whispersystems.textsecuregcm.controllers.VerificationSessionRateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
|
||||
public class RegistrationServiceClient implements Managed {
|
||||
|
||||
@@ -76,7 +78,10 @@ public class RegistrationServiceClient implements Managed {
|
||||
this.callbackExecutor = callbackExecutor;
|
||||
}
|
||||
|
||||
public CompletableFuture<byte[]> createRegistrationSession(final Phonenumber.PhoneNumber phoneNumber, final Duration timeout) {
|
||||
// The …Session suffix methods distinguish the new methods, which return Sessions, from the old.
|
||||
// Once the deprecated methods are removed, the names can be streamlined.
|
||||
public CompletableFuture<RegistrationServiceSession> createRegistrationSessionSession(
|
||||
final Phonenumber.PhoneNumber phoneNumber, final Duration timeout) {
|
||||
final long e164 = Long.parseLong(
|
||||
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
|
||||
|
||||
@@ -85,13 +90,18 @@ public class RegistrationServiceClient implements Managed {
|
||||
.setE164(e164)
|
||||
.build()))
|
||||
.thenApply(response -> switch (response.getResponseCase()) {
|
||||
case SESSION_METADATA -> response.getSessionMetadata().getSessionId().toByteArray();
|
||||
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
|
||||
case ERROR -> {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
|
||||
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
|
||||
new RateLimitExceededException(response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null,
|
||||
true));
|
||||
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER -> throw new IllegalArgumentException();
|
||||
default -> throw new RuntimeException("Unrecognized error type from registration service: " + response.getError().getErrorType());
|
||||
default -> throw new RuntimeException(
|
||||
"Unrecognized error type from registration service: " + response.getError().getErrorType());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +109,14 @@ public class RegistrationServiceClient implements Managed {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<byte[]> sendRegistrationCode(final byte[] sessionId,
|
||||
@Deprecated
|
||||
public CompletableFuture<byte[]> createRegistrationSession(final Phonenumber.PhoneNumber phoneNumber,
|
||||
final Duration timeout) {
|
||||
return createRegistrationSessionSession(phoneNumber, timeout)
|
||||
.thenApply(RegistrationServiceSession::id);
|
||||
}
|
||||
|
||||
public CompletableFuture<RegistrationServiceSession> sendVerificationCode(final byte[] sessionId,
|
||||
final MessageTransport messageTransport,
|
||||
final ClientType clientType,
|
||||
@Nullable final String acceptLanguage,
|
||||
@@ -119,21 +136,58 @@ public class RegistrationServiceClient implements Managed {
|
||||
.thenApply(response -> {
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED ->
|
||||
throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
|
||||
new VerificationSessionRateLimitExceededException(
|
||||
buildSessionResponseFromMetadata(response.getSessionMetadata()),
|
||||
response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null,
|
||||
true));
|
||||
|
||||
default -> throw new CompletionException(new RuntimeException("Failed to send verification code: " + response.getError().getErrorType()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new CompletionException(
|
||||
new RegistrationServiceException(null));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_ALREADY_VERIFIED -> throw new CompletionException(
|
||||
new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata())));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED -> throw new CompletionException(
|
||||
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT -> throw new CompletionException(
|
||||
RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED -> throw new CompletionException(
|
||||
RegistrationServiceSenderException.unknown(response.getError().getMayRetry()));
|
||||
|
||||
default -> throw new CompletionException(
|
||||
new RuntimeException("Failed to send verification code: " + response.getError().getErrorType()));
|
||||
}
|
||||
} else {
|
||||
return response.getSessionId().toByteArray();
|
||||
return buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public CompletableFuture<byte[]> sendRegistrationCode(final byte[] sessionId,
|
||||
final MessageTransport messageTransport,
|
||||
final ClientType clientType,
|
||||
@Nullable final String acceptLanguage,
|
||||
final Duration timeout) {
|
||||
return sendVerificationCode(sessionId, messageTransport, clientType, acceptLanguage, timeout)
|
||||
.thenApply(RegistrationServiceSession::id);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public CompletableFuture<Boolean> checkVerificationCode(final byte[] sessionId,
|
||||
final String verificationCode,
|
||||
final Duration timeout) {
|
||||
|
||||
return checkVerificationCodeSession(sessionId, verificationCode, timeout)
|
||||
.thenApply(RegistrationServiceSession::verified);
|
||||
}
|
||||
|
||||
public CompletableFuture<RegistrationServiceSession> checkVerificationCodeSession(final byte[] sessionId,
|
||||
final String verificationCode,
|
||||
final Duration timeout) {
|
||||
return toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
.checkVerificationCode(CheckVerificationCodeRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId))
|
||||
@@ -142,18 +196,33 @@ public class RegistrationServiceClient implements Managed {
|
||||
.thenApply(response -> {
|
||||
if (response.hasError()) {
|
||||
switch (response.getError().getErrorType()) {
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED ->
|
||||
throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
|
||||
new VerificationSessionRateLimitExceededException(
|
||||
buildSessionResponseFromMetadata(response.getSessionMetadata()),
|
||||
response.getError().getMayRetry()
|
||||
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
|
||||
: null,
|
||||
true));
|
||||
|
||||
default -> throw new CompletionException(new RuntimeException("Failed to check verification code: " + response.getError().getErrorType()));
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT, CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPT_EXPIRED ->
|
||||
throw new CompletionException(
|
||||
new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()))
|
||||
);
|
||||
|
||||
case CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new CompletionException(
|
||||
new RegistrationServiceException(null)
|
||||
);
|
||||
|
||||
default -> throw new CompletionException(
|
||||
new RuntimeException("Failed to check verification code: " + response.getError().getErrorType()));
|
||||
}
|
||||
} else {
|
||||
return response.getVerified() || response.getSessionMetadata().getVerified();
|
||||
return buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RegistrationSession>> getSession(final byte[] sessionId,
|
||||
public CompletableFuture<Optional<RegistrationServiceSession>> getSession(final byte[] sessionId,
|
||||
final Duration timeout) {
|
||||
return toCompletableFuture(stub.withDeadline(toDeadline(timeout)).getSessionMetadata(
|
||||
GetRegistrationSessionMetadataRequest.newBuilder()
|
||||
@@ -168,11 +237,16 @@ public class RegistrationServiceClient implements Managed {
|
||||
}
|
||||
}
|
||||
|
||||
final String number = convertNumeralE164ToString(response.getSessionMetadata().getE164());
|
||||
return Optional.of(new RegistrationSession(number, response.getSessionMetadata().getVerified()));
|
||||
return Optional.of(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
});
|
||||
}
|
||||
|
||||
private static RegistrationServiceSession buildSessionResponseFromMetadata(
|
||||
final RegistrationSessionMetadata sessionMetadata) {
|
||||
return new RegistrationServiceSession(sessionMetadata.getSessionId().toByteArray(),
|
||||
convertNumeralE164ToString(sessionMetadata.getE164()), sessionMetadata);
|
||||
}
|
||||
|
||||
private static Deadline toDeadline(final Duration timeout) {
|
||||
return Deadline.after(timeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.registration;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
|
||||
/**
|
||||
* When the Registration Service returns an error, it will also return the latest {@link RegistrationServiceSession}
|
||||
* data, so that clients may have the latest details on requesting and submitting codes.
|
||||
*/
|
||||
public class RegistrationServiceException extends Exception {
|
||||
|
||||
private final RegistrationServiceSession registrationServiceSession;
|
||||
|
||||
public RegistrationServiceException(final RegistrationServiceSession registrationServiceSession) {
|
||||
super(null, null, true, false);
|
||||
this.registrationServiceSession = registrationServiceSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return if empty, the session that encountered should be considered non-existent and may be discarded
|
||||
*/
|
||||
public Optional<RegistrationServiceSession> getRegistrationSession() {
|
||||
return Optional.ofNullable(registrationServiceSession);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.registration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
/**
|
||||
* An error from an SMS/voice provider (“sender”) downstream of Registration Service is mapped to a {@link Reason}, and
|
||||
* may be permanent.
|
||||
*/
|
||||
public class RegistrationServiceSenderException extends Exception {
|
||||
|
||||
private final Reason reason;
|
||||
private final boolean permanent;
|
||||
|
||||
public static RegistrationServiceSenderException illegalArgument(final boolean permanent) {
|
||||
return new RegistrationServiceSenderException(Reason.ILLEGAL_ARGUMENT, permanent);
|
||||
}
|
||||
|
||||
public static RegistrationServiceSenderException rejected(final boolean permanent) {
|
||||
return new RegistrationServiceSenderException(Reason.PROVIDER_REJECTED, permanent);
|
||||
}
|
||||
|
||||
public static RegistrationServiceSenderException unknown(final boolean permanent) {
|
||||
return new RegistrationServiceSenderException(Reason.PROVIDER_UNAVAILABLE, permanent);
|
||||
}
|
||||
|
||||
private RegistrationServiceSenderException(final Reason reason, final boolean permanent) {
|
||||
super(null, null, true, false);
|
||||
this.reason = reason;
|
||||
this.permanent = permanent;
|
||||
}
|
||||
|
||||
public Reason getReason() {
|
||||
return reason;
|
||||
}
|
||||
|
||||
public boolean isPermanent() {
|
||||
return permanent;
|
||||
}
|
||||
|
||||
public enum Reason {
|
||||
|
||||
@JsonProperty("providerUnavailable")
|
||||
PROVIDER_UNAVAILABLE,
|
||||
@JsonProperty("providerRejected")
|
||||
PROVIDER_REJECTED,
|
||||
@JsonProperty("illegalArgument")
|
||||
ILLEGAL_ARGUMENT
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.registration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.storage.SerializedExpireableJsonDynamoStore;
|
||||
|
||||
/**
|
||||
* Server-internal stored session object. Primarily used by
|
||||
* {@link org.whispersystems.textsecuregcm.controllers.VerificationController} to manage the steps required to begin
|
||||
* requesting codes from Registration Service, in order to get a verified session to be provided to
|
||||
* {@link org.whispersystems.textsecuregcm.controllers.RegistrationController}.
|
||||
*
|
||||
* @param pushChallenge the value of a push challenge sent to a client, after it submitted a push token
|
||||
* @param requestedInformation information requested that a client send to the server
|
||||
* @param submittedInformation information that a client has submitted and that the server has verified
|
||||
* @param allowedToRequestCode whether the client is allowed to request a code. This request will be forwarded to
|
||||
* Registration Service
|
||||
* @param createdTimestamp when this session was created
|
||||
* @param updatedTimestamp when this session was updated
|
||||
* @param remoteExpirationSeconds when the remote
|
||||
* {@link org.whispersystems.textsecuregcm.entities.RegistrationServiceSession} expires
|
||||
* @see org.whispersystems.textsecuregcm.entities.RegistrationServiceSession
|
||||
* @see org.whispersystems.textsecuregcm.entities.VerificationSessionResponse
|
||||
*/
|
||||
public record VerificationSession(@Nullable String pushChallenge,
|
||||
List<Information> requestedInformation, List<Information> submittedInformation,
|
||||
boolean allowedToRequestCode, long createdTimestamp, long updatedTimestamp,
|
||||
long remoteExpirationSeconds) implements
|
||||
SerializedExpireableJsonDynamoStore.Expireable {
|
||||
|
||||
@Override
|
||||
public long getExpirationEpochSeconds() {
|
||||
return Instant.ofEpochMilli(updatedTimestamp).plusSeconds(remoteExpirationSeconds).getEpochSecond();
|
||||
}
|
||||
|
||||
public enum Information {
|
||||
@JsonProperty("pushChallenge")
|
||||
PUSH_CHALLENGE,
|
||||
@JsonProperty("captcha")
|
||||
CAPTCHA
|
||||
}
|
||||
}
|
||||
+1
-11
@@ -23,16 +23,6 @@ public interface ReportSpamTokenProvider {
|
||||
* @return the provider
|
||||
*/
|
||||
static ReportSpamTokenProvider noop() {
|
||||
return create(c -> Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider which generates ReportSpamTokens using the given function
|
||||
*
|
||||
* @param fn function from message requests to optional tokens
|
||||
* @return the provider
|
||||
*/
|
||||
static ReportSpamTokenProvider create(Function<ContainerRequestContext, Optional<byte[]>> fn) {
|
||||
return fn::apply;
|
||||
return context -> Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -195,6 +195,9 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
account.setUuid(UUIDUtil.fromByteBuffer(actualAccountUuid));
|
||||
|
||||
final Account existingAccount = getByAccountIdentifier(account.getUuid()).orElseThrow();
|
||||
|
||||
// It's up to the client to delete this username hash if they can't retrieve and decrypt the plaintext username from storage service
|
||||
existingAccount.getUsernameHash().ifPresent(existingUsernameHash -> account.setUsernameHash(existingUsernameHash));
|
||||
account.setNumber(existingAccount.getNumber(), existingAccount.getPhoneNumberIdentifier());
|
||||
account.setVersion(existingAccount.getVersion());
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -227,7 +228,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
discardStaleEphemeralMessages(destinationUuid, destinationDevice, staleEphemeralMessages);
|
||||
|
||||
return messagesToPublish.name(GET_FLUX_NAME)
|
||||
.metrics();
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
|
||||
|
||||
@@ -9,6 +9,7 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -26,6 +27,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@@ -77,7 +79,7 @@ public class MessagesManager {
|
||||
|
||||
return Flux.from(
|
||||
getMessagesForDevice(destinationUuid, destinationDevice, RESULT_SET_CHUNK_SIZE, cachedMessagesOnly))
|
||||
.take(RESULT_SET_CHUNK_SIZE, true)
|
||||
.take(RESULT_SET_CHUNK_SIZE)
|
||||
.collectList()
|
||||
.map(envelopes -> new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE));
|
||||
}
|
||||
@@ -97,7 +99,7 @@ public class MessagesManager {
|
||||
|
||||
return Flux.concat(dynamoPublisher, cachePublisher)
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.metrics();
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public void clear(UUID destinationUuid) {
|
||||
|
||||
+8
-4
@@ -16,9 +16,11 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -31,7 +33,7 @@ public class ReportMessageManager {
|
||||
|
||||
private final List<ReportedMessageListener> reportedMessageListeners = new ArrayList<>();
|
||||
|
||||
private static final String REPORT_MESSAGE_COUNTER_NAME = MetricsUtil.name(ReportMessageManager.class);
|
||||
private static final String REPORT_MESSAGE_COUNTER_NAME = MetricsUtil.name(ReportMessageManager.class, "reportMessage");
|
||||
private static final String FOUND_MESSAGE_TAG = "foundMessage";
|
||||
private static final String TOKEN_PRESENT_TAG = "hasReportSpamToken";
|
||||
|
||||
@@ -67,14 +69,16 @@ public class ReportMessageManager {
|
||||
final Optional<UUID> sourcePni,
|
||||
final UUID messageGuid,
|
||||
final UUID reporterUuid,
|
||||
final Optional<byte[]> reportSpamToken) {
|
||||
final Optional<byte[]> reportSpamToken,
|
||||
final String reporterUserAgent) {
|
||||
|
||||
final boolean found = sourceAci.map(uuid -> reportMessageDynamoDb.remove(hash(messageGuid, uuid.toString())))
|
||||
.orElse(false);
|
||||
|
||||
Metrics.counter(REPORT_MESSAGE_COUNTER_NAME,
|
||||
FOUND_MESSAGE_TAG, String.valueOf(found),
|
||||
TOKEN_PRESENT_TAG, String.valueOf(reportSpamToken.isPresent()))
|
||||
Tags.of(FOUND_MESSAGE_TAG, String.valueOf(found),
|
||||
TOKEN_PRESENT_TAG, String.valueOf(reportSpamToken.isPresent()))
|
||||
.and(UserAgentTagUtil.getPlatformTag(reporterUserAgent)))
|
||||
.increment();
|
||||
|
||||
if (found) {
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.time.Clock;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
|
||||
public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
|
||||
public interface Expireable {
|
||||
|
||||
@JsonIgnore
|
||||
long getExpirationEpochSeconds();
|
||||
}
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbClient;
|
||||
private final String tableName;
|
||||
private final Clock clock;
|
||||
private final Class<T> deserializationTargetClass;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String KEY_KEY = "K";
|
||||
|
||||
private static final String ATTR_SERIALIZED_VALUE = "V";
|
||||
private static final String ATTR_TTL = "E";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(VerificationCodeStore.class);
|
||||
|
||||
public SerializedExpireableJsonDynamoStore(final DynamoDbAsyncClient dynamoDbClient, final String tableName,
|
||||
final Clock clock) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.tableName = tableName;
|
||||
this.clock = clock;
|
||||
|
||||
if (getClass().getGenericSuperclass() instanceof ParameterizedType pt) {
|
||||
// Extract the parameterized class declared by concrete implementations, so that it can
|
||||
// be passed to future deserialization calls
|
||||
final Type[] actualTypeArguments = pt.getActualTypeArguments();
|
||||
if (actualTypeArguments.length != 1) {
|
||||
throw new RuntimeException("Unexpected number of type arguments: " + actualTypeArguments.length);
|
||||
}
|
||||
deserializationTargetClass = (Class<T>) actualTypeArguments[0];
|
||||
} else {
|
||||
throw new RuntimeException(
|
||||
"Unable to determine target class for deserialization - generic superclass is not a ParameterizedType");
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> insert(final String key, final T v) {
|
||||
return put(key, v, builder -> builder.expressionAttributeNames(Map.of(
|
||||
"#key", KEY_KEY
|
||||
)).conditionExpression("attribute_not_exists(#key)"));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> update(final String key, final T v) {
|
||||
return put(key, v, ignored -> {
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> put(final String key, final T v,
|
||||
final Consumer<PutItemRequest.Builder> putRequestCustomizer) {
|
||||
try {
|
||||
final Map<String, AttributeValue> attributeValueMap = new HashMap<>(Map.of(
|
||||
KEY_KEY, AttributeValues.fromString(key),
|
||||
ATTR_SERIALIZED_VALUE,
|
||||
AttributeValues.fromString(SystemMapper.getMapper().writeValueAsString(v))));
|
||||
if (v instanceof Expireable ev) {
|
||||
attributeValueMap.put(ATTR_TTL, AttributeValues.fromLong(getExpirationTimestamp(ev)));
|
||||
}
|
||||
final PutItemRequest.Builder builder = PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(attributeValueMap);
|
||||
putRequestCustomizer.accept(builder);
|
||||
|
||||
return dynamoDbClient.putItem(builder.build())
|
||||
.thenRun(() -> {
|
||||
});
|
||||
} catch (final JsonProcessingException e) {
|
||||
// This should never happen when writing directly to a string except in cases of serious misconfiguration, which
|
||||
// would be caught by tests.
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private long getExpirationTimestamp(final Expireable v) {
|
||||
return v.getExpirationEpochSeconds();
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<T>> findForKey(final String key) {
|
||||
return dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(KEY_KEY, AttributeValues.fromString(key)))
|
||||
.build())
|
||||
.thenApply(response -> {
|
||||
try {
|
||||
return response.hasItem()
|
||||
? filterMaybeExpiredValue(
|
||||
SystemMapper.getMapper()
|
||||
.readValue(response.item().get(ATTR_SERIALIZED_VALUE).s(), deserializationTargetClass))
|
||||
: Optional.empty();
|
||||
} catch (final JsonProcessingException e) {
|
||||
log.error("Failed to parse stored value", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Optional<T> filterMaybeExpiredValue(T v) {
|
||||
// It's possible for DynamoDB to return items after their expiration time (although it is very unlikely for small
|
||||
// tables)
|
||||
if (v instanceof Expireable ev) {
|
||||
if (getExpirationTimestamp(ev) < clock.instant().getEpochSecond()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.of(v);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> remove(final String key) {
|
||||
return dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_KEY, AttributeValues.fromString(key)))
|
||||
.build())
|
||||
.thenRun(() -> {
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public class VerificationSessionManager {
|
||||
|
||||
private final VerificationSessions verificationSessions;
|
||||
|
||||
public VerificationSessionManager(final VerificationSessions verificationSessions) {
|
||||
this.verificationSessions = verificationSessions;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> insert(final String encodedSessionId, final VerificationSession verificationSession) {
|
||||
return verificationSessions.insert(encodedSessionId, verificationSession);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> update(final String encodedSessionId, final VerificationSession verificationSession) {
|
||||
return verificationSessions.update(encodedSessionId, verificationSession);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<VerificationSession>> findForId(final String encodedSessionId) {
|
||||
return verificationSessions.findForKey(encodedSessionId);
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.time.Clock;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
|
||||
public class VerificationSessions extends SerializedExpireableJsonDynamoStore<VerificationSession> {
|
||||
|
||||
public VerificationSessions(final DynamoDbAsyncClient dynamoDbClient, final String tableName, final Clock clock) {
|
||||
super(dynamoDbClient, tableName, clock);
|
||||
}
|
||||
}
|
||||
+3
-23
@@ -5,10 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
@@ -25,11 +23,7 @@ public class CircuitBreakerUtil {
|
||||
private static final String NAME_TAG_NAME = "name";
|
||||
private static final String OUTCOME_TAG_NAME = "outcome";
|
||||
|
||||
public static void registerMetrics(MetricRegistry metricRegistry, CircuitBreaker circuitBreaker, Class<?> clazz) {
|
||||
Meter successMeter = metricRegistry.meter(name(clazz, circuitBreaker.getName(), "success" ));
|
||||
Meter failureMeter = metricRegistry.meter(name(clazz, circuitBreaker.getName(), "failure" ));
|
||||
Meter unpermittedMeter = metricRegistry.meter(name(clazz, circuitBreaker.getName(), "unpermitted"));
|
||||
|
||||
public static void registerMetrics(CircuitBreaker circuitBreaker, Class<?> clazz) {
|
||||
final String breakerName = clazz.getSimpleName() + "/" + circuitBreaker.getName();
|
||||
|
||||
final Counter successCounter = Metrics.counter(CIRCUIT_BREAKER_CALL_COUNTER_NAME,
|
||||
@@ -45,33 +39,23 @@ public class CircuitBreakerUtil {
|
||||
OUTCOME_TAG_NAME, "unpermitted");
|
||||
|
||||
circuitBreaker.getEventPublisher().onSuccess(event -> {
|
||||
successMeter.mark();
|
||||
successCounter.increment();
|
||||
});
|
||||
|
||||
circuitBreaker.getEventPublisher().onError(event -> {
|
||||
failureMeter.mark();
|
||||
failureCounter.increment();
|
||||
});
|
||||
|
||||
circuitBreaker.getEventPublisher().onCallNotPermitted(event -> {
|
||||
unpermittedMeter.mark();
|
||||
unpermittedCounter.increment();
|
||||
});
|
||||
|
||||
metricRegistry.gauge(name(clazz, circuitBreaker.getName(), "state"), () -> ()-> circuitBreaker.getState().getOrder());
|
||||
|
||||
Metrics.gauge(CIRCUIT_BREAKER_STATE_GAUGE_NAME,
|
||||
Tags.of(Tag.of(NAME_TAG_NAME, circuitBreaker.getName())),
|
||||
circuitBreaker, breaker -> breaker.getState().getOrder());
|
||||
}
|
||||
|
||||
public static void registerMetrics(MetricRegistry metricRegistry, Retry retry, Class<?> clazz) {
|
||||
Meter successMeter = metricRegistry.meter(name(clazz, retry.getName(), "success" ));
|
||||
Meter retryMeter = metricRegistry.meter(name(clazz, retry.getName(), "retry" ));
|
||||
Meter errorMeter = metricRegistry.meter(name(clazz, retry.getName(), "error" ));
|
||||
Meter ignoredErrorMeter = metricRegistry.meter(name(clazz, retry.getName(), "ignored_error"));
|
||||
|
||||
public static void registerMetrics(Retry retry, Class<?> clazz) {
|
||||
final String retryName = clazz.getSimpleName() + "/" + retry.getName();
|
||||
|
||||
final Counter successCounter = Metrics.counter(RETRY_CALL_COUNTER_NAME,
|
||||
@@ -91,22 +75,18 @@ public class CircuitBreakerUtil {
|
||||
OUTCOME_TAG_NAME, "ignored_error");
|
||||
|
||||
retry.getEventPublisher().onSuccess(event -> {
|
||||
successMeter.mark();
|
||||
successCounter.increment();
|
||||
});
|
||||
|
||||
retry.getEventPublisher().onRetry(event -> {
|
||||
retryMeter.mark();
|
||||
retryCounter.increment();
|
||||
});
|
||||
|
||||
retry.getEventPublisher().onError(event -> {
|
||||
errorMeter.mark();
|
||||
errorCounter.increment();
|
||||
});
|
||||
|
||||
retry.getEventPublisher().onIgnoredError(event -> {
|
||||
ignoredErrorMeter.mark();
|
||||
ignoredErrorCounter.increment();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ import javax.validation.Payload;
|
||||
@Documented
|
||||
public @interface E164 {
|
||||
|
||||
String message() default "{org.whispersystems.textsecuregcm.util.E164.message}";
|
||||
String message() default "value is not a valid E164 number";
|
||||
|
||||
Class<?>[] groups() default { };
|
||||
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.usernames.Username;
|
||||
|
||||
public class UsernameHashZkProofVerifier {
|
||||
public void verifyProof(byte[] proof, byte[] hash) throws BaseUsernameException {
|
||||
Username.verifyProof(proof, hash);
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -52,6 +52,7 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -359,19 +360,20 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
|
||||
final Disposable subscription = Flux.from(messages)
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.metrics()
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
.flatMapSequential(envelope ->
|
||||
Mono.fromFuture(sendMessage(envelope)
|
||||
.orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS))
|
||||
.doOnError(e -> {
|
||||
final String errorType;
|
||||
if (!(e instanceof TimeoutException)) {
|
||||
// TimeoutExceptions are expected, no need to log
|
||||
if (e instanceof TimeoutException) {
|
||||
errorType = "timeout";
|
||||
} else if (e instanceof java.nio.channels.ClosedChannelException) {
|
||||
errorType = "closedChannel";
|
||||
} else {
|
||||
logger.warn("Send message failed", e);
|
||||
errorType = "other";
|
||||
} else {
|
||||
errorType = "timeout";
|
||||
}
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
|
||||
@@ -66,6 +66,66 @@ message RegistrationSessionMetadata {
|
||||
* The phone number associated with this registration session.
|
||||
*/
|
||||
uint64 e164 = 3;
|
||||
|
||||
/**
|
||||
* Indicates whether the caller may request delivery of a verification code
|
||||
* via SMS now or at some time in the future. If true, the time a caller must
|
||||
* wait before requesting a verification code via SMS is given in the
|
||||
* `next_sms_seconds` field.
|
||||
*/
|
||||
bool may_request_sms = 4;
|
||||
|
||||
/**
|
||||
* The duration, in seconds, after which a caller will next be allowed to
|
||||
* request delivery of a verification code via SMS if `may_request_sms` is
|
||||
* true. If zero, a caller may request a verification code via SMS
|
||||
* immediately. If `may_request_sms` is false, this field has no meaning.
|
||||
*/
|
||||
uint64 next_sms_seconds = 5;
|
||||
|
||||
/**
|
||||
* Indicates whether the caller may request delivery of a verification code
|
||||
* via a phone call now or at some time in the future. If true, the time a
|
||||
* caller must wait before requesting a verification code via SMS is given in
|
||||
* the `next_voice_call_seconds` field. If false, simply waiting will not
|
||||
* allow the caller to request a phone call and the caller may need to
|
||||
* perform some other action (like attempting verification code delivery via
|
||||
* SMS) before requesting a voice call.
|
||||
*/
|
||||
bool may_request_voice_call = 6;
|
||||
|
||||
/**
|
||||
* The duration, in seconds, after which a caller will next be allowed to
|
||||
* request delivery of a verification code via a phone call if
|
||||
* `may_request_voice_call` is true. If zero, a caller may request a
|
||||
* verification code via a phone call immediately. If `may_request_voice_call`
|
||||
* is false, this field has no meaning.
|
||||
*/
|
||||
uint64 next_voice_call_seconds = 7;
|
||||
|
||||
/**
|
||||
* Indicates whether the caller may submit new verification codes now or at
|
||||
* some time in the future. If true, the time a caller must wait before
|
||||
* submitting a verification code is given in the `next_code_check_seconds`
|
||||
* field. If false, simply waiting will not allow the caller to submit a
|
||||
* verification code and the caller may need to perform some other action
|
||||
* (like requesting delivery of a verification code) before checking a
|
||||
* verification code.
|
||||
*/
|
||||
bool may_check_code = 8;
|
||||
|
||||
/**
|
||||
* The duration, in seconds, after which a caller will next be allowed to
|
||||
* submit a verification code if `may_check_code` is true. If zero, a caller
|
||||
* may submit a verification code immediately. If `may_check_code` is false,
|
||||
* this field has no meaning.
|
||||
*/
|
||||
uint64 next_code_check_seconds = 9;
|
||||
|
||||
/**
|
||||
* The duration, in seconds, after which this session will expire.
|
||||
*/
|
||||
uint64 expiration_seconds = 10;
|
||||
}
|
||||
|
||||
message CreateRegistrationSessionError {
|
||||
@@ -315,29 +375,30 @@ message CheckVerificationCodeError {
|
||||
enum CheckVerificationCodeErrorType {
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED = 0;
|
||||
|
||||
/**
|
||||
* The caller has made too many incorrect guesses within the scope of this
|
||||
* session and may not make any further guesses.
|
||||
*/
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPTS_EXHAUSTED = 1;
|
||||
|
||||
/**
|
||||
* The caller has attempted to submit a verification code even though no
|
||||
* verification codes have been sent within the scope of this session. The
|
||||
* caller must issue a "send code" request before trying again.
|
||||
*/
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT = 2;
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT = 1;
|
||||
|
||||
/**
|
||||
* The caller has made too many guesses within some period of time. Callers
|
||||
* should wait for the duration prescribed in the session metadata object
|
||||
* elsewhere in the response before trying again.
|
||||
*/
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED = 3;
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED = 2;
|
||||
|
||||
/**
|
||||
* The session identified in this request could not be found (possibly due to
|
||||
* session expiration).
|
||||
*/
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND = 4;
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND = 3;
|
||||
|
||||
/**
|
||||
* The session identified in this request is still active, but the most
|
||||
* recently-sent code has expired. Callers should request a new code, then
|
||||
* try again.
|
||||
*/
|
||||
CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPT_EXPIRED = 4;
|
||||
}
|
||||
+1
-2
@@ -22,8 +22,7 @@ class StoredVerificationCodeTest {
|
||||
|
||||
private static Stream<Arguments> isValid() {
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
new StoredVerificationCode("code", System.currentTimeMillis(), null, null), "code", true),
|
||||
Arguments.of(new StoredVerificationCode("code", System.currentTimeMillis(), null, null), "code", true),
|
||||
Arguments.of(new StoredVerificationCode("code", System.currentTimeMillis(), null, null), "incorrect", false),
|
||||
Arguments.of(new StoredVerificationCode("", System.currentTimeMillis(), null, null), "", false)
|
||||
);
|
||||
|
||||
+201
-69
@@ -64,6 +64,7 @@ import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -74,6 +75,7 @@ import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
@@ -119,6 +121,7 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class AccountControllerTest {
|
||||
@@ -142,7 +145,8 @@ class AccountControllerTest {
|
||||
private static final byte[] USERNAME_HASH_2 = Base64.getUrlDecoder().decode(BASE_64_URL_USERNAME_HASH_2);
|
||||
private static final byte[] INVALID_USERNAME_HASH = Base64.getDecoder().decode(INVALID_BASE_64_URL_USERNAME_HASH);
|
||||
private static final byte[] TOO_SHORT_USERNAME_HASH = Base64.getUrlDecoder().decode(TOO_SHORT_BASE_64_URL_USERNAME_HASH);
|
||||
|
||||
private static final String BASE_64_URL_ZK_PROOF = "2kambOgmdeeIO0faCMgR6HR4G2BQ5bnhXdIe9ZuZY0NmQXSra5BzDBQ7jzy1cvoEqUHYLpBYMrXudkYPJaWoQg";
|
||||
private static final byte[] ZK_PROOF = Base64.getUrlDecoder().decode(BASE_64_URL_ZK_PROOF);
|
||||
private static final UUID SENDER_REG_LOCK_UUID = UUID.randomUUID();
|
||||
private static final UUID SENDER_TRANSFER_UUID = UUID.randomUUID();
|
||||
|
||||
@@ -179,10 +183,10 @@ class AccountControllerTest {
|
||||
private static RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
|
||||
RegistrationRecoveryPasswordsManager.class);
|
||||
private static ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
private static final UsernameHashZkProofVerifier usernameZkProofVerifier = mock(UsernameHashZkProofVerifier.class);
|
||||
private static TestClock testClock = TestClock.now();
|
||||
|
||||
private static DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
|
||||
private byte[] registration_lock_key = new byte[32];
|
||||
|
||||
private static final SecureBackupServiceConfiguration BACKUP_CFG = MockUtils.buildMock(
|
||||
@@ -194,6 +198,8 @@ class AccountControllerTest {
|
||||
|
||||
private static final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, clientPresenceManager, backupCredentialsGenerator, rateLimiters);
|
||||
private static final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(
|
||||
captchaChecker, rateLimiters, Map.of(TEST_NUMBER, 123456), dynamicConfigurationManager);
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
@@ -214,12 +220,12 @@ class AccountControllerTest {
|
||||
registrationServiceClient,
|
||||
dynamicConfigurationManager,
|
||||
turnTokenGenerator,
|
||||
Map.of(TEST_NUMBER, 123456),
|
||||
captchaChecker,
|
||||
registrationCaptchaManager,
|
||||
pushNotificationManager,
|
||||
changeNumberManager,
|
||||
registrationLockVerificationManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
usernameZkProofVerifier,
|
||||
testClock))
|
||||
.build();
|
||||
|
||||
@@ -246,30 +252,43 @@ class AccountControllerTest {
|
||||
when(rateLimiters.getUsernameLookupLimiter()).thenReturn(usernameLookupLimiter);
|
||||
|
||||
when(senderPinAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
when(senderPinAccount.getRegistrationLock()).thenReturn(new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
when(senderPinAccount.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
|
||||
when(senderHasStorage.getUuid()).thenReturn(UUID.randomUUID());
|
||||
when(senderHasStorage.isStorageSupported()).thenReturn(true);
|
||||
when(senderHasStorage.getRegistrationLock()).thenReturn(new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
when(senderHasStorage.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
|
||||
when(senderRegLockAccount.getRegistrationLock()).thenReturn(new StoredRegistrationLock(Optional.of(registrationLockCredentials.hash()), Optional.of(registrationLockCredentials.salt()), System.currentTimeMillis()));
|
||||
when(senderRegLockAccount.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.of(registrationLockCredentials.hash()),
|
||||
Optional.of(registrationLockCredentials.salt()), System.currentTimeMillis()));
|
||||
when(senderRegLockAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
when(senderRegLockAccount.getUuid()).thenReturn(SENDER_REG_LOCK_UUID);
|
||||
when(senderRegLockAccount.getNumber()).thenReturn(SENDER_REG_LOCK);
|
||||
|
||||
when(senderTransfer.getRegistrationLock()).thenReturn(new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
when(senderTransfer.getRegistrationLock()).thenReturn(
|
||||
new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
when(senderTransfer.getUuid()).thenReturn(SENDER_TRANSFER_UUID);
|
||||
when(senderTransfer.getNumber()).thenReturn(SENDER_TRANSFER);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OLD)).thenReturn(Optional.empty());
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "validchallenge", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "validchallenge", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
|
||||
when(accountsManager.getByE164(eq(SENDER_PIN))).thenReturn(Optional.of(senderPinAccount));
|
||||
when(accountsManager.getByE164(eq(SENDER_REG_LOCK))).thenReturn(Optional.of(senderRegLockAccount));
|
||||
@@ -327,11 +346,12 @@ class AccountControllerTest {
|
||||
when(captchaChecker.verify(eq(VALID_CAPTCHA_TOKEN), anyString()))
|
||||
.thenReturn(new AssessmentResult(true, ""));
|
||||
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO)).when(pinLimiter).validate(eq(SENDER_OVER_PIN));
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO, true)).when(pinLimiter).validate(eq(SENDER_OVER_PIN));
|
||||
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO)).when(smsVoicePrefixLimiter).validate(SENDER_OVER_PREFIX.substring(0, 4+2));
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_IP_HOST);
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_HOST2);
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO, true)).when(smsVoicePrefixLimiter)
|
||||
.validate(SENDER_OVER_PREFIX.substring(0, 4 + 2));
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO, true)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_IP_HOST);
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO, true)).when(smsVoiceIpLimiter).validate(RATE_LIMITED_HOST2);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -356,7 +376,8 @@ class AccountControllerTest {
|
||||
captchaChecker,
|
||||
pushNotificationManager,
|
||||
changeNumberManager,
|
||||
clientPresenceManager);
|
||||
clientPresenceManager,
|
||||
usernameZkProofVerifier);
|
||||
|
||||
clearInvocations(AuthHelper.DISABLED_DEVICE);
|
||||
}
|
||||
@@ -366,8 +387,10 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/fcm/preauth/mytoken/+14152222222")
|
||||
.target("/v1/accounts/fcm/preauth/mytoken/" + SENDER)
|
||||
.request()
|
||||
.get();
|
||||
|
||||
@@ -376,7 +399,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.FCM), challengeTokenCaptor.capture());
|
||||
@@ -412,8 +435,10 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/+14152222222")
|
||||
.target("/v1/accounts/apn/preauth/mytoken/" + SENDER)
|
||||
.request()
|
||||
.get();
|
||||
|
||||
@@ -422,7 +447,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
@@ -435,8 +460,10 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/+14152222222")
|
||||
.target("/v1/accounts/apn/preauth/mytoken/" + SENDER)
|
||||
.queryParam("voip", "true")
|
||||
.request()
|
||||
.get();
|
||||
@@ -446,7 +473,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
@@ -459,8 +486,10 @@ class AccountControllerTest {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.empty());
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/+14152222222")
|
||||
.target("/v1/accounts/apn/preauth/mytoken/" + SENDER)
|
||||
.queryParam("voip", "false")
|
||||
.request()
|
||||
.get();
|
||||
@@ -470,7 +499,7 @@ class AccountControllerTest {
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
eq(PhoneNumberUtil.getInstance().parse(SENDER, null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN), challengeTokenCaptor.capture());
|
||||
@@ -511,6 +540,58 @@ class AccountControllerTest {
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetPreauthExistingSession() throws NumberParseException {
|
||||
final String existingPushCode = "existing-push-code";
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), existingPushCode, new byte[16])));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/" + SENDER)
|
||||
.request()
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient, never()).createRegistrationSession(any(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
|
||||
assertThat(challengeTokenCaptor.getValue()).isEqualTo(existingPushCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetPreauthExistingSessionWithoutPushCode() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, new byte[16])));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/" + SENDER)
|
||||
.request()
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient, never()).createRegistrationSession(any(), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
|
||||
assertThat(challengeTokenCaptor.getValue().length()).isEqualTo(32);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCodeWithExistingSessionFromPreauth() {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
@@ -566,7 +647,7 @@ class AccountControllerTest {
|
||||
@Test
|
||||
void testSendCodeRateLimited() {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(Duration.ofMinutes(10))));
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(Duration.ofMinutes(10), true)));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -887,7 +968,8 @@ class AccountControllerTest {
|
||||
final String challenge = "challenge";
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), challenge, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), challenge, null)));
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
@@ -1037,8 +1119,8 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
.thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1071,8 +1153,8 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
.thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1098,8 +1180,8 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
.thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1125,8 +1207,8 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
.thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1158,8 +1240,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
.thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "1234", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1183,8 +1264,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
.thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "1234", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1208,8 +1288,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
.thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "1234", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1233,8 +1312,8 @@ class AccountControllerTest {
|
||||
final String code = "987654";
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1334,8 +1413,8 @@ class AccountControllerTest {
|
||||
final String code = "987654";
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
@@ -1360,8 +1439,8 @@ class AccountControllerTest {
|
||||
final String code = "987654";
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1394,8 +1473,8 @@ class AccountControllerTest {
|
||||
final String code = "987654";
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1473,8 +1552,8 @@ class AccountControllerTest {
|
||||
final String reglock = "setec-astronomy";
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1525,15 +1604,15 @@ class AccountControllerTest {
|
||||
when(AuthHelper.VALID_ACCOUNT.getDevice(2L)).thenReturn(Optional.of(device2));
|
||||
when(AuthHelper.VALID_ACCOUNT.getDevice(3L)).thenReturn(Optional.of(device3));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
var deviceMessages = List.of(
|
||||
new IncomingMessage(1, 2, 2, "content2"),
|
||||
new IncomingMessage(1, 3, 3, "content3"));
|
||||
new IncomingMessage(1, 2, 2, "content2"),
|
||||
new IncomingMessage(1, 3, 3, "content3"));
|
||||
var deviceKeys = Map.of(1L, new SignedPreKey(), 2L, new SignedPreKey(), 3L, new SignedPreKey());
|
||||
|
||||
final Map<Long, Integer> registrationIds = Map.of(1L, 17, 2L, 47, 3L, 89);
|
||||
@@ -1751,7 +1830,8 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommitUsername() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
void testConfirmUsernameHash()
|
||||
throws UsernameHashNotAvailableException, UsernameReservationNotFoundException, BaseUsernameException {
|
||||
Account account = mock(Account.class);
|
||||
when(account.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH_1));
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1))).thenReturn(account);
|
||||
@@ -1760,13 +1840,15 @@ class AccountControllerTest {
|
||||
.target("/v1/accounts/username_hash/confirm")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(USERNAME_HASH_1)));
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(USERNAME_HASH_1, ZK_PROOF)));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertArrayEquals(response.readEntity(UsernameHashResponse.class).usernameHash(), USERNAME_HASH_1);
|
||||
verify(usernameZkProofVerifier).verifyProof(ZK_PROOF, USERNAME_HASH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommitUnreservedUsername() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
void testConfirmUnreservedUsernameHash()
|
||||
throws UsernameHashNotAvailableException, UsernameReservationNotFoundException, BaseUsernameException {
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1)))
|
||||
.thenThrow(new UsernameReservationNotFoundException());
|
||||
Response response =
|
||||
@@ -1774,12 +1856,14 @@ class AccountControllerTest {
|
||||
.target("/v1/accounts/username_hash/confirm")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(USERNAME_HASH_1)));
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(USERNAME_HASH_1, ZK_PROOF)));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
verify(usernameZkProofVerifier).verifyProof(ZK_PROOF, USERNAME_HASH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommitLapsedUsername() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
void testConfirmLapsedUsernameHash()
|
||||
throws UsernameHashNotAvailableException, UsernameReservationNotFoundException, BaseUsernameException {
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1)))
|
||||
.thenThrow(new UsernameHashNotAvailableException());
|
||||
Response response =
|
||||
@@ -1787,8 +1871,54 @@ class AccountControllerTest {
|
||||
.target("/v1/accounts/username_hash/confirm")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(USERNAME_HASH_1)));
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(USERNAME_HASH_1, ZK_PROOF)));
|
||||
assertThat(response.getStatus()).isEqualTo(410);
|
||||
verify(usernameZkProofVerifier).verifyProof(ZK_PROOF, USERNAME_HASH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConfirmUsernameHashInvalidBase64UrlEncoding() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target("/v1/accounts/username_hash/confirm")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(
|
||||
// Has '+' and '='characters which are invalid in base64url
|
||||
"""
|
||||
{
|
||||
"usernameHash": "jh1jJ50oGn9wUXAFNtDus6AJgWOQ6XbZzF+wCv7OOQs=",
|
||||
"zkProof": "iYXE0QPK60PS3lGa-xdNv0GlXA3B03xQLzltSf-2xmscyS_8fjy5H9ymfaEr62PcVY7tsWhWjOOvcCnhmP_HS="
|
||||
}
|
||||
"""));
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
verifyNoInteractions(usernameZkProofVerifier);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConfirmUsernameHashInvalidHashSize() {
|
||||
byte[] usernameHash = new byte[31];
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target("/v1/accounts/username_hash/confirm")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(usernameHash, ZK_PROOF)));
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
verifyNoInteractions(usernameZkProofVerifier);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommitUsernameHashWithInvalidProof() throws BaseUsernameException {
|
||||
doThrow(new BaseUsernameException("invalid username")).when(usernameZkProofVerifier).verifyProof(eq(ZK_PROOF), eq(USERNAME_HASH_1));
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target("/v1/accounts/username_hash/confirm")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(new ConfirmUsernameHashRequest(USERNAME_HASH_1, ZK_PROOF)));
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
verify(usernameZkProofVerifier).verifyProof(ZK_PROOF, USERNAME_HASH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1994,7 +2124,7 @@ class AccountControllerTest {
|
||||
when(accountsManager.getByAccountIdentifier(accountIdentifier)).thenReturn(Optional.of(account));
|
||||
|
||||
MockUtils.updateRateLimiterResponseToFail(
|
||||
rateLimiters, RateLimiters.Handle.CHECK_ACCOUNT_EXISTENCE, "127.0.0.1", expectedRetryAfter);
|
||||
rateLimiters, RateLimiters.Handle.CHECK_ACCOUNT_EXISTENCE, "127.0.0.1", expectedRetryAfter, true);
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/account/%s", accountIdentifier))
|
||||
@@ -2059,7 +2189,7 @@ class AccountControllerTest {
|
||||
void testLookupUsernameRateLimited() throws RateLimitExceededException {
|
||||
final Duration expectedRetryAfter = Duration.ofSeconds(13);
|
||||
MockUtils.updateRateLimiterResponseToFail(
|
||||
rateLimiters, RateLimiters.Handle.USERNAME_LOOKUP, "127.0.0.1", expectedRetryAfter);
|
||||
rateLimiters, RateLimiters.Handle.USERNAME_LOOKUP, "127.0.0.1", expectedRetryAfter, true);
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target(String.format("v1/accounts/username_hash/%s", BASE_64_URL_USERNAME_HASH_1))
|
||||
.request()
|
||||
@@ -2114,8 +2244,10 @@ class AccountControllerTest {
|
||||
Arguments.of("123456", null, false),
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, null, null), false),
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, "123456", null), false),
|
||||
Arguments.of("654321", new StoredVerificationCode(null, 0, "123456", null), false),
|
||||
Arguments.of("123456", new StoredVerificationCode(null, 0, "123456", null), true)
|
||||
Arguments.of("654321", new StoredVerificationCode(null, 0, "123456", null),
|
||||
false),
|
||||
Arguments.of("123456", new StoredVerificationCode(null, 0, "123456", null),
|
||||
true)
|
||||
);
|
||||
}
|
||||
}
|
||||
+454
@@ -0,0 +1,454 @@
|
||||
/*
|
||||
* Copyright 2023 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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.client.Invocation;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
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.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class AccountControllerV2Test {
|
||||
|
||||
private static final long SESSION_EXPIRATION_SECONDS = Duration.ofMinutes(10).toSeconds();
|
||||
|
||||
private static final String NEW_NUMBER = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final ChangeNumberManager changeNumberManager = mock(ChangeNumberManager.class);
|
||||
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
|
||||
RegistrationRecoveryPasswordsManager.class);
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager = mock(
|
||||
RegistrationLockVerificationManager.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final RateLimiter registrationLimiter = mock(RateLimiter.class);
|
||||
|
||||
private final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(
|
||||
new PolymorphicAuthValueFactoryProvider.Binder<>(
|
||||
ImmutableSet.of(AuthenticatedAccount.class,
|
||||
DisabledPermittedAuthenticatedAccount.class)))
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
|
||||
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
|
||||
.setMapper(SystemMapper.getMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new AccountControllerV2(accountsManager, changeNumberManager,
|
||||
new PhoneVerificationTokenManager(registrationServiceClient, registrationRecoveryPasswordsManager),
|
||||
registrationLockVerificationManager, rateLimiters))
|
||||
.build();
|
||||
|
||||
@Nested
|
||||
class ChangeNumber {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any())).thenAnswer(
|
||||
(Answer<Account>) invocation -> {
|
||||
final Account account = invocation.getArgument(0, Account.class);
|
||||
final String number = invocation.getArgument(1, String.class);
|
||||
final String pniIdentityKey = invocation.getArgument(2, String.class);
|
||||
|
||||
final UUID uuid = account.getUuid();
|
||||
final List<Device> devices = account.getDevices();
|
||||
|
||||
final Account updatedAccount = mock(Account.class);
|
||||
when(updatedAccount.getUuid()).thenReturn(uuid);
|
||||
when(updatedAccount.getNumber()).thenReturn(number);
|
||||
when(updatedAccount.getPhoneNumberIdentityKey()).thenReturn(pniIdentityKey);
|
||||
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(UUID.randomUUID());
|
||||
when(updatedAccount.getDevices()).thenReturn(devices);
|
||||
|
||||
for (long i = 1; i <= 3; i++) {
|
||||
final Optional<Device> d = account.getDevice(i);
|
||||
when(updatedAccount.getDevice(i)).thenReturn(d);
|
||||
}
|
||||
|
||||
return updatedAccount;
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberSuccess() throws Exception {
|
||||
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS))));
|
||||
|
||||
final AccountIdentityResponse accountIdentityResponse =
|
||||
resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(
|
||||
new ChangeNumberRequest(encodeSessionId("session"), null, NEW_NUMBER, "123", "123",
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(), Collections.emptyMap()),
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
|
||||
any());
|
||||
|
||||
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
|
||||
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
|
||||
assertNotEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unprocessableRequestJson() {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(unprocessableJson()))) {
|
||||
assertEquals(400, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingBasicAuthorization() {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request();
|
||||
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidBasicAuthorization() {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, "Basic but-invalid");
|
||||
try (Response response = request.put(Entity.json(invalidRequestJson()))) {
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidRequestBody() {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(invalidRequestJson()))) {
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rateLimitedNumber() throws Exception {
|
||||
doThrow(new RateLimitExceededException(null, true))
|
||||
.when(registrationLimiter).validate(anyString());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
|
||||
assertEquals(429, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void registrationServiceTimeout() {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
|
||||
assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void registrationServiceSessionCheck(@Nullable final RegistrationServiceSession session, final int expectedStatus,
|
||||
final String message) {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.ofNullable(session)));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
|
||||
assertEquals(expectedStatus, response.getStatus(), message);
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Arguments> registrationServiceSessionCheck() {
|
||||
return Stream.of(
|
||||
Arguments.of(null, 401, "session not found"),
|
||||
Arguments.of(new RegistrationServiceSession(new byte[16], "+18005551234", false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS), 400,
|
||||
"session number mismatch"),
|
||||
Arguments.of(
|
||||
new RegistrationServiceSession(new byte[16], NEW_NUMBER, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS),
|
||||
401,
|
||||
"session not verified")
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(RegistrationLockError.class)
|
||||
void registrationLock(final RegistrationLockError error) throws Exception {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
Optional.of(new RegistrationServiceSession(new byte[16], NEW_NUMBER, true, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS))));
|
||||
|
||||
when(accountsManager.getByE164(any())).thenReturn(Optional.of(mock(Account.class)));
|
||||
|
||||
final Exception e = switch (error) {
|
||||
case MISMATCH -> new WebApplicationException(error.getExpectedStatus());
|
||||
case RATE_LIMITED -> new RateLimitExceededException(null, true);
|
||||
};
|
||||
doThrow(e)
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(requestJson("sessionId", NEW_NUMBER)))) {
|
||||
assertEquals(error.getExpectedStatus(), response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationTrue() throws Exception {
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
final byte[] recoveryPassword = new byte[32];
|
||||
try (Response response = request.put(Entity.json(requestJsonRecoveryPassword(recoveryPassword, NEW_NUMBER)))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
final AccountIdentityResponse accountIdentityResponse = response.readEntity(AccountIdentityResponse.class);
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(NEW_NUMBER), any(), any(), any(),
|
||||
any());
|
||||
|
||||
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
|
||||
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
|
||||
assertNotEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationFalse() {
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.put(Entity.json(requestJsonRecoveryPassword(new byte[32], NEW_NUMBER)))) {
|
||||
assertEquals(403, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the given Recovery Password
|
||||
*/
|
||||
private static String requestJsonRecoveryPassword(final byte[] recoveryPassword, final String newNumber) {
|
||||
return requestJson("", recoveryPassword, newNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the give session ID and recovery password
|
||||
*/
|
||||
private static String requestJson(final String sessionId, final byte[] recoveryPassword, final String newNumber) {
|
||||
return String.format("""
|
||||
{
|
||||
"sessionId": "%s",
|
||||
"recoveryPassword": "%s",
|
||||
"number": "%s",
|
||||
"reglock": "1234",
|
||||
"pniIdentityKey": "5678",
|
||||
"deviceMessages": [],
|
||||
"devicePniSignedPrekeys": {},
|
||||
"pniRegistrationIds": {}
|
||||
}
|
||||
""", encodeSessionId(sessionId), encodeRecoveryPassword(recoveryPassword), newNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the give session ID
|
||||
*/
|
||||
private static String requestJson(final String sessionId, final String newNumber) {
|
||||
return requestJson(sessionId, new byte[0], newNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request JSON in the shape of {@link org.whispersystems.textsecuregcm.entities.ChangeNumberRequest}, but that
|
||||
* fails validation
|
||||
*/
|
||||
private static String invalidRequestJson() {
|
||||
return """
|
||||
{
|
||||
"sessionId": null
|
||||
}
|
||||
""";
|
||||
}
|
||||
|
||||
/**
|
||||
* Request JSON that cannot be marshalled into
|
||||
* {@link org.whispersystems.textsecuregcm.entities.ChangeNumberRequest}
|
||||
*/
|
||||
private static String unprocessableJson() {
|
||||
return """
|
||||
{
|
||||
"sessionId": []
|
||||
}
|
||||
""";
|
||||
}
|
||||
|
||||
private static String encodeSessionId(final String sessionId) {
|
||||
return Base64.getUrlEncoder().encodeToString(sessionId.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String encodeRecoveryPassword(final byte[] recoveryPassword) {
|
||||
return Base64.getEncoder().encodeToString(recoveryPassword);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class PhoneNumberDiscoverability {
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
AccountsHelper.setupMockUpdate(accountsManager);
|
||||
}
|
||||
@Test
|
||||
void testSetPhoneNumberDiscoverability() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/phone_number_discoverability")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(new PhoneNumberDiscoverabilityRequest(true)));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
|
||||
ArgumentCaptor<Boolean> discoverabilityCapture = ArgumentCaptor.forClass(Boolean.class);
|
||||
verify(AuthHelper.VALID_ACCOUNT).setDiscoverableByPhoneNumber(discoverabilityCapture.capture());
|
||||
assertThat(discoverabilityCapture.getValue()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetNullPhoneNumberDiscoverability() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/phone_number_discoverability")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(
|
||||
"""
|
||||
{
|
||||
"discoverableByPhoneNumber": null
|
||||
}
|
||||
"""));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
verify(AuthHelper.VALID_ACCOUNT, never()).setDiscoverableByPhoneNumber(anyBoolean());
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -86,7 +86,8 @@ class ChallengeControllerTest {
|
||||
""";
|
||||
|
||||
final Duration retryAfter = Duration.ofMinutes(17);
|
||||
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimitChallengeManager).answerPushChallenge(any(), any());
|
||||
doThrow(new RateLimitExceededException(retryAfter, true)).when(rateLimitChallengeManager)
|
||||
.answerPushChallenge(any(), any());
|
||||
|
||||
final Response response = EXTENSION.target("/v1/challenge")
|
||||
.request()
|
||||
@@ -128,7 +129,8 @@ class ChallengeControllerTest {
|
||||
""";
|
||||
|
||||
final Duration retryAfter = Duration.ofMinutes(17);
|
||||
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimitChallengeManager).answerRecaptchaChallenge(any(), any(), any(), any());
|
||||
doThrow(new RateLimitExceededException(retryAfter, true)).when(rateLimitChallengeManager)
|
||||
.answerRecaptchaChallenge(any(), any(), any(), any());
|
||||
|
||||
final Response response = EXTENSION.target("/v1/challenge")
|
||||
.request()
|
||||
|
||||
+62
-7
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -29,7 +30,6 @@ import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.asJson;
|
||||
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.jsonFixture;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
@@ -54,10 +54,13 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.client.Invocation;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -607,6 +610,7 @@ class MessageControllerTest {
|
||||
final String senderNumber = "+12125550001";
|
||||
final UUID senderAci = UUID.randomUUID();
|
||||
final UUID senderPni = UUID.randomUUID();
|
||||
final String userAgent = "user-agent";
|
||||
UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -623,12 +627,13 @@ class MessageControllerTest {
|
||||
.target(String.format("/v1/messages/report/%s/%s", senderNumber, messageGuid))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, userAgent)
|
||||
.post(null);
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent);
|
||||
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
|
||||
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
|
||||
|
||||
@@ -640,12 +645,13 @@ class MessageControllerTest {
|
||||
.target(String.format("/v1/messages/report/%s/%s", senderNumber, messageGuid))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, userAgent)
|
||||
.post(null);
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -654,6 +660,7 @@ class MessageControllerTest {
|
||||
final String senderNumber = "+12125550001";
|
||||
final UUID senderAci = UUID.randomUUID();
|
||||
final UUID senderPni = UUID.randomUUID();
|
||||
final String userAgent = "user-agent";
|
||||
UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -670,12 +677,13 @@ class MessageControllerTest {
|
||||
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, userAgent)
|
||||
.post(null);
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent);
|
||||
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
|
||||
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
|
||||
|
||||
@@ -688,12 +696,13 @@ class MessageControllerTest {
|
||||
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, userAgent)
|
||||
.post(null);
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty(), userAgent);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -727,7 +736,8 @@ class MessageControllerTest {
|
||||
eq(Optional.of(senderPni)),
|
||||
eq(messageGuid),
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[3])).orElse(false)));
|
||||
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[3])).orElse(false)),
|
||||
any());
|
||||
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
|
||||
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
|
||||
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.empty());
|
||||
@@ -748,7 +758,52 @@ class MessageControllerTest {
|
||||
eq(Optional.of(senderPni)),
|
||||
eq(messageGuid),
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[5])).orElse(false)));
|
||||
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[5])).orElse(false)),
|
||||
any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testReportMessageByAciWithNullSpamReportToken(Entity<?> entity, boolean expectOk) {
|
||||
|
||||
final String senderNumber = "+12125550001";
|
||||
final UUID senderAci = UUID.randomUUID();
|
||||
final UUID senderPni = UUID.randomUUID();
|
||||
UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(senderAci);
|
||||
when(account.getNumber()).thenReturn(senderNumber);
|
||||
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
|
||||
when(deletedAccountsManager.findDeletedAccountE164(senderAci)).thenReturn(Optional.of(senderNumber));
|
||||
when(accountsManager.getPhoneNumberIdentifier(senderNumber)).thenReturn(senderPni);
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.post(entity);
|
||||
|
||||
Matcher<Integer> matcher = expectOk ? is(equalTo(202)) : not(equalTo(202));
|
||||
assertThat(response.getStatus(), matcher);
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testReportMessageByAciWithNullSpamReportToken() {
|
||||
return Stream.of(
|
||||
Arguments.of(Entity.json(new SpamReport(new byte[5])), true),
|
||||
Arguments.of(Entity.json("{\"token\":\"AAAAAAA\"}"), true),
|
||||
Arguments.of(Entity.json(new SpamReport(new byte[0])), true),
|
||||
Arguments.of(Entity.json(new SpamReport(null)), true),
|
||||
Arguments.of(Entity.json("{\"token\": \"\"}"), true),
|
||||
Arguments.of(Entity.json("{\"token\": null}"), true),
|
||||
Arguments.of(Entity.json("null"), true),
|
||||
Arguments.of(Entity.json("{\"weird\": 123}"), true),
|
||||
Arguments.of(Entity.json("\"weirder\""), false),
|
||||
Arguments.of(Entity.json("weirdest"), false)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+67
-7
@@ -59,6 +59,7 @@ 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.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerPublicParams;
|
||||
@@ -255,7 +256,8 @@ class ProfileControllerTest {
|
||||
|
||||
@Test
|
||||
void testProfileGetByAciRateLimited() throws RateLimitExceededException {
|
||||
doThrow(new RateLimitExceededException(Duration.ofSeconds(13))).when(rateLimiter).validate(AuthHelper.VALID_UUID);
|
||||
doThrow(new RateLimitExceededException(Duration.ofSeconds(13), true)).when(rateLimiter)
|
||||
.validate(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response= resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO)
|
||||
@@ -326,7 +328,8 @@ class ProfileControllerTest {
|
||||
|
||||
@Test
|
||||
void testProfileGetByPniRateLimited() throws RateLimitExceededException {
|
||||
doThrow(new RateLimitExceededException(Duration.ofSeconds(13))).when(rateLimiter).validate(AuthHelper.VALID_UUID);
|
||||
doThrow(new RateLimitExceededException(Duration.ofSeconds(13), true)).when(rateLimiter)
|
||||
.validate(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response= resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_PNI_TWO)
|
||||
@@ -727,7 +730,9 @@ class ProfileControllerTest {
|
||||
.target("/v1/profile")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false, List.of()), MediaType.APPLICATION_JSON_TYPE));
|
||||
.put(Entity.entity(
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
|
||||
List.of()), MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
@@ -735,13 +740,68 @@ class ProfileControllerTest {
|
||||
verify(profilesManager, never()).set(any(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testSetProfilePaymentAddressCountryNotAllowedExistingPaymentAddress(
|
||||
final boolean existingPaymentAddressOnProfile) throws InvalidInputException {
|
||||
when(dynamicPaymentsConfiguration.getDisallowedPrefixes())
|
||||
.thenReturn(List.of(AuthHelper.VALID_NUMBER_TWO.substring(0, 3)));
|
||||
|
||||
ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(AuthHelper.VALID_UUID);
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any()))
|
||||
.thenReturn(Optional.of(
|
||||
new VersionedProfile("1", "name", null, null, null,
|
||||
existingPaymentAddressOnProfile ? RandomStringUtils.randomAlphanumeric(776) : null,
|
||||
commitment.serialize())));
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
|
||||
List.of()), MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
if (existingPaymentAddressOnProfile) {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq("yetanotherversion"));
|
||||
verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
|
||||
verifyNoMoreInteractions(s3client);
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
assertThat(profile.getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.getAvatar()).isNull();
|
||||
assertThat(profile.getVersion()).isEqualTo("yetanotherversion");
|
||||
assertThat(profile.getName()).isEqualTo(name);
|
||||
assertThat(profile.getAboutEmoji()).isNull();
|
||||
assertThat(profile.getAbout()).isNull();
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo(paymentAddress);
|
||||
} else {
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
verify(profilesManager, never()).set(any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetProfileByVersion() throws RateLimitExceededException {
|
||||
VersionedProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/validversion")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VersionedProfileResponse.class);
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/validversion")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VersionedProfileResponse.class);
|
||||
|
||||
assertThat(profile.getBaseProfileResponse().getIdentityKey()).isEqualTo(ACCOUNT_TWO_IDENTITY_KEY);
|
||||
assertThat(profile.getName()).isEqualTo("validname");
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class ProvisioningControllerTest {
|
||||
|
||||
private RateLimiter messagesRateLimiter;
|
||||
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final ProvisioningManager provisioningManager = mock(ProvisioningManager.class);
|
||||
|
||||
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(
|
||||
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.setMapper(SystemMapper.getMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new ProvisioningController(rateLimiters, provisioningManager))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
reset(rateLimiters, provisioningManager);
|
||||
|
||||
messagesRateLimiter = mock(RateLimiter.class);
|
||||
when(rateLimiters.getMessagesLimiter()).thenReturn(messagesRateLimiter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendProvisioningMessage() {
|
||||
final String destination = UUID.randomUUID().toString();
|
||||
final byte[] messageBody = "test".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(provisioningManager.sendProvisioningMessage(any(), any())).thenReturn(true);
|
||||
|
||||
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
|
||||
.target("/v1/provisioning/" + destination)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new ProvisioningMessage(Base64.getMimeEncoder().encodeToString(messageBody)),
|
||||
MediaType.APPLICATION_JSON))) {
|
||||
|
||||
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
|
||||
|
||||
final ArgumentCaptor<ProvisioningAddress> provisioningAddressCaptor =
|
||||
ArgumentCaptor.forClass(ProvisioningAddress.class);
|
||||
|
||||
final ArgumentCaptor<byte[]> provisioningMessageCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
|
||||
verify(provisioningManager).sendProvisioningMessage(provisioningAddressCaptor.capture(),
|
||||
provisioningMessageCaptor.capture());
|
||||
|
||||
assertEquals(destination, provisioningAddressCaptor.getValue().getAddress());
|
||||
assertEquals(0, provisioningAddressCaptor.getValue().getDeviceId());
|
||||
|
||||
assertArrayEquals(messageBody, provisioningMessageCaptor.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendProvisioningMessageRateLimited() throws RateLimitExceededException {
|
||||
final String destination = UUID.randomUUID().toString();
|
||||
final byte[] messageBody = "test".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
doThrow(new RateLimitExceededException(Duration.ZERO, true))
|
||||
.when(messagesRateLimiter).validate(AuthHelper.VALID_UUID);
|
||||
|
||||
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
|
||||
.target("/v1/provisioning/" + destination)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new ProvisioningMessage(Base64.getMimeEncoder().encodeToString(messageBody)),
|
||||
MediaType.APPLICATION_JSON))) {
|
||||
|
||||
assertEquals(413, response.getStatus());
|
||||
|
||||
verify(provisioningManager, never()).sendProvisioningMessage(any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
+131
-39
@@ -6,14 +6,18 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -35,9 +39,12 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationSession;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
@@ -46,20 +53,29 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class RegistrationControllerTest {
|
||||
|
||||
private static final String NUMBER = "+18005551212";
|
||||
private static final long SESSION_EXPIRATION_SECONDS = Duration.ofMinutes(10).toSeconds();
|
||||
|
||||
private static final String NUMBER = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
private static final String PASSWORD = "password";
|
||||
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager = mock(
|
||||
RegistrationLockVerificationManager.class);
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
|
||||
RegistrationRecoveryPasswordsManager.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
|
||||
private final RateLimiter registrationLimiter = mock(RateLimiter.class);
|
||||
private final RateLimiter pinLimiter = mock(RateLimiter.class);
|
||||
|
||||
private final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
|
||||
@@ -69,14 +85,22 @@ class RegistrationControllerTest {
|
||||
.setMapper(SystemMapper.getMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new RegistrationController(accountsManager, registrationServiceClient, registrationLockVerificationManager,
|
||||
rateLimiters))
|
||||
new RegistrationController(accountsManager,
|
||||
new PhoneVerificationTokenManager(registrationServiceClient, registrationRecoveryPasswordsManager),
|
||||
registrationLockVerificationManager, rateLimiters))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
|
||||
when(rateLimiters.getPinLimiter()).thenReturn(pinLimiter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegistrationRequest() throws Exception {
|
||||
assertFalse(new RegistrationRequest("", new byte[0], new AccountAttributes(), true).isValid());
|
||||
assertFalse(new RegistrationRequest("some", new byte[32], new AccountAttributes(), true).isValid());
|
||||
assertTrue(new RegistrationRequest("", new byte[32], new AccountAttributes(), true).isValid());
|
||||
assertTrue(new RegistrationRequest("some", new byte[0], new AccountAttributes(), true).isValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -115,25 +139,23 @@ class RegistrationControllerTest {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, authorizationHeader(NUMBER));
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(invalidRequestJson()))) {
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rateLimitedSession() throws Exception {
|
||||
final String sessionId = "sessionId";
|
||||
void rateLimitedNumber() throws Exception {
|
||||
doThrow(RateLimitExceededException.class)
|
||||
.when(registrationLimiter).validate(encodeSessionId(sessionId));
|
||||
.when(registrationLimiter).validate(NUMBER);
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, authorizationHeader(NUMBER));
|
||||
try (Response response = request.post(Entity.json(requestJson(sessionId)))) {
|
||||
assertEquals(413, response.getStatus());
|
||||
// In the future, change to assertEquals(429, response.getStatus());
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
|
||||
assertEquals(429, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,15 +167,29 @@ class RegistrationControllerTest {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, authorizationHeader(NUMBER));
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
|
||||
assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationFailureOrTimeout() {
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(new byte[32])))) {
|
||||
assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void registrationServiceSessionCheck(@Nullable final RegistrationSession session, final int expectedStatus,
|
||||
void registrationServiceSessionCheck(@Nullable final RegistrationServiceSession session, final int expectedStatus,
|
||||
final String message) {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.ofNullable(session)));
|
||||
@@ -161,7 +197,7 @@ class RegistrationControllerTest {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, authorizationHeader(NUMBER));
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
|
||||
assertEquals(expectedStatus, response.getStatus(), message);
|
||||
}
|
||||
@@ -170,22 +206,63 @@ class RegistrationControllerTest {
|
||||
static Stream<Arguments> registrationServiceSessionCheck() {
|
||||
return Stream.of(
|
||||
Arguments.of(null, 401, "session not found"),
|
||||
Arguments.of(new RegistrationSession("+18005551234", false), 400, "session number mismatch"),
|
||||
Arguments.of(new RegistrationSession(NUMBER, false), 401, "session not verified")
|
||||
Arguments.of(
|
||||
new RegistrationServiceSession(new byte[16], "+18005551234", false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS),
|
||||
400,
|
||||
"session number mismatch"),
|
||||
Arguments.of(
|
||||
new RegistrationServiceSession(new byte[16], NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS),
|
||||
401,
|
||||
"session not verified")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationTrue() throws InterruptedException {
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
when(accountsManager.create(any(), any(), any(), any(), any()))
|
||||
.thenReturn(mock(Account.class));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
final byte[] recoveryPassword = new byte[32];
|
||||
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(recoveryPassword)))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationFalse() throws InterruptedException {
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJsonRecoveryPassword(new byte[32])))) {
|
||||
assertEquals(403, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(RegistrationLockError.class)
|
||||
void registrationLock(final RegistrationLockError error) throws Exception {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(new RegistrationSession(NUMBER, true))));
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS))));
|
||||
|
||||
when(accountsManager.getByE164(any())).thenReturn(Optional.of(mock(Account.class)));
|
||||
|
||||
final Exception e = switch (error) {
|
||||
case MISMATCH -> new WebApplicationException(error.getExpectedStatus());
|
||||
case RATE_LIMITED -> new RateLimitExceededException(null);
|
||||
case RATE_LIMITED -> new RateLimitExceededException(null, true);
|
||||
};
|
||||
doThrow(e)
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(any(), any());
|
||||
@@ -193,7 +270,7 @@ class RegistrationControllerTest {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, authorizationHeader(NUMBER));
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
|
||||
assertEquals(error.getExpectedStatus(), response.getStatus());
|
||||
}
|
||||
@@ -210,7 +287,10 @@ class RegistrationControllerTest {
|
||||
void deviceTransferAvailable(final boolean existingAccount, final boolean transferSupported,
|
||||
final boolean skipDeviceTransfer, final int expectedStatus) throws Exception {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(new RegistrationSession(NUMBER, true))));
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS))));
|
||||
|
||||
final Optional<Account> maybeAccount;
|
||||
if (existingAccount) {
|
||||
@@ -226,24 +306,27 @@ class RegistrationControllerTest {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, authorizationHeader(NUMBER));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId", skipDeviceTransfer)))) {
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId", new byte[0], skipDeviceTransfer)))) {
|
||||
assertEquals(expectedStatus, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// this is functionally the same as deviceTransferAvailable(existingAccount=false)
|
||||
@Test
|
||||
void success() throws Exception {
|
||||
void registrationSuccess() throws Exception {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(new RegistrationSession(NUMBER, true))));
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
Optional.of(new RegistrationServiceSession(new byte[16], NUMBER, true, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS))));
|
||||
when(accountsManager.create(any(), any(), any(), any(), any()))
|
||||
.thenReturn(mock(Account.class));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, authorizationHeader(NUMBER));
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
try (Response response = request.post(Entity.json(requestJson("sessionId")))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
@@ -252,21 +335,32 @@ class RegistrationControllerTest {
|
||||
/**
|
||||
* Valid request JSON with the give session ID and skipDeviceTransfer
|
||||
*/
|
||||
private static String requestJson(final String sessionId, final boolean skipDeviceTransfer) {
|
||||
private static String requestJson(final String sessionId, final byte[] recoveryPassword, final boolean skipDeviceTransfer) {
|
||||
final String rp = encodeRecoveryPassword(recoveryPassword);
|
||||
return String.format("""
|
||||
{
|
||||
"sessionId": "%s",
|
||||
"accountAttributes": {},
|
||||
"recoveryPassword": "%s",
|
||||
"accountAttributes": {
|
||||
"recoveryPassword": "%s"
|
||||
},
|
||||
"skipDeviceTransfer": %s
|
||||
}
|
||||
""", encodeSessionId(sessionId), skipDeviceTransfer);
|
||||
""", encodeSessionId(sessionId), rp, rp, skipDeviceTransfer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the give session ID
|
||||
* Valid request JSON with the given session ID
|
||||
*/
|
||||
private static String requestJson(final String sessionId) {
|
||||
return requestJson(sessionId, false);
|
||||
return requestJson(sessionId, new byte[0], false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the given Recovery Password
|
||||
*/
|
||||
private static String requestJsonRecoveryPassword(final byte[] recoveryPassword) {
|
||||
return requestJson("", recoveryPassword, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -294,13 +388,11 @@ class RegistrationControllerTest {
|
||||
""";
|
||||
}
|
||||
|
||||
private static String authorizationHeader(final String number) {
|
||||
return "Basic " + Base64.getEncoder().encodeToString(
|
||||
String.format("%s:password", number).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String encodeSessionId(final String sessionId) {
|
||||
return Base64.getEncoder().encodeToString(sessionId.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getUrlEncoder().encodeToString(sessionId.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String encodeRecoveryPassword(final byte[] recoveryPassword) {
|
||||
return Base64.getEncoder().encodeToString(recoveryPassword);
|
||||
}
|
||||
}
|
||||
+1268
File diff suppressed because it is too large.
Load diff
+39
-4
@@ -11,23 +11,28 @@ import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
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.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
class OutgoingMessageEntityTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void toFromEnvelope(@Nullable final UUID sourceUuid, @Nullable final UUID updatedPni) {
|
||||
void roundTripThroughEnvelope(@Nullable final UUID sourceUuid, @Nullable final UUID updatedPni) {
|
||||
final byte[] messageContent = new byte[16];
|
||||
new Random().nextBytes(messageContent);
|
||||
|
||||
final long messageTimestamp = System.currentTimeMillis();
|
||||
final long serverTimestamp = messageTimestamp + 17;
|
||||
|
||||
final OutgoingMessageEntity outgoingMessageEntity = new OutgoingMessageEntity(UUID.randomUUID(),
|
||||
byte[] reportSpamToken = {1, 2, 3, 4, 5};
|
||||
|
||||
final OutgoingMessageEntity outgoingMessageEntity = new OutgoingMessageEntity(
|
||||
UUID.randomUUID(),
|
||||
MessageProtos.Envelope.Type.CIPHERTEXT_VALUE,
|
||||
messageTimestamp,
|
||||
UUID.randomUUID(),
|
||||
@@ -37,15 +42,45 @@ class OutgoingMessageEntityTest {
|
||||
messageContent,
|
||||
serverTimestamp,
|
||||
true,
|
||||
false);
|
||||
false,
|
||||
reportSpamToken);
|
||||
|
||||
assertEquals(outgoingMessageEntity, OutgoingMessageEntity.fromEnvelope(outgoingMessageEntity.toEnvelope()));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> toFromEnvelope() {
|
||||
private static Stream<Arguments> roundTripThroughEnvelope() {
|
||||
return Stream.of(
|
||||
Arguments.of(UUID.randomUUID(), UUID.randomUUID()),
|
||||
Arguments.of(UUID.randomUUID(), null),
|
||||
Arguments.of(null, UUID.randomUUID()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void entityPreservesEnvelope() {
|
||||
final Random random = new Random();
|
||||
|
||||
final byte[] messageContent = new byte[16];
|
||||
random.nextBytes(messageContent);
|
||||
|
||||
final byte[] reportSpamToken = new byte[8];
|
||||
random.nextBytes(reportSpamToken);
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(UUID.randomUUID());
|
||||
|
||||
IncomingMessage message = new IncomingMessage(1, 4444L, 55, "AAAAAA");
|
||||
|
||||
MessageProtos.Envelope baseEnvelope = message.toEnvelope(
|
||||
UUID.randomUUID(),
|
||||
account,
|
||||
123L,
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
true,
|
||||
reportSpamToken);
|
||||
|
||||
MessageProtos.Envelope envelope = baseEnvelope.toBuilder().setServerGuid(UUID.randomUUID().toString()).build();
|
||||
|
||||
assertEquals(envelope, OutgoingMessageEntity.fromEnvelope(envelope).toEnvelope());
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -72,11 +72,11 @@ public class RateLimitedByIpTest {
|
||||
public void testRateLimits() throws Exception {
|
||||
Mockito.doNothing().when(RATE_LIMITER).validate(Mockito.eq(IP));
|
||||
validateSuccess("/test/strict", VALID_X_FORWARDED_FOR);
|
||||
Mockito.doThrow(new RateLimitExceededException(RETRY_AFTER)).when(RATE_LIMITER).validate(Mockito.eq(IP));
|
||||
Mockito.doThrow(new RateLimitExceededException(RETRY_AFTER, true)).when(RATE_LIMITER).validate(Mockito.eq(IP));
|
||||
validateFailure("/test/strict", VALID_X_FORWARDED_FOR, RETRY_AFTER);
|
||||
Mockito.doNothing().when(RATE_LIMITER).validate(Mockito.eq(IP));
|
||||
validateSuccess("/test/strict", VALID_X_FORWARDED_FOR);
|
||||
Mockito.doThrow(new RateLimitExceededException(RETRY_AFTER)).when(RATE_LIMITER).validate(Mockito.eq(IP));
|
||||
Mockito.doThrow(new RateLimitExceededException(RETRY_AFTER, true)).when(RATE_LIMITER).validate(Mockito.eq(IP));
|
||||
validateFailure("/test/strict", VALID_X_FORWARDED_FOR, RETRY_AFTER);
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ public class RateLimitedByIpTest {
|
||||
validateSuccess("/test/loose", "");
|
||||
|
||||
// also checking that even if rate limiter is failing -- it doesn't matter in the case of invalid IP
|
||||
Mockito.doThrow(new RateLimitExceededException(RETRY_AFTER)).when(RATE_LIMITER).validate(Mockito.anyString());
|
||||
Mockito.doThrow(new RateLimitExceededException(RETRY_AFTER, true)).when(RATE_LIMITER).validate(Mockito.anyString());
|
||||
validateFailure("/test/loose", VALID_X_FORWARDED_FOR, RETRY_AFTER);
|
||||
validateSuccess("/test/loose", INVALID_X_FORWARDED_FOR);
|
||||
validateSuccess("/test/loose", "");
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ class MessageMetricsTest {
|
||||
}
|
||||
|
||||
private OutgoingMessageEntity createOutgoingMessageEntity(UUID destinationUuid) {
|
||||
return new OutgoingMessageEntity(UUID.randomUUID(), 1, 1L, null, 1, destinationUuid, null, new byte[]{}, 1, true, false);
|
||||
return new OutgoingMessageEntity(UUID.randomUUID(), 1, 1L, null, 1, destinationUuid, null, new byte[]{}, 1, true, false, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -19,6 +19,7 @@ import static org.mockito.Mockito.when;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.uuid.UUIDComparator;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -163,14 +164,14 @@ class AccountsTest {
|
||||
boolean freshUser = accounts.create(account);
|
||||
|
||||
assertThat(freshUser).isTrue();
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", account.getUuid());
|
||||
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
|
||||
|
||||
freshUser = accounts.create(account);
|
||||
assertThat(freshUser).isTrue();
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", account.getUuid());
|
||||
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
|
||||
@@ -183,7 +184,7 @@ class AccountsTest {
|
||||
|
||||
accounts.create(account);
|
||||
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", account.getUuid());
|
||||
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
|
||||
@@ -212,8 +213,8 @@ class AccountsTest {
|
||||
assertThat(retrievedFirst.isPresent()).isTrue();
|
||||
assertThat(retrievedSecond.isPresent()).isTrue();
|
||||
|
||||
verifyStoredState("+14151112222", uuidFirst, pniFirst, retrievedFirst.get(), accountFirst);
|
||||
verifyStoredState("+14152221111", uuidSecond, pniSecond, retrievedSecond.get(), accountSecond);
|
||||
verifyStoredState("+14151112222", uuidFirst, pniFirst, null, retrievedFirst.get(), accountFirst);
|
||||
verifyStoredState("+14152221111", uuidSecond, pniSecond, null, retrievedSecond.get(), accountSecond);
|
||||
|
||||
retrievedFirst = accounts.getByAccountIdentifier(uuidFirst);
|
||||
retrievedSecond = accounts.getByAccountIdentifier(uuidSecond);
|
||||
@@ -221,8 +222,8 @@ class AccountsTest {
|
||||
assertThat(retrievedFirst.isPresent()).isTrue();
|
||||
assertThat(retrievedSecond.isPresent()).isTrue();
|
||||
|
||||
verifyStoredState("+14151112222", uuidFirst, pniFirst, retrievedFirst.get(), accountFirst);
|
||||
verifyStoredState("+14152221111", uuidSecond, pniSecond, retrievedSecond.get(), accountSecond);
|
||||
verifyStoredState("+14151112222", uuidFirst, pniFirst, null, retrievedFirst.get(), accountFirst);
|
||||
verifyStoredState("+14152221111", uuidSecond, pniSecond, null, retrievedSecond.get(), accountSecond);
|
||||
|
||||
retrievedFirst = accounts.getByPhoneNumberIdentifier(pniFirst);
|
||||
retrievedSecond = accounts.getByPhoneNumberIdentifier(pniSecond);
|
||||
@@ -230,8 +231,8 @@ class AccountsTest {
|
||||
assertThat(retrievedFirst.isPresent()).isTrue();
|
||||
assertThat(retrievedSecond.isPresent()).isTrue();
|
||||
|
||||
verifyStoredState("+14151112222", uuidFirst, pniFirst, retrievedFirst.get(), accountFirst);
|
||||
verifyStoredState("+14152221111", uuidSecond, pniSecond, retrievedSecond.get(), accountSecond);
|
||||
verifyStoredState("+14151112222", uuidFirst, pniFirst, null, retrievedFirst.get(), accountFirst);
|
||||
verifyStoredState("+14152221111", uuidSecond, pniSecond, null, retrievedSecond.get(), accountSecond);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -284,12 +285,12 @@ class AccountsTest {
|
||||
Optional<Account> retrieved = accounts.getByE164("+14151112222");
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
verifyStoredState("+14151112222", uuid, null, retrieved.get(), account);
|
||||
verifyStoredState("+14151112222", uuid, null, null, retrieved.get(), account);
|
||||
|
||||
retrieved = accounts.getByAccountIdentifier(uuid);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
verifyStoredState("+14151112222", uuid, null, retrieved.get(), account);
|
||||
verifyStoredState("+14151112222", uuid, null, null, retrieved.get(), account);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -301,7 +302,14 @@ class AccountsTest {
|
||||
|
||||
accounts.create(account);
|
||||
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
final SecureRandom byteGenerator = new SecureRandom();
|
||||
final byte[] usernameHash = new byte[32];
|
||||
byteGenerator.nextBytes(usernameHash);
|
||||
|
||||
// Set up the existing account to have a username hash
|
||||
accounts.confirmUsernameHash(account, usernameHash);
|
||||
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), usernameHash, account, true);
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", firstUuid);
|
||||
assertPhoneNumberIdentifierConstraintExists(firstPni, firstUuid);
|
||||
@@ -315,7 +323,7 @@ class AccountsTest {
|
||||
|
||||
final boolean freshUser = accounts.create(account);
|
||||
assertThat(freshUser).isFalse();
|
||||
verifyStoredState("+14151112222", firstUuid, firstPni, account, true);
|
||||
verifyStoredState("+14151112222", firstUuid, firstPni, usernameHash, account, true);
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", firstUuid);
|
||||
assertPhoneNumberIdentifierConstraintExists(firstPni, firstUuid);
|
||||
@@ -346,12 +354,12 @@ class AccountsTest {
|
||||
Optional<Account> retrieved = accounts.getByE164("+14151112222");
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), retrieved.get(), account);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, retrieved.get(), account);
|
||||
|
||||
retrieved = accounts.getByAccountIdentifier(account.getUuid());
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
|
||||
device = generateDevice(1);
|
||||
Account unknownAccount = generateAccount("+14151113333", UUID.randomUUID(), UUID.randomUUID(), List.of(device));
|
||||
@@ -362,7 +370,7 @@ class AccountsTest {
|
||||
|
||||
assertThat(account.getVersion()).isEqualTo(2);
|
||||
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
|
||||
account.setVersion(1);
|
||||
|
||||
@@ -372,7 +380,7 @@ class AccountsTest {
|
||||
|
||||
accounts.update(account);
|
||||
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -418,7 +426,7 @@ class AccountsTest {
|
||||
.findAny()
|
||||
.orElseThrow();
|
||||
|
||||
verifyStoredState(expectedAccount.getNumber(), expectedAccount.getUuid(), expectedAccount.getPhoneNumberIdentifier(), retrievedAccount, expectedAccount);
|
||||
verifyStoredState(expectedAccount.getNumber(), expectedAccount.getUuid(), expectedAccount.getPhoneNumberIdentifier(), null, retrievedAccount, expectedAccount);
|
||||
|
||||
users.remove(expectedAccount);
|
||||
}
|
||||
@@ -435,7 +443,7 @@ class AccountsTest {
|
||||
.findAny()
|
||||
.orElseThrow();
|
||||
|
||||
verifyStoredState(expectedAccount.getNumber(), expectedAccount.getUuid(), expectedAccount.getPhoneNumberIdentifier(), retrievedAccount, expectedAccount);
|
||||
verifyStoredState(expectedAccount.getNumber(), expectedAccount.getUuid(), expectedAccount.getPhoneNumberIdentifier(), null, retrievedAccount, expectedAccount);
|
||||
|
||||
users.remove(expectedAccount);
|
||||
}
|
||||
@@ -472,7 +480,7 @@ class AccountsTest {
|
||||
assertPhoneNumberIdentifierConstraintDoesNotExist(deletedAccount.getPhoneNumberIdentifier());
|
||||
|
||||
verifyStoredState(retainedAccount.getNumber(), retainedAccount.getUuid(), retainedAccount.getPhoneNumberIdentifier(),
|
||||
accounts.getByAccountIdentifier(retainedAccount.getUuid()).get(), retainedAccount);
|
||||
null, accounts.getByAccountIdentifier(retainedAccount.getUuid()).get(), retainedAccount);
|
||||
|
||||
{
|
||||
final Account recreatedAccount = generateAccount(deletedAccount.getNumber(), UUID.randomUUID(),
|
||||
@@ -483,7 +491,7 @@ class AccountsTest {
|
||||
assertThat(freshUser).isTrue();
|
||||
assertThat(accounts.getByAccountIdentifier(recreatedAccount.getUuid())).isPresent();
|
||||
verifyStoredState(recreatedAccount.getNumber(), recreatedAccount.getUuid(), recreatedAccount.getPhoneNumberIdentifier(),
|
||||
accounts.getByAccountIdentifier(recreatedAccount.getUuid()).get(), recreatedAccount);
|
||||
null, accounts.getByAccountIdentifier(recreatedAccount.getUuid()).get(), recreatedAccount);
|
||||
|
||||
assertPhoneNumberConstraintExists(recreatedAccount.getNumber(), recreatedAccount.getUuid());
|
||||
assertPhoneNumberIdentifierConstraintExists(recreatedAccount.getPhoneNumberIdentifier(), recreatedAccount.getUuid());
|
||||
@@ -510,13 +518,13 @@ class AccountsTest {
|
||||
Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device));
|
||||
account.setDiscoverableByPhoneNumber(false);
|
||||
accounts.create(account);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, false);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, false);
|
||||
account.setDiscoverableByPhoneNumber(true);
|
||||
accounts.update(account);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, true);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
account.setDiscoverableByPhoneNumber(false);
|
||||
accounts.update(account);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), account, false);
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -541,7 +549,7 @@ class AccountsTest {
|
||||
final Optional<Account> retrieved = accounts.getByE164(originalNumber);
|
||||
assertThat(retrieved).isPresent();
|
||||
|
||||
verifyStoredState(originalNumber, account.getUuid(), account.getPhoneNumberIdentifier(), retrieved.get(), account);
|
||||
verifyStoredState(originalNumber, account.getUuid(), account.getPhoneNumberIdentifier(), null, retrieved.get(), account);
|
||||
}
|
||||
|
||||
accounts.changeNumber(account, targetNumber, targetPni);
|
||||
@@ -558,7 +566,7 @@ class AccountsTest {
|
||||
final Optional<Account> retrieved = accounts.getByE164(targetNumber);
|
||||
assertThat(retrieved).isPresent();
|
||||
|
||||
verifyStoredState(targetNumber, account.getUuid(), account.getPhoneNumberIdentifier(), retrieved.get(), account);
|
||||
verifyStoredState(targetNumber, account.getUuid(), account.getPhoneNumberIdentifier(), null, retrieved.get(), account);
|
||||
|
||||
assertThat(retrieved.get().getPhoneNumberIdentifier()).isEqualTo(targetPni);
|
||||
assertThat(accounts.getByPhoneNumberIdentifier(targetPni)).isPresent();
|
||||
@@ -634,11 +642,7 @@ class AccountsTest {
|
||||
{
|
||||
final Optional<Account> maybeAccount = accounts.getByUsernameHash(USERNAME_HASH_1);
|
||||
|
||||
assertThat(maybeAccount).hasValueSatisfying(retrievedAccount ->
|
||||
assertThat(retrievedAccount.getUsernameHash()).hasValueSatisfying(retrievedUsernameHash ->
|
||||
assertArrayEquals(retrievedUsernameHash, USERNAME_HASH_1)));
|
||||
|
||||
verifyStoredState(account.getNumber(), account.getUuid(), account.getPhoneNumberIdentifier(), maybeAccount.orElseThrow(), account);
|
||||
verifyStoredState(account.getNumber(), account.getUuid(), account.getPhoneNumberIdentifier(), USERNAME_HASH_1, maybeAccount.orElseThrow(), account);
|
||||
}
|
||||
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_2, Duration.ofDays(1));
|
||||
@@ -657,7 +661,7 @@ class AccountsTest {
|
||||
|
||||
assertThat(maybeAccount).isPresent();
|
||||
verifyStoredState(account.getNumber(), account.getUuid(), account.getPhoneNumberIdentifier(),
|
||||
maybeAccount.get(), account);
|
||||
USERNAME_HASH_2, maybeAccount.get(), account);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -678,7 +682,7 @@ class AccountsTest {
|
||||
final Optional<Account> maybeAccount = accounts.getByUsernameHash(USERNAME_HASH_1);
|
||||
|
||||
assertThat(maybeAccount).isPresent();
|
||||
verifyStoredState(firstAccount.getNumber(), firstAccount.getUuid(), firstAccount.getPhoneNumberIdentifier(), maybeAccount.get(), firstAccount);
|
||||
verifyStoredState(firstAccount.getNumber(), firstAccount.getUuid(), firstAccount.getPhoneNumberIdentifier(), USERNAME_HASH_1, maybeAccount.get(), firstAccount);
|
||||
|
||||
// throw an error if second account tries to reserve or confirm the same username hash
|
||||
assertThatExceptionOfType(ContestedOptimisticLockException.class)
|
||||
@@ -929,7 +933,7 @@ class AccountsTest {
|
||||
assertThat(pniConstraintResponse.hasItem()).isFalse();
|
||||
}
|
||||
|
||||
private void verifyStoredState(String number, UUID uuid, UUID pni, Account expecting, boolean canonicallyDiscoverable) {
|
||||
private void verifyStoredState(String number, UUID uuid, UUID pni, byte[] usernameHash, Account expecting, boolean canonicallyDiscoverable) {
|
||||
final DynamoDbClient db = dynamoDbExtension.getDynamoDbClient();
|
||||
|
||||
final GetItemResponse get = db.getItem(GetItemRequest.builder()
|
||||
@@ -951,19 +955,22 @@ class AccountsTest {
|
||||
assertThat(AttributeValues.getByteArray(get.item(), Accounts.ATTR_UAK, null))
|
||||
.isEqualTo(expecting.getUnidentifiedAccessKey().orElse(null));
|
||||
|
||||
assertArrayEquals(AttributeValues.getByteArray(get.item(), Accounts.ATTR_USERNAME_HASH, null), usernameHash);
|
||||
|
||||
Account result = Accounts.fromItem(get.item());
|
||||
verifyStoredState(number, uuid, pni, result, expecting);
|
||||
verifyStoredState(number, uuid, pni, usernameHash, result, expecting);
|
||||
} else {
|
||||
throw new AssertionError("No data");
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyStoredState(String number, UUID uuid, UUID pni, Account result, Account expecting) {
|
||||
private void verifyStoredState(String number, UUID uuid, UUID pni, byte[] usernameHash, Account result, Account expecting) {
|
||||
assertThat(result.getNumber()).isEqualTo(number);
|
||||
assertThat(result.getPhoneNumberIdentifier()).isEqualTo(pni);
|
||||
assertThat(result.getLastSeen()).isEqualTo(expecting.getLastSeen());
|
||||
assertThat(result.getUuid()).isEqualTo(uuid);
|
||||
assertThat(result.getVersion()).isEqualTo(expecting.getVersion());
|
||||
assertArrayEquals(result.getUsernameHash().orElse(null), usernameHash);
|
||||
assertThat(Arrays.equals(result.getUnidentifiedAccessKey().get(), expecting.getUnidentifiedAccessKey().get())).isTrue();
|
||||
|
||||
for (Device expectingDevice : expecting.getDevices()) {
|
||||
|
||||
+6
-6
@@ -81,13 +81,13 @@ class ReportMessageManagerTest {
|
||||
|
||||
when(reportMessageDynamoDb.remove(any())).thenReturn(false);
|
||||
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni), messageGuid,
|
||||
reporterUuid, Optional.empty());
|
||||
reporterUuid, Optional.empty(), "user-agent");
|
||||
|
||||
assertEquals(0, reportMessageManager.getRecentReportCount(sourceAccount));
|
||||
|
||||
when(reportMessageDynamoDb.remove(any())).thenReturn(true);
|
||||
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni), messageGuid,
|
||||
reporterUuid, Optional.empty());
|
||||
reporterUuid, Optional.empty(), "user-agent");
|
||||
|
||||
assertEquals(1, reportMessageManager.getRecentReportCount(sourceAccount));
|
||||
verify(listener).handleMessageReported(sourceNumber, messageGuid, reporterUuid, Optional.empty());
|
||||
@@ -100,7 +100,7 @@ class ReportMessageManagerTest {
|
||||
|
||||
for (int i = 0; i < 100; i++) {
|
||||
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni),
|
||||
messageGuid, UUID.randomUUID(), Optional.empty());
|
||||
messageGuid, UUID.randomUUID(), Optional.empty(), "user-agent");
|
||||
}
|
||||
|
||||
assertTrue(reportMessageManager.getRecentReportCount(sourceAccount) > 10);
|
||||
@@ -114,7 +114,7 @@ class ReportMessageManagerTest {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni),
|
||||
messageGuid,
|
||||
reporterUuid, Optional.empty());
|
||||
reporterUuid, Optional.empty(), "user-agent");
|
||||
}
|
||||
|
||||
assertEquals(1, reportMessageManager.getRecentReportCount(sourceAccount));
|
||||
@@ -127,11 +127,11 @@ class ReportMessageManagerTest {
|
||||
|
||||
for (int i = 0; i < 100; i++) {
|
||||
reportMessageManager.report(Optional.empty(), Optional.of(sourceAci), Optional.of(sourcePni),
|
||||
messageGuid, UUID.randomUUID(), Optional.empty());
|
||||
messageGuid, UUID.randomUUID(), Optional.empty(), "user-agent");
|
||||
}
|
||||
|
||||
reportMessageManager.report(Optional.empty(), Optional.of(sourceAci), Optional.empty(),
|
||||
messageGuid, UUID.randomUUID(), Optional.empty());
|
||||
messageGuid, UUID.randomUUID(), Optional.empty(), "user-agent");
|
||||
|
||||
final int recentReportCount = reportMessageManager.getRecentReportCount(sourceAccount);
|
||||
assertTrue(recentReportCount > 10);
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class SerializedExpireableJsonDynamoStoreTest {
|
||||
|
||||
static abstract class Tests<T> {
|
||||
|
||||
private static final String TABLE_NAME = "test";
|
||||
private static final String KEY = "foo";
|
||||
|
||||
static final Clock clock = Clock.systemUTC();
|
||||
|
||||
interface Value {
|
||||
|
||||
String v();
|
||||
}
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = DynamoDbExtension.builder()
|
||||
.tableName(TABLE_NAME)
|
||||
.hashKey(SerializedExpireableJsonDynamoStore.KEY_KEY)
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(SerializedExpireableJsonDynamoStore.KEY_KEY)
|
||||
.attributeType(ScalarAttributeType.S)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
private SerializedExpireableJsonDynamoStore<T> store;
|
||||
|
||||
abstract SerializedExpireableJsonDynamoStore<T> getStore(final DynamoDbAsyncClient dynamoDbClient,
|
||||
final String tableName);
|
||||
|
||||
abstract T testValue(final String v);
|
||||
|
||||
abstract T maybeExpiredTestValue(final String v);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
store = getStore(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), TABLE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStoreAndFind() throws Exception {
|
||||
assertEquals(Optional.empty(), store.findForKey(KEY).get(1, TimeUnit.SECONDS));
|
||||
|
||||
final T original = testValue("1234");
|
||||
final T second = testValue("5678");
|
||||
|
||||
store.insert(KEY, original).get(1, TimeUnit.SECONDS);
|
||||
{
|
||||
final Optional<T> maybeValue = store.findForKey(KEY).get(1, TimeUnit.SECONDS);
|
||||
|
||||
assertTrue(maybeValue.isPresent());
|
||||
assertEquals(original, maybeValue.get());
|
||||
}
|
||||
|
||||
assertThrows(Exception.class, () -> store.insert(KEY, second).get(1, TimeUnit.SECONDS));
|
||||
|
||||
assertDoesNotThrow(() -> store.update(KEY, second).get(1, TimeUnit.SECONDS));
|
||||
{
|
||||
final Optional<T> maybeValue = store.findForKey(KEY).get(1, TimeUnit.SECONDS);
|
||||
|
||||
assertTrue(maybeValue.isPresent());
|
||||
assertEquals(second, maybeValue.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRemove() throws Exception {
|
||||
assertEquals(Optional.empty(), store.findForKey(KEY).get(1, TimeUnit.SECONDS));
|
||||
|
||||
store.insert(KEY, testValue("1234")).get(1, TimeUnit.SECONDS);
|
||||
assertTrue(store.findForKey(KEY).get(1, TimeUnit.SECONDS).isPresent());
|
||||
|
||||
store.remove(KEY).get(1, TimeUnit.SECONDS);
|
||||
assertFalse(store.findForKey(KEY).get(1, TimeUnit.SECONDS).isPresent());
|
||||
|
||||
final T v = maybeExpiredTestValue("1234");
|
||||
store.insert(KEY, v).get(1, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(v instanceof SerializedExpireableJsonDynamoStore.Expireable,
|
||||
store.findForKey(KEY).get(1, TimeUnit.SECONDS).isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
record Expires(String v, long timestamp) implements SerializedExpireableJsonDynamoStore.Expireable, Tests.Value {
|
||||
|
||||
static final Duration EXPIRATION = Duration.ofSeconds(30);
|
||||
|
||||
@Override
|
||||
public long getExpirationEpochSeconds() {
|
||||
return Instant.ofEpochMilli(timestamp()).plus(EXPIRATION).getEpochSecond();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Expireable extends Tests<Expires> {
|
||||
|
||||
class ExpiresStore extends SerializedExpireableJsonDynamoStore<Expires> {
|
||||
|
||||
public ExpiresStore(final DynamoDbAsyncClient dynamoDbClient, final String tableName) {
|
||||
super(dynamoDbClient, tableName, clock);
|
||||
}
|
||||
}
|
||||
|
||||
private static final long VALID_TIMESTAMP = Instant.now().toEpochMilli();
|
||||
private static final long EXPIRED_TIMESTAMP = Instant.now().minus(Expires.EXPIRATION).minus(
|
||||
Duration.ofHours(1)).toEpochMilli();
|
||||
|
||||
@Override
|
||||
SerializedExpireableJsonDynamoStore<Expires> getStore(final DynamoDbAsyncClient dynamoDbClient,
|
||||
final String tableName) {
|
||||
return new ExpiresStore(dynamoDbClient, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
Expires testValue(final String v) {
|
||||
return new Expires(v, VALID_TIMESTAMP);
|
||||
}
|
||||
|
||||
@Override
|
||||
Expires maybeExpiredTestValue(final String v) {
|
||||
return new Expires(v, EXPIRED_TIMESTAMP);
|
||||
}
|
||||
}
|
||||
|
||||
record DoesNotExpire(String v) implements Tests.Value {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Nested
|
||||
class NotExpireable extends Tests<DoesNotExpire> {
|
||||
|
||||
class DoesNotExpireStore extends SerializedExpireableJsonDynamoStore<DoesNotExpire> {
|
||||
|
||||
public DoesNotExpireStore(final DynamoDbAsyncClient dynamoDbClient, final String tableName) {
|
||||
super(dynamoDbClient, tableName, clock);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
SerializedExpireableJsonDynamoStore<DoesNotExpire> getStore(final DynamoDbAsyncClient dynamoDbClient,
|
||||
final String tableName) {
|
||||
return new DoesNotExpireStore(dynamoDbClient, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
DoesNotExpire testValue(final String v) {
|
||||
return new DoesNotExpire(v);
|
||||
}
|
||||
|
||||
@Override
|
||||
DoesNotExpire maybeExpiredTestValue(final String v) {
|
||||
return new DoesNotExpire(v);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+8
-4
@@ -53,8 +53,10 @@ class VerificationCodeStoreTest {
|
||||
void testStoreAndFind() {
|
||||
assertEquals(Optional.empty(), verificationCodeStore.findForNumber(PHONE_NUMBER));
|
||||
|
||||
final StoredVerificationCode originalCode = new StoredVerificationCode("1234", VALID_TIMESTAMP, "abcd", "session".getBytes(StandardCharsets.UTF_8));
|
||||
final StoredVerificationCode secondCode = new StoredVerificationCode("5678", VALID_TIMESTAMP, "efgh", "changed-session".getBytes(StandardCharsets.UTF_8));
|
||||
final StoredVerificationCode originalCode = new StoredVerificationCode("1234", VALID_TIMESTAMP, "abcd",
|
||||
"session".getBytes(StandardCharsets.UTF_8));
|
||||
final StoredVerificationCode secondCode = new StoredVerificationCode("5678", VALID_TIMESTAMP, "efgh",
|
||||
"changed-session".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
verificationCodeStore.insert(PHONE_NUMBER, originalCode);
|
||||
{
|
||||
@@ -77,13 +79,15 @@ class VerificationCodeStoreTest {
|
||||
void testRemove() {
|
||||
assertEquals(Optional.empty(), verificationCodeStore.findForNumber(PHONE_NUMBER));
|
||||
|
||||
verificationCodeStore.insert(PHONE_NUMBER, new StoredVerificationCode("1234", VALID_TIMESTAMP, "abcd", "session".getBytes(StandardCharsets.UTF_8)));
|
||||
verificationCodeStore.insert(PHONE_NUMBER,
|
||||
new StoredVerificationCode("1234", VALID_TIMESTAMP, "abcd", "session".getBytes(StandardCharsets.UTF_8)));
|
||||
assertTrue(verificationCodeStore.findForNumber(PHONE_NUMBER).isPresent());
|
||||
|
||||
verificationCodeStore.remove(PHONE_NUMBER);
|
||||
assertFalse(verificationCodeStore.findForNumber(PHONE_NUMBER).isPresent());
|
||||
|
||||
verificationCodeStore.insert(PHONE_NUMBER, new StoredVerificationCode("1234", EXPIRED_TIMESTAMP, "abcd", "session".getBytes(StandardCharsets.UTF_8)));
|
||||
verificationCodeStore.insert(PHONE_NUMBER,
|
||||
new StoredVerificationCode("1234", EXPIRED_TIMESTAMP, "abcd", "session".getBytes(StandardCharsets.UTF_8)));
|
||||
assertFalse(verificationCodeStore.findForNumber(PHONE_NUMBER).isPresent());
|
||||
}
|
||||
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
|
||||
|
||||
class VerificationSessionsTest {
|
||||
|
||||
private static final String TABLE_NAME = "verification_sessions_test";
|
||||
|
||||
private static final Clock clock = Clock.systemUTC();
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = DynamoDbExtension.builder()
|
||||
.tableName(TABLE_NAME)
|
||||
.hashKey(VerificationSessions.KEY_KEY)
|
||||
.attributeDefinition(AttributeDefinition.builder()
|
||||
.attributeName(VerificationSessions.KEY_KEY)
|
||||
.attributeType(ScalarAttributeType.S)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
private VerificationSessions verificationSessions;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
verificationSessions = new VerificationSessions(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), TABLE_NAME, clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExpiration() {
|
||||
final Instant created = Instant.now().minusSeconds(60);
|
||||
final Instant updates = Instant.now();
|
||||
final Duration remoteExpiration = Duration.ofMinutes(2);
|
||||
|
||||
final VerificationSession verificationSession = new VerificationSession(null,
|
||||
List.of(VerificationSession.Information.PUSH_CHALLENGE), Collections.emptyList(), true,
|
||||
created.toEpochMilli(), updates.toEpochMilli(), remoteExpiration.toSeconds());
|
||||
|
||||
assertEquals(updates.plus(remoteExpiration).getEpochSecond(), verificationSession.getExpirationEpochSeconds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStore() {
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
|
||||
final String sessionId = "sessionId";
|
||||
|
||||
final Optional<VerificationSession> absentSession = verificationSessions.findForKey(sessionId).join();
|
||||
assertTrue(absentSession.isEmpty());
|
||||
|
||||
final VerificationSession session = new VerificationSession(null,
|
||||
List.of(VerificationSession.Information.PUSH_CHALLENGE), Collections.emptyList(), true,
|
||||
clock.millis(), clock.millis(), Duration.ofMinutes(1).toSeconds());
|
||||
|
||||
verificationSessions.insert(sessionId, session).join();
|
||||
|
||||
assertEquals(session, verificationSessions.findForKey(sessionId).join().orElseThrow());
|
||||
|
||||
final CompletionException ce = assertThrows(CompletionException.class,
|
||||
() -> verificationSessions.insert(sessionId, session).join());
|
||||
|
||||
final Throwable t = ExceptionUtils.unwrap(ce);
|
||||
assertTrue(t instanceof ConditionalCheckFailedException,
|
||||
"inserting with the same key should fail conditional checks");
|
||||
|
||||
final VerificationSession updatedSession = new VerificationSession(null, Collections.emptyList(),
|
||||
List.of(VerificationSession.Information.PUSH_CHALLENGE), true, clock.millis(), clock.millis(),
|
||||
Duration.ofMinutes(2).toSeconds());
|
||||
verificationSessions.update(sessionId, updatedSession).join();
|
||||
|
||||
assertEquals(updatedSession, verificationSessions.findForKey(sessionId).join().orElseThrow());
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
-3
@@ -25,7 +25,6 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
@@ -36,8 +35,6 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
|
||||
+8
-12
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.controllers;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -14,7 +13,6 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
@@ -32,7 +30,6 @@ import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
@@ -55,20 +52,19 @@ class DonationControllerTest {
|
||||
|
||||
private static final long nowEpochSeconds = 1_500_000_000L;
|
||||
|
||||
@RegisterExtension
|
||||
static WireMockExtension wm = WireMockExtension.newInstance()
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
static BadgesConfiguration getBadgesConfiguration() {
|
||||
return new BadgesConfiguration(
|
||||
List.of(
|
||||
new BadgeConfiguration("TEST", "other", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST1", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST2", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))),
|
||||
new BadgeConfiguration("TEST", "other", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG",
|
||||
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST1", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG",
|
||||
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST2", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG",
|
||||
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG",
|
||||
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))),
|
||||
List.of("TEST"),
|
||||
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3"));
|
||||
}
|
||||
|
||||
+1
-1
@@ -340,7 +340,7 @@ class KeysControllerTest {
|
||||
@Test
|
||||
void testGetKeysRateLimited() throws RateLimitExceededException {
|
||||
Duration retryAfter = Duration.ofSeconds(31);
|
||||
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimiter).validate(anyString());
|
||||
doThrow(new RateLimitExceededException(retryAfter, true)).when(rateLimiter).validate(anyString());
|
||||
|
||||
Response result = resources.getJerseyTest()
|
||||
.target(String.format("/v2/keys/%s/*", EXISTS_PNI))
|
||||
|
||||
@@ -60,11 +60,12 @@ public final class MockUtils {
|
||||
final RateLimiters rateLimitersMock,
|
||||
final RateLimiters.Handle handle,
|
||||
final String input,
|
||||
final Duration retryAfter) {
|
||||
final Duration retryAfter,
|
||||
final boolean legacyStatusCode) {
|
||||
final RateLimiter mockRateLimiter = Mockito.mock(RateLimiter.class);
|
||||
doReturn(Optional.of(mockRateLimiter)).when(rateLimitersMock).byHandle(eq(handle));
|
||||
try {
|
||||
doThrow(new RateLimitExceededException(retryAfter)).when(mockRateLimiter).validate(eq(input));
|
||||
doThrow(new RateLimitExceededException(retryAfter, legacyStatusCode)).when(mockRateLimiter).validate(eq(input));
|
||||
} catch (final RateLimitExceededException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 4dbea3c3ce...5b394c0482.
Reference in new issue
Block a user