mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:46:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a01f96e0e4 | ||
|
|
1d1e3ba79d | ||
|
|
2c9c50711f | ||
|
|
d3f0ab8c6d | ||
|
|
80a3a8a43c | ||
|
|
e6e6eb323d | ||
|
|
681a5bafb4 | ||
|
|
5bec89ecc8 | ||
|
|
69ed0edb74 | ||
|
|
ad5925908e | ||
|
|
d186245c5c | ||
|
|
bbbab4b8a4 | ||
|
|
f83080eb8d | ||
|
|
e0178fa0ea | ||
|
|
c6a79ca176 | ||
|
|
6426e6cc49 | ||
|
|
b13cb098ce | ||
|
|
afda5ca98f | ||
|
|
eb57d87513 | ||
|
|
fbf6b9826e | ||
|
|
a01b29a6bd |
No files matched your search
@@ -290,6 +290,9 @@ remoteConfig:
|
||||
paymentsService:
|
||||
userAuthenticationTokenSharedSecret: 0000000f0000000f0000000f0000000f0000000f0000000f0000000f0000000f # hex-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
fixerApiKey: unset
|
||||
coinMarketCapApiKey: unset
|
||||
coinMarketCapCurrencyIds:
|
||||
MOB: 7878
|
||||
paymentCurrencies:
|
||||
# list of symbols for supported currencies
|
||||
- MOB
|
||||
|
||||
@@ -106,9 +106,9 @@ import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
|
||||
import org.whispersystems.textsecuregcm.controllers.VoiceVerificationController;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
import org.whispersystems.textsecuregcm.currency.FtxClient;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.ContentLengthFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
|
||||
@@ -223,6 +223,7 @@ 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;
|
||||
@@ -367,8 +368,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
VerificationCodeStore pendingDevices = new VerificationCodeStore(dynamoDbClient,
|
||||
config.getDynamoDbTables().getPendingDevices().getTableName());
|
||||
|
||||
RedisClientFactory pubSubClientFactory = new RedisClientFactory("pubsub_cache", config.getPubsubCacheConfiguration().getUrl(), config.getPubsubCacheConfiguration().getReplicaUrls(), config.getPubsubCacheConfiguration().getCircuitBreakerConfiguration());
|
||||
ReplicatedJedisPool pubsubClient = pubSubClientFactory.getRedisClientPool();
|
||||
reactor.util.Metrics.MicrometerConfiguration.useRegistry(Metrics.globalRegistry);
|
||||
Schedulers.enableMetrics();
|
||||
|
||||
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()
|
||||
@@ -382,9 +388,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FaultTolerantRedisCluster pushSchedulerCluster = new FaultTolerantRedisCluster("push_scheduler", config.getPushSchedulerCluster(), redisClientResources);
|
||||
FaultTolerantRedisCluster rateLimitersCluster = new FaultTolerantRedisCluster("rate_limiters", config.getRateLimitersCluster(), redisClientResources);
|
||||
|
||||
BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(10_000);
|
||||
final BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(100_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(), keyspaceNotificationDispatchQueue);
|
||||
final ArrayBlockingQueue<Runnable> receiptSenderQueue = new ArrayBlockingQueue<>(10_000);
|
||||
final BlockingQueue<Runnable> receiptSenderQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "receiptSenderQueue"), Collections.emptyList(), receiptSenderQueue);
|
||||
|
||||
final BlockingQueue<Runnable> fcmSenderQueue = new LinkedBlockingQueue<>();
|
||||
@@ -463,9 +469,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messagesCluster, Clock.systemUTC(),
|
||||
keyspaceNotificationDispatchExecutor, messageDeletionAsyncExecutor);
|
||||
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster, dynamicConfigurationManager);
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster, config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager);
|
||||
UsernameGenerator usernameGenerator = new UsernameGenerator(config.getUsername());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
|
||||
messageDeletionAsyncExecutor);
|
||||
UsernameGenerator usernameGenerator = new UsernameGenerator(config.getUsername());
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient, config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
@@ -569,10 +577,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
DeletedAccountsTableCrawler deletedAccountsTableCrawler = new DeletedAccountsTableCrawler(deletedAccountsManager, deletedAccountsDirectoryReconcilers, cacheCluster, recurringJobExecutor);
|
||||
|
||||
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
|
||||
FixerClient fixerClient = new FixerClient(currencyClient, config.getPaymentsServiceConfiguration().getFixerApiKey());
|
||||
FtxClient ftxClient = new FtxClient(currencyClient);
|
||||
CurrencyConversionManager currencyManager = new CurrencyConversionManager(fixerClient, ftxClient, config.getPaymentsServiceConfiguration().getPaymentCurrencies());
|
||||
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
|
||||
FixerClient fixerClient = new FixerClient(currencyClient, config.getPaymentsServiceConfiguration().getFixerApiKey());
|
||||
CoinMarketCapClient coinMarketCapClient = new CoinMarketCapClient(currencyClient, config.getPaymentsServiceConfiguration().getCoinMarketCapApiKey(), config.getPaymentsServiceConfiguration().getCoinMarketCapCurrencyIds());
|
||||
CurrencyConversionManager currencyManager = new CurrencyConversionManager(fixerClient, coinMarketCapClient,
|
||||
cacheCluster, config.getPaymentsServiceConfiguration().getPaymentCurrencies(), Clock.systemUTC());
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(apnPushNotificationScheduler);
|
||||
@@ -646,7 +655,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(
|
||||
new AccountController(pendingAccountsManager, accountsManager, abusiveHostRules, rateLimiters,
|
||||
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator, config.getTestDevices(),
|
||||
recaptchaClient, pushNotificationManager, changeNumberManager, backupCredentialsGenerator));
|
||||
recaptchaClient, pushNotificationManager, changeNumberManager, backupCredentialsGenerator,
|
||||
clientPresenceManager, clock));
|
||||
|
||||
environment.jersey().register(new KeysController(rateLimiters, keys, accountsManager));
|
||||
|
||||
|
||||
+21
-9
@@ -21,6 +21,20 @@ public class StoredRegistrationLock {
|
||||
|
||||
private final long lastSeen;
|
||||
|
||||
/**
|
||||
* @return milliseconds since the last time the account was seen.
|
||||
*/
|
||||
private long timeSinceLastSeen() {
|
||||
return System.currentTimeMillis() - lastSeen;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if the registration lock and salt are both set.
|
||||
*/
|
||||
private boolean hasLockAndSalt() {
|
||||
return registrationLock.isPresent() && registrationLockSalt.isPresent();
|
||||
}
|
||||
|
||||
public StoredRegistrationLock(Optional<String> registrationLock, Optional<String> registrationLockSalt, long lastSeen) {
|
||||
this.registrationLock = registrationLock;
|
||||
this.registrationLockSalt = registrationLockSalt;
|
||||
@@ -28,24 +42,22 @@ public class StoredRegistrationLock {
|
||||
}
|
||||
|
||||
public boolean requiresClientRegistrationLock() {
|
||||
return registrationLock.isPresent() && registrationLockSalt.isPresent() && System.currentTimeMillis() - lastSeen < TimeUnit.DAYS.toMillis(7);
|
||||
boolean hasTimeRemaining = getTimeRemaining() >= 0;
|
||||
return hasLockAndSalt() && hasTimeRemaining;
|
||||
}
|
||||
|
||||
public boolean needsFailureCredentials() {
|
||||
return registrationLock.isPresent() && registrationLockSalt.isPresent();
|
||||
return hasLockAndSalt();
|
||||
}
|
||||
|
||||
public long getTimeRemaining() {
|
||||
return TimeUnit.DAYS.toMillis(7) - (System.currentTimeMillis() - lastSeen);
|
||||
return TimeUnit.DAYS.toMillis(7) - timeSinceLastSeen();
|
||||
}
|
||||
|
||||
public boolean verify(@Nullable String clientRegistrationLock) {
|
||||
if (Util.isEmpty(clientRegistrationLock)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (registrationLock.isPresent() && registrationLockSalt.isPresent() && !Util.isEmpty(clientRegistrationLock)) {
|
||||
return new AuthenticationCredentials(registrationLock.get(), registrationLockSalt.get()).verify(clientRegistrationLock);
|
||||
if (hasLockAndSalt() && Util.nonEmpty(clientRegistrationLock)) {
|
||||
AuthenticationCredentials credentials = new AuthenticationCredentials(registrationLock.get(), registrationLockSalt.get());
|
||||
return credentials.verify(clientRegistrationLock);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
+18
@@ -9,8 +9,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class PaymentsServiceConfiguration {
|
||||
|
||||
@@ -18,6 +20,14 @@ public class PaymentsServiceConfiguration {
|
||||
@JsonProperty
|
||||
private String userAuthenticationTokenSharedSecret;
|
||||
|
||||
@NotBlank
|
||||
@JsonProperty
|
||||
private String coinMarketCapApiKey;
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private Map<@NotBlank String, Integer> coinMarketCapCurrencyIds;
|
||||
|
||||
@NotEmpty
|
||||
@JsonProperty
|
||||
private String fixerApiKey;
|
||||
@@ -30,6 +40,14 @@ public class PaymentsServiceConfiguration {
|
||||
return Hex.decodeHex(userAuthenticationTokenSharedSecret.toCharArray());
|
||||
}
|
||||
|
||||
public String getCoinMarketCapApiKey() {
|
||||
return coinMarketCapApiKey;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getCoinMarketCapCurrencyIds() {
|
||||
return coinMarketCapCurrencyIds;
|
||||
}
|
||||
|
||||
public String getFixerApiKey() {
|
||||
return fixerApiKey;
|
||||
}
|
||||
|
||||
+91
-28
@@ -19,8 +19,10 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -82,6 +84,7 @@ import org.whispersystems.textsecuregcm.entities.UsernameResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotification;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient;
|
||||
@@ -127,6 +130,8 @@ public class AccountController {
|
||||
|
||||
private static final String NONSTANDARD_USERNAME_COUNTER_NAME = name(AccountController.class, "nonStandardUsername");
|
||||
|
||||
private static final String LOCKED_ACCOUNT_COUNTER_NAME = name(AccountController.class, "lockedAccount");
|
||||
|
||||
private static final String CHALLENGE_PRESENT_TAG_NAME = "present";
|
||||
private static final String CHALLENGE_MATCH_TAG_NAME = "matches";
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
@@ -139,6 +144,8 @@ public class AccountController {
|
||||
private static final String REGION_CODE_TAG_NAME = "regionCode";
|
||||
private static final String VERIFICATION_TRANSPORT_TAG_NAME = "transport";
|
||||
private static final String SCORE_TAG_NAME = "score";
|
||||
private static final String LOCK_REASON_TAG_NAME = "lockReason";
|
||||
private static final String ALREADY_LOCKED_TAG_NAME = "alreadyLocked";
|
||||
|
||||
|
||||
private final StoredVerificationCodeManager pendingAccounts;
|
||||
@@ -154,35 +161,64 @@ public class AccountController {
|
||||
private final ExternalServiceCredentialGenerator backupServiceCredentialGenerator;
|
||||
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
private final Clock clock;
|
||||
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
|
||||
public AccountController(StoredVerificationCodeManager pendingAccounts,
|
||||
AccountsManager accounts,
|
||||
AbusiveHostRules abusiveHostRules,
|
||||
RateLimiters rateLimiters,
|
||||
RegistrationServiceClient registrationServiceClient,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
TurnTokenGenerator turnTokenGenerator,
|
||||
Map<String, Integer> testDevices,
|
||||
RecaptchaClient recaptchaClient,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ChangeNumberManager changeNumberManager,
|
||||
ExternalServiceCredentialGenerator backupServiceCredentialGenerator)
|
||||
{
|
||||
this.pendingAccounts = pendingAccounts;
|
||||
this.accounts = accounts;
|
||||
this.abusiveHostRules = abusiveHostRules;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.testDevices = testDevices;
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
public AccountController(
|
||||
StoredVerificationCodeManager pendingAccounts,
|
||||
AccountsManager accounts,
|
||||
AbusiveHostRules abusiveHostRules,
|
||||
RateLimiters rateLimiters,
|
||||
RegistrationServiceClient registrationServiceClient,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
TurnTokenGenerator turnTokenGenerator,
|
||||
Map<String, Integer> testDevices,
|
||||
RecaptchaClient recaptchaClient,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ChangeNumberManager changeNumberManager,
|
||||
ExternalServiceCredentialGenerator backupServiceCredentialGenerator,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
Clock clock
|
||||
) {
|
||||
this.pendingAccounts = pendingAccounts;
|
||||
this.accounts = accounts;
|
||||
this.abusiveHostRules = abusiveHostRules;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.testDevices = testDevices;
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.recaptchaClient = recaptchaClient;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public AccountController(
|
||||
StoredVerificationCodeManager pendingAccounts,
|
||||
AccountsManager accounts,
|
||||
AbusiveHostRules abusiveHostRules,
|
||||
RateLimiters rateLimiters,
|
||||
RegistrationServiceClient registrationServiceClient,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
TurnTokenGenerator turnTokenGenerator,
|
||||
Map<String, Integer> testDevices,
|
||||
RecaptchaClient recaptchaClient,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ChangeNumberManager changeNumberManager,
|
||||
ExternalServiceCredentialGenerator backupServiceCredentialGenerator
|
||||
) {
|
||||
this(pendingAccounts, accounts, abusiveHostRules, rateLimiters,
|
||||
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator, testDevices, recaptchaClient,
|
||||
pushNotificationManager, changeNumberManager,
|
||||
backupServiceCredentialGenerator, null, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -205,7 +241,7 @@ public class AccountController {
|
||||
|
||||
String pushChallenge = generatePushChallenge();
|
||||
StoredVerificationCode storedVerificationCode =
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), pushChallenge, null, null);
|
||||
new StoredVerificationCode(null, clock.millis(), pushChallenge, null, null);
|
||||
|
||||
pendingAccounts.store(number, storedVerificationCode);
|
||||
pushNotificationManager.sendRegistrationChallengeNotification(pushToken, tokenType, storedVerificationCode.pushCode());
|
||||
@@ -310,7 +346,7 @@ public class AccountController {
|
||||
messageTransport, clientType, acceptLanguage.orElse(null), REGISTRATION_RPC_TIMEOUT).join();
|
||||
|
||||
final StoredVerificationCode storedVerificationCode = new StoredVerificationCode(null,
|
||||
System.currentTimeMillis(),
|
||||
clock.millis(),
|
||||
maybeStoredVerificationCode.map(StoredVerificationCode::pushCode).orElse(null),
|
||||
null,
|
||||
sessionId);
|
||||
@@ -776,25 +812,51 @@ public class AccountController {
|
||||
rateLimiters.getPinLimiter().validate(existingAccount.getNumber());
|
||||
}
|
||||
|
||||
final String phoneNumber = existingAccount.getNumber();
|
||||
|
||||
if (!existingRegistrationLock.verify(clientRegistrationLock)) {
|
||||
// At this point, the client verified ownership of the phone number but doesn’t have the reglock PIN.
|
||||
// Freezing the existing account credentials will definitively start the reglock timeout.
|
||||
// Until the timeout, the current reglock can still be supplied,
|
||||
// along with phone number verification, to restore access.
|
||||
/* boolean alreadyLocked = existingAccount.hasLockedCredentials();
|
||||
Metrics.counter(LOCKED_ACCOUNT_COUNTER_NAME,
|
||||
LOCK_REASON_TAG_NAME, "verifiedNumberFailedReglock",
|
||||
ALREADY_LOCKED_TAG_NAME, Boolean.toString(alreadyLocked))
|
||||
.increment();
|
||||
|
||||
final Account updatedAccount;
|
||||
if (!alreadyLocked) {
|
||||
updatedAccount = accounts.update(existingAccount, Account::lockAuthenticationCredentials);
|
||||
} else {
|
||||
updatedAccount = existingAccount;
|
||||
}
|
||||
|
||||
List<Long> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
clientPresenceManager.disconnectAllPresences(updatedAccount.getUuid(), deviceIds); */
|
||||
|
||||
throw new WebApplicationException(Response.status(423)
|
||||
.entity(new RegistrationLockFailure(existingRegistrationLock.getTimeRemaining(),
|
||||
existingRegistrationLock.needsFailureCredentials() ? existingBackupCredentials : null))
|
||||
.build());
|
||||
}
|
||||
|
||||
rateLimiters.getPinLimiter().clear(existingAccount.getNumber());
|
||||
rateLimiters.getPinLimiter().clear(phoneNumber);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean pushChallengeMatches(
|
||||
@VisibleForTesting
|
||||
static boolean pushChallengeMatches(
|
||||
final String number,
|
||||
final Optional<String> pushChallenge,
|
||||
final Optional<StoredVerificationCode> storedVerificationCode) {
|
||||
|
||||
final String countryCode = Util.getCountryCode(number);
|
||||
final String region = Util.getRegion(number);
|
||||
Optional<String> storedPushChallenge = storedVerificationCode.map(StoredVerificationCode::pushCode);
|
||||
boolean match = Optionals.zipWith(pushChallenge, storedPushChallenge, String::equals).orElse(false);
|
||||
final Optional<String> storedPushChallenge = storedVerificationCode.map(StoredVerificationCode::pushCode);
|
||||
|
||||
final boolean match = Optionals.zipWith(pushChallenge, storedPushChallenge, String::equals).orElse(false);
|
||||
|
||||
Metrics.counter(PUSH_CHALLENGE_COUNTER_NAME,
|
||||
COUNTRY_CODE_TAG_NAME, countryCode,
|
||||
REGION_TAG_NAME, region,
|
||||
@@ -802,6 +864,7 @@ public class AccountController {
|
||||
CHALLENGE_PRESENT_TAG_NAME, Boolean.toString(pushChallenge.isPresent()),
|
||||
CHALLENGE_MATCH_TAG_NAME, Boolean.toString(match))
|
||||
.increment();
|
||||
|
||||
return match;
|
||||
}
|
||||
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package org.whispersystems.textsecuregcm.currency;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Map;
|
||||
|
||||
public class CoinMarketCapClient {
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final String apiKey;
|
||||
private final Map<String, Integer> currencyIdsBySymbol;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoinMarketCapClient.class);
|
||||
|
||||
record CoinMarketCapResponse(@JsonProperty("data") PriceConversionResponse priceConversionResponse) {};
|
||||
|
||||
record PriceConversionResponse(int id, String symbol, Map<String, PriceConversionQuote> quote) {};
|
||||
|
||||
record PriceConversionQuote(BigDecimal price) {};
|
||||
|
||||
public CoinMarketCapClient(final HttpClient httpClient, final String apiKey, final Map<String, Integer> currencyIdsBySymbol) {
|
||||
this.httpClient = httpClient;
|
||||
this.apiKey = apiKey;
|
||||
this.currencyIdsBySymbol = currencyIdsBySymbol;
|
||||
}
|
||||
|
||||
public BigDecimal getSpotPrice(final String currency, final String base) throws IOException {
|
||||
if (!currencyIdsBySymbol.containsKey(currency)) {
|
||||
throw new IllegalArgumentException("No currency ID found for " + currency);
|
||||
}
|
||||
|
||||
final URI quoteUri = URI.create(
|
||||
String.format("https://pro-api.coinmarketcap.com/v2/tools/price-conversion?amount=1&id=%d&convert=%s",
|
||||
currencyIdsBySymbol.get(currency), base));
|
||||
|
||||
try {
|
||||
final HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
|
||||
.GET()
|
||||
.uri(quoteUri)
|
||||
.header("X-CMC_PRO_API_KEY", apiKey)
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
logger.warn("CoinMarketCapRequest failed with response: {}", response);
|
||||
throw new IOException("CoinMarketCap request failed with status code " + response.statusCode());
|
||||
}
|
||||
|
||||
return extractConversionRate(parseResponse(response.body()), base);
|
||||
} catch (final InterruptedException e) {
|
||||
throw new IOException("Interrupted while waiting for a response", e);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static CoinMarketCapResponse parseResponse(final String responseJson) throws JsonProcessingException {
|
||||
return SystemMapper.getMapper().readValue(responseJson, CoinMarketCapResponse.class);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static BigDecimal extractConversionRate(final CoinMarketCapResponse response, final String destinationCurrency)
|
||||
throws IOException {
|
||||
if (!response.priceConversionResponse().quote.containsKey(destinationCurrency)) {
|
||||
throw new IOException("Response does not contain conversion rate for " + destinationCurrency);
|
||||
}
|
||||
|
||||
return response.priceConversionResponse().quote.get(destinationCurrency).price();
|
||||
}
|
||||
}
|
||||
+75
-41
@@ -1,47 +1,63 @@
|
||||
package org.whispersystems.textsecuregcm.currency;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class CurrencyConversionManager implements Managed {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CurrencyConversionManager.class);
|
||||
|
||||
private static final long FIXER_INTERVAL = TimeUnit.HOURS.toMillis(2);
|
||||
private static final long FTX_INTERVAL = TimeUnit.MINUTES.toMillis(5);
|
||||
@VisibleForTesting
|
||||
static final Duration FIXER_REFRESH_INTERVAL = Duration.ofHours(2);
|
||||
|
||||
private static final Duration COIN_MARKET_CAP_REFRESH_INTERVAL = Duration.ofMinutes(5);
|
||||
|
||||
@VisibleForTesting
|
||||
static final String COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY = "CurrencyConversionManager::CoinMarketCapCacheCurrent";
|
||||
private static final String COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY = "CurrencyConversionManager::CoinMarketCapCacheData";
|
||||
|
||||
private final FixerClient fixerClient;
|
||||
private final FtxClient ftxClient;
|
||||
private final CoinMarketCapClient coinMarketCapClient;
|
||||
private final FaultTolerantRedisCluster cacheCluster;
|
||||
private final Clock clock;
|
||||
|
||||
private final List<String> currencies;
|
||||
|
||||
private AtomicReference<CurrencyConversionEntityList> cached = new AtomicReference<>(null);
|
||||
private final AtomicReference<CurrencyConversionEntityList> cached = new AtomicReference<>(null);
|
||||
|
||||
private long fixerUpdatedTimestamp;
|
||||
private long ftxUpdatedTimestamp;
|
||||
private Instant fixerUpdatedTimestamp = Instant.MIN;
|
||||
|
||||
private Map<String, BigDecimal> cachedFixerValues;
|
||||
private Map<String, BigDecimal> cachedFtxValues;
|
||||
private Map<String, BigDecimal> cachedCoinMarketCapValues;
|
||||
|
||||
public CurrencyConversionManager(FixerClient fixerClient, FtxClient ftxClient, List<String> currencies) {
|
||||
public CurrencyConversionManager(final FixerClient fixerClient,
|
||||
final CoinMarketCapClient coinMarketCapClient,
|
||||
final FaultTolerantRedisCluster cacheCluster,
|
||||
final List<String> currencies,
|
||||
final Clock clock) {
|
||||
this.fixerClient = fixerClient;
|
||||
this.ftxClient = ftxClient;
|
||||
this.coinMarketCapClient = coinMarketCapClient;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.currencies = currencies;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public Optional<CurrencyConversionEntityList> getCurrencyConversions() {
|
||||
@@ -70,25 +86,55 @@ public class CurrencyConversionManager implements Managed {
|
||||
|
||||
@VisibleForTesting
|
||||
void updateCacheIfNecessary() throws IOException {
|
||||
if (System.currentTimeMillis() - fixerUpdatedTimestamp > FIXER_INTERVAL || cachedFixerValues == null) {
|
||||
this.cachedFixerValues = new HashMap<>(fixerClient.getConversionsForBase("USD"));
|
||||
this.fixerUpdatedTimestamp = System.currentTimeMillis();
|
||||
if (Duration.between(fixerUpdatedTimestamp, clock.instant()).abs().compareTo(FIXER_REFRESH_INTERVAL) >= 0 || cachedFixerValues == null) {
|
||||
this.cachedFixerValues = new HashMap<>(fixerClient.getConversionsForBase("USD"));
|
||||
this.fixerUpdatedTimestamp = clock.instant();
|
||||
}
|
||||
|
||||
if (System.currentTimeMillis() - ftxUpdatedTimestamp > FTX_INTERVAL || cachedFtxValues == null) {
|
||||
Map<String, BigDecimal> cachedFtxValues = new HashMap<>();
|
||||
{
|
||||
final Map<String, BigDecimal> coinMarketCapValuesFromSharedCache = cacheCluster.withCluster(connection -> {
|
||||
final Map<String, BigDecimal> parsedSharedCacheData = new HashMap<>();
|
||||
|
||||
for (String currency : currencies) {
|
||||
cachedFtxValues.put(currency, ftxClient.getSpotPrice(currency, "USD"));
|
||||
connection.sync().hgetall(COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY).forEach((currency, conversionRate) ->
|
||||
parsedSharedCacheData.put(currency, new BigDecimal(conversionRate)));
|
||||
|
||||
return parsedSharedCacheData;
|
||||
});
|
||||
|
||||
if (coinMarketCapValuesFromSharedCache != null && !coinMarketCapValuesFromSharedCache.isEmpty()) {
|
||||
cachedCoinMarketCapValues = coinMarketCapValuesFromSharedCache;
|
||||
}
|
||||
}
|
||||
|
||||
final boolean shouldUpdateSharedCache = cacheCluster.withCluster(connection ->
|
||||
"OK".equals(connection.sync().set(COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY,
|
||||
"true",
|
||||
SetArgs.Builder.nx().ex(COIN_MARKET_CAP_REFRESH_INTERVAL))));
|
||||
|
||||
if (shouldUpdateSharedCache || cachedCoinMarketCapValues == null) {
|
||||
final Map<String, BigDecimal> conversionRatesFromCoinMarketCap = new HashMap<>(currencies.size());
|
||||
|
||||
for (final String currency : currencies) {
|
||||
conversionRatesFromCoinMarketCap.put(currency, coinMarketCapClient.getSpotPrice(currency, "USD"));
|
||||
}
|
||||
|
||||
this.cachedFtxValues = cachedFtxValues;
|
||||
this.ftxUpdatedTimestamp = System.currentTimeMillis();
|
||||
cachedCoinMarketCapValues = conversionRatesFromCoinMarketCap;
|
||||
|
||||
if (shouldUpdateSharedCache) {
|
||||
cacheCluster.useCluster(connection -> {
|
||||
final Map<String, String> sharedCoinMarketCapValues = new HashMap<>();
|
||||
|
||||
cachedCoinMarketCapValues.forEach((currency, conversionRate) ->
|
||||
sharedCoinMarketCapValues.put(currency, conversionRate.toString()));
|
||||
|
||||
connection.sync().hset(COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY, sharedCoinMarketCapValues);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
List<CurrencyConversionEntity> entities = new LinkedList<>();
|
||||
|
||||
for (Map.Entry<String, BigDecimal> currency : cachedFtxValues.entrySet()) {
|
||||
for (Map.Entry<String, BigDecimal> currency : cachedCoinMarketCapValues.entrySet()) {
|
||||
BigDecimal usdValue = stripTrailingZerosAfterDecimal(currency.getValue());
|
||||
|
||||
Map<String, BigDecimal> values = new HashMap<>();
|
||||
@@ -101,8 +147,7 @@ public class CurrencyConversionManager implements Managed {
|
||||
entities.add(new CurrencyConversionEntity(currency.getKey(), values));
|
||||
}
|
||||
|
||||
|
||||
this.cached.set(new CurrencyConversionEntityList(entities, ftxUpdatedTimestamp));
|
||||
this.cached.set(new CurrencyConversionEntityList(entities, clock.millis()));
|
||||
}
|
||||
|
||||
private BigDecimal stripTrailingZerosAfterDecimal(BigDecimal bigDecimal) {
|
||||
@@ -113,15 +158,4 @@ public class CurrencyConversionManager implements Managed {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void setFixerUpdatedTimestamp(long timestamp) {
|
||||
this.fixerUpdatedTimestamp = timestamp;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void setFtxUpdatedTimestamp(long timestamp) {
|
||||
this.ftxUpdatedTimestamp = timestamp;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.currency;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
public class FtxClient {
|
||||
|
||||
private final HttpClient client;
|
||||
|
||||
public FtxClient(HttpClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public BigDecimal getSpotPrice(String currency, String base) throws FtxException{
|
||||
try {
|
||||
URI uri = URI.create("https://ftx.com/api/markets/" + currency + "/" + base);
|
||||
|
||||
HttpResponse<String> response = client.send(HttpRequest.newBuilder()
|
||||
.GET()
|
||||
.uri(uri)
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
throw new FtxException("Bad response: " + response.statusCode() + " " + response.toString());
|
||||
}
|
||||
|
||||
FtxResponse parsedResponse = SystemMapper.getMapper().readValue(response.body(), FtxResponse.class);
|
||||
|
||||
return parsedResponse.result.price;
|
||||
|
||||
} catch (IOException | InterruptedException e) {
|
||||
throw new FtxException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class FtxResponse {
|
||||
|
||||
@JsonProperty
|
||||
private FtxResult result;
|
||||
|
||||
}
|
||||
|
||||
private static class FtxResult {
|
||||
|
||||
@JsonProperty
|
||||
private BigDecimal price;
|
||||
|
||||
}
|
||||
|
||||
public static class FtxException extends IOException {
|
||||
public FtxException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public FtxException(Exception exception) {
|
||||
super(exception);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+21
-9
@@ -13,6 +13,8 @@ import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.Timer;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.LettuceFutures;
|
||||
import io.lettuce.core.RedisFuture;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
@@ -21,6 +23,7 @@ import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
@@ -178,16 +181,25 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
List.of(managerId, String.valueOf(PRESENCE_EXPIRATION_SECONDS)));
|
||||
}
|
||||
|
||||
public void disconnectAllPresences(final UUID accountUuid, final List<Long> deviceIds) {
|
||||
|
||||
List<String> presenceKeys = new ArrayList<>();
|
||||
deviceIds.forEach(deviceId -> {
|
||||
String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
if (isLocallyPresent(accountUuid, deviceId)) {
|
||||
displacePresence(presenceKey, false);
|
||||
}
|
||||
presenceKeys.add(presenceKey);
|
||||
});
|
||||
|
||||
presenceCluster.useCluster(connection -> {
|
||||
List<RedisFuture<Long>> futures = presenceKeys.stream().map(key -> connection.async().del(key)).toList();
|
||||
LettuceFutures.awaitAll(connection.getTimeout(), futures.toArray(new RedisFuture[0]));
|
||||
});
|
||||
}
|
||||
|
||||
public void disconnectPresence(final UUID accountUuid, final long deviceId) {
|
||||
final String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
if (isLocallyPresent(accountUuid, deviceId)) {
|
||||
displacePresence(presenceKey, false);
|
||||
}
|
||||
|
||||
// If connected locally, we still need to clean up the presence key.
|
||||
// If connected remotely, the other server will get a keyspace message and handle the disconnect
|
||||
presenceCluster.useCluster(connection -> connection.sync().del(presenceKey));
|
||||
disconnectAllPresences(accountUuid, List.of(deviceId));
|
||||
}
|
||||
|
||||
private void displacePresence(final String presenceKey, final boolean connectedElsewhere) {
|
||||
|
||||
@@ -8,14 +8,11 @@ package org.whispersystems.textsecuregcm.push;
|
||||
import com.codahale.metrics.InstrumentedExecutorService;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.NoSuchUserException;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
@@ -37,34 +34,41 @@ public class ReceiptSender {
|
||||
MetricsUtil.name(ReceiptSender.class, "executor"));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> sendReceipt(UUID sourceUuid, long sourceDeviceId, UUID destinationUuid, long messageId)
|
||||
throws NoSuchUserException {
|
||||
public void sendReceipt(UUID sourceUuid, long sourceDeviceId, UUID destinationUuid, long messageId) {
|
||||
if (sourceUuid.equals(destinationUuid)) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
return;
|
||||
}
|
||||
|
||||
final Account destinationAccount = accountManager.getByAccountIdentifier(destinationUuid)
|
||||
.orElseThrow(() -> new NoSuchUserException(destinationUuid));
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
accountManager.getByAccountIdentifier(destinationUuid).ifPresentOrElse(
|
||||
destinationAccount -> {
|
||||
final Envelope.Builder message = Envelope.newBuilder()
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setSourceUuid(sourceUuid.toString())
|
||||
.setSourceDevice((int) sourceDeviceId)
|
||||
.setDestinationUuid(destinationUuid.toString())
|
||||
.setTimestamp(messageId)
|
||||
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT)
|
||||
.setUrgent(false);
|
||||
|
||||
final Envelope.Builder message = Envelope.newBuilder()
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setSourceUuid(sourceUuid.toString())
|
||||
.setSourceDevice((int) sourceDeviceId)
|
||||
.setDestinationUuid(destinationUuid.toString())
|
||||
.setTimestamp(messageId)
|
||||
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT)
|
||||
.setUrgent(false);
|
||||
for (final Device destinationDevice : destinationAccount.getDevices()) {
|
||||
try {
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
|
||||
} catch (final NotPushRegisteredException e) {
|
||||
logger.debug("User no longer push registered for delivery receipt: {}", e.getMessage());
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
}
|
||||
},
|
||||
() -> logger.info("No longer registered: {}", destinationUuid)
|
||||
);
|
||||
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
for (final Device destinationDevice : destinationAccount.getDevices()) {
|
||||
try {
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
|
||||
} catch (final NotPushRegisteredException e) {
|
||||
logger.info("User no longer push registered for delivery receipt: " + e.getMessage());
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
// this exception is most likely a Dynamo timeout or a Redis timeout/circuit breaker
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
}, executor);
|
||||
});
|
||||
}
|
||||
}
|
||||
+25
-21
@@ -53,35 +53,39 @@ public class FaultTolerantRedisCluster {
|
||||
private final Retry retry;
|
||||
|
||||
public FaultTolerantRedisCluster(final String name, final RedisClusterConfiguration clusterConfiguration, final ClientResources clientResources) {
|
||||
this(name,
|
||||
RedisClusterClient.create(clientResources, clusterConfiguration.getConfigurationUri()),
|
||||
clusterConfiguration.getTimeout(),
|
||||
clusterConfiguration.getCircuitBreakerConfiguration(),
|
||||
clusterConfiguration.getRetryConfiguration());
|
||||
this(name,
|
||||
RedisClusterClient.create(clientResources, clusterConfiguration.getConfigurationUri()),
|
||||
clusterConfiguration.getTimeout(),
|
||||
clusterConfiguration.getCircuitBreakerConfiguration(),
|
||||
clusterConfiguration.getRetryConfiguration());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FaultTolerantRedisCluster(final String name, final RedisClusterClient clusterClient, final Duration commandTimeout, final CircuitBreakerConfiguration circuitBreakerConfiguration, final RetryConfiguration retryConfiguration) {
|
||||
this.name = name;
|
||||
this.name = name;
|
||||
|
||||
this.clusterClient = clusterClient;
|
||||
this.clusterClient.setDefaultTimeout(commandTimeout);
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
.disconnectedBehavior(DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
.enableAllAdaptiveRefreshTriggers()
|
||||
.build())
|
||||
.build());
|
||||
this.clusterClient = clusterClient;
|
||||
this.clusterClient.setDefaultTimeout(commandTimeout);
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
.disconnectedBehavior(DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
.enableAllAdaptiveRefreshTriggers()
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
this.circuitBreaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
this.retry = Retry.of(name + "-retry", retryConfiguration.toRetryConfigBuilder().retryOnException(exception -> exception instanceof RedisCommandTimeoutException).build());
|
||||
this.circuitBreaker = CircuitBreaker.of(name + "-breaker", circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
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(SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME), circuitBreaker,
|
||||
FaultTolerantRedisCluster.class);
|
||||
CircuitBreakerUtil.registerMetrics(SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME), retry,
|
||||
FaultTolerantRedisCluster.class);
|
||||
}
|
||||
|
||||
void shutdown() {
|
||||
|
||||
@@ -85,6 +85,7 @@ public class Account {
|
||||
@JsonIgnore
|
||||
private boolean canonicallyDiscoverable;
|
||||
|
||||
|
||||
public UUID getUuid() {
|
||||
// this is the one method that may be called on a stale account
|
||||
return uuid;
|
||||
@@ -304,16 +305,10 @@ public class Account {
|
||||
|
||||
public long getLastSeen() {
|
||||
requireNotStale();
|
||||
|
||||
long lastSeen = 0;
|
||||
|
||||
for (Device device : devices) {
|
||||
if (device.getLastSeen() > lastSeen) {
|
||||
lastSeen = device.getLastSeen();
|
||||
}
|
||||
}
|
||||
|
||||
return lastSeen;
|
||||
return devices.stream()
|
||||
.map(Device::getLastSeen)
|
||||
.max(Long::compare)
|
||||
.orElse(0L);
|
||||
}
|
||||
|
||||
public Optional<String> getCurrentProfileVersion() {
|
||||
@@ -344,7 +339,6 @@ public class Account {
|
||||
|
||||
public void addBadge(Clock clock, AccountBadge badge) {
|
||||
requireNotStale();
|
||||
|
||||
boolean added = false;
|
||||
for (int i = 0; i < badges.size(); i++) {
|
||||
AccountBadge badgeInList = badges.get(i);
|
||||
@@ -478,6 +472,31 @@ public class Account {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Have all this account's devices been manually locked?
|
||||
*
|
||||
* @see Device#hasLockedCredentials
|
||||
*
|
||||
* @return true if all the account's devices were locked, false otherwise.
|
||||
*/
|
||||
public boolean hasLockedCredentials() {
|
||||
return devices.stream().allMatch(Device::hasLockedCredentials);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock account by invalidating authentication tokens.
|
||||
*
|
||||
* We only want to do this in cases where there is a potential conflict between the
|
||||
* phone number holder and the registration lock holder. In that case, locking the
|
||||
* account will ensure that either the registration lock holder proves ownership
|
||||
* of the phone number, or after 7 days the phone number holder can register a new
|
||||
* account.
|
||||
*/
|
||||
public void lockAuthenticationCredentials() {
|
||||
devices.forEach(Device::lockAuthenticationCredentials);
|
||||
}
|
||||
|
||||
boolean isStale() {
|
||||
return stale;
|
||||
}
|
||||
|
||||
@@ -149,6 +149,33 @@ public class Device {
|
||||
this.salt = credentials.getSalt();
|
||||
}
|
||||
|
||||
/**
|
||||
* Has this device been manually locked?
|
||||
*
|
||||
* We lock a device by prepending "!" to its token.
|
||||
* This character cannot normally appear in valid tokens.
|
||||
*
|
||||
* @return true if the credential was locked, false otherwise.
|
||||
*/
|
||||
public boolean hasLockedCredentials() {
|
||||
AuthenticationCredentials auth = getAuthenticationCredentials();
|
||||
return auth.getHashedAuthenticationToken().startsWith("!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock device by invalidating authentication tokens.
|
||||
*
|
||||
* This should only be used from Account::lockAuthenticationCredentials.
|
||||
*
|
||||
* See that method for more information.
|
||||
*/
|
||||
public void lockAuthenticationCredentials() {
|
||||
AuthenticationCredentials oldAuth = getAuthenticationCredentials();
|
||||
String token = "!" + oldAuth.getHashedAuthenticationToken();
|
||||
String salt = oldAuth.getSalt();
|
||||
setAuthenticationCredentials(new AuthenticationCredentials(token, salt));
|
||||
}
|
||||
|
||||
public AuthenticationCredentials getAuthenticationCredentials() {
|
||||
return new AuthenticationCredentials(authToken, salt);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
@@ -92,6 +93,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
|
||||
|
||||
private static final String GET_FLUX_NAME = MetricsUtil.name(MessagesCache.class, "get");
|
||||
private static final int PAGE_SIZE = 100;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesCache.class);
|
||||
@@ -220,7 +222,8 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
|
||||
discardStaleEphemeralMessages(destinationUuid, destinationDevice, staleEphemeralMessages);
|
||||
|
||||
return messagesToPublish;
|
||||
return messagesToPublish.name(GET_FLUX_NAME)
|
||||
.metrics();
|
||||
}
|
||||
|
||||
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
|
||||
@@ -384,12 +387,13 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
public void removeMessageAvailabilityListener(final MessageAvailabilityListener listener) {
|
||||
@Nullable final String queueName = queueNamesByMessageListener.remove(listener);
|
||||
@Nullable final String queueName = queueNamesByMessageListener.get(listener);
|
||||
|
||||
if (queueName != null) {
|
||||
unsubscribeFromKeyspaceNotifications(queueName);
|
||||
|
||||
synchronized (messageListenersByQueueName) {
|
||||
queueNamesByMessageListener.remove(listener);
|
||||
messageListenersByQueueName.remove(queueName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,8 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -60,6 +62,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
private final String tableName;
|
||||
private final Duration timeToLive;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Scheduler messageDeletionScheduler;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
|
||||
|
||||
@@ -72,6 +75,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
this.timeToLive = timeToLive;
|
||||
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.messageDeletionScheduler = Schedulers.fromExecutor(messageDeletionExecutor);
|
||||
}
|
||||
|
||||
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
@@ -176,6 +180,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
return null;
|
||||
})
|
||||
.map(Optional::ofNullable)
|
||||
.subscribeOn(messageDeletionScheduler)
|
||||
.last(Optional.empty()) // if the flux is empty, last() will throw without a default
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
+26
-11
@@ -9,12 +9,12 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -23,13 +23,16 @@ import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
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.publisher.Flux;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
public class MessagesManager {
|
||||
|
||||
private static final int RESULT_SET_CHUNK_SIZE = 100;
|
||||
final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = MetricsUtil.name(MessagesManager.class, "getMessagesForDevice");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesManager.class);
|
||||
|
||||
@@ -42,14 +45,17 @@ public class MessagesManager {
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final ReportMessageManager reportMessageManager) {
|
||||
final ReportMessageManager reportMessageManager,
|
||||
final ExecutorService messageDeletionExecutor) {
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
}
|
||||
|
||||
public void insert(UUID destinationUuid, long destinationDevice, Envelope message) {
|
||||
@@ -69,13 +75,20 @@ public class MessagesManager {
|
||||
public Pair<List<Envelope>, Boolean> getMessagesForDevice(UUID destinationUuid, long destinationDevice,
|
||||
boolean cachedMessagesOnly) {
|
||||
|
||||
final List<Envelope> envelopes = Flux.from(
|
||||
getMessagesForDevice(destinationUuid, destinationDevice, RESULT_SET_CHUNK_SIZE, cachedMessagesOnly))
|
||||
.take(RESULT_SET_CHUNK_SIZE, true)
|
||||
.collectList()
|
||||
.blockOptional().orElse(Collections.emptyList());
|
||||
try {
|
||||
final List<Envelope> envelopes = Flux.from(
|
||||
getMessagesForDevice(destinationUuid, destinationDevice, RESULT_SET_CHUNK_SIZE, cachedMessagesOnly))
|
||||
.take(RESULT_SET_CHUNK_SIZE, true)
|
||||
.collectList()
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.toFuture()
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
|
||||
return new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE);
|
||||
}
|
||||
|
||||
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, long destinationDevice,
|
||||
@@ -91,7 +104,9 @@ public class MessagesManager {
|
||||
cachedMessagesOnly ? Flux.empty() : messagesDynamoDb.load(destinationUuid, destinationDevice, limit);
|
||||
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice);
|
||||
|
||||
return Flux.concat(dynamoPublisher, cachePublisher);
|
||||
return Flux.concat(dynamoPublisher, cachePublisher)
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.metrics();
|
||||
}
|
||||
|
||||
public void clear(UUID destinationUuid) {
|
||||
@@ -107,7 +122,7 @@ public class MessagesManager {
|
||||
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, long destinationDeviceId, UUID guid,
|
||||
@Nullable Long serverTimestamp) {
|
||||
return messagesCache.remove(destinationUuid, destinationDeviceId, guid)
|
||||
.thenCompose(removed -> {
|
||||
.thenComposeAsync(removed -> {
|
||||
|
||||
if (removed.isPresent()) {
|
||||
cacheHitByGuidMeter.mark();
|
||||
@@ -122,7 +137,7 @@ public class MessagesManager {
|
||||
return messagesDynamoDb.deleteMessage(destinationUuid, destinationDeviceId, guid, serverTimestamp);
|
||||
}
|
||||
|
||||
});
|
||||
}, messageDeletionExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
@@ -249,6 +249,7 @@ public class StripeManager implements SubscriptionProcessorManager {
|
||||
// not prorated
|
||||
.setProrationBehavior(ProrationBehavior.NONE)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
|
||||
.setOffSession(true)
|
||||
.addAllItem(items)
|
||||
.build();
|
||||
try {
|
||||
|
||||
@@ -101,6 +101,10 @@ public class Util {
|
||||
return param == null || param.length() == 0;
|
||||
}
|
||||
|
||||
public static boolean nonEmpty(String param) {
|
||||
return !isEmpty(param);
|
||||
}
|
||||
|
||||
public static byte[] truncate(byte[] element, int length) {
|
||||
byte[] result = new byte[length];
|
||||
System.arraycopy(element, 0, result, 0, result.length);
|
||||
@@ -138,15 +142,11 @@ public class Util {
|
||||
return parts;
|
||||
}
|
||||
|
||||
public static int toIntExact(long value) {
|
||||
if ((int) value != value) {
|
||||
throw new ArithmeticException("integer overflow");
|
||||
}
|
||||
return (int) value;
|
||||
}
|
||||
public static final long DAY_IN_MILLIS = 86400000L;
|
||||
public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
|
||||
|
||||
public static int currentDaysSinceEpoch(@Nonnull Clock clock) {
|
||||
return toIntExact(clock.millis() / 1000 / 60/ 60 / 24);
|
||||
return Math.toIntExact(clock.millis() / DAY_IN_MILLIS);
|
||||
}
|
||||
|
||||
public static void sleep(long i) {
|
||||
@@ -180,12 +180,12 @@ public class Util {
|
||||
}
|
||||
|
||||
public static long todayInMillis(Clock clock) {
|
||||
return TimeUnit.DAYS.toMillis(TimeUnit.MILLISECONDS.toDays(clock.instant().toEpochMilli()));
|
||||
return TimeUnit.DAYS.toMillis(TimeUnit.MILLISECONDS.toDays(clock.millis()));
|
||||
}
|
||||
|
||||
public static long todayInMillisGivenOffsetFromNow(Clock clock, Duration offset) {
|
||||
final long currentTimeSeconds = offset.addTo(clock.instant()).getLong(ChronoField.INSTANT_SECONDS);
|
||||
return TimeUnit.DAYS.toMillis(TimeUnit.SECONDS.toDays(currentTimeSeconds));
|
||||
final long ms = offset.toMillis() + clock.millis();
|
||||
return TimeUnit.DAYS.toMillis(TimeUnit.MILLISECONDS.toDays(ms));
|
||||
}
|
||||
|
||||
public static Optional<String> findBestLocale(List<LanguageRange> priorityList, Collection<String> supportedLocales) {
|
||||
|
||||
+28
-8
@@ -26,21 +26,21 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.NoSuchUserException;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.DisplacedPresenceListener;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
@@ -83,8 +83,13 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
"clientNonSuccessResponse");
|
||||
private static final String CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class,
|
||||
"messageAvailableAfterClientClosed");
|
||||
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(WebSocketConnection.class,
|
||||
"sendMessages");
|
||||
private static final String SEND_MESSAGE_ERROR_COUNTER = MetricsUtil.name(WebSocketConnection.class,
|
||||
"sendMessageError");
|
||||
private static final String STATUS_CODE_TAG = "status";
|
||||
private static final String STATUS_MESSAGE_TAG = "message";
|
||||
private static final String ERROR_TYPE_TAG = "errorType";
|
||||
private static final String REACTIVE_TAG = "reactive";
|
||||
|
||||
private static final long SLOW_DRAIN_THRESHOLD = 10_000;
|
||||
@@ -124,7 +129,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
|
||||
private final Random random = new Random();
|
||||
private final boolean useReactive;
|
||||
private Scheduler reactiveScheduler;
|
||||
private final Scheduler reactiveScheduler;
|
||||
|
||||
private enum StoredMessageState {
|
||||
EMPTY,
|
||||
@@ -279,12 +284,10 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
receiptSender.sendReceipt(UUID.fromString(message.getDestinationUuid()),
|
||||
auth.getAuthenticatedDevice().getId(), UUID.fromString(message.getSourceUuid()),
|
||||
message.getTimestamp());
|
||||
} catch (NoSuchUserException e) {
|
||||
logger.info("No longer registered: {}", e.getMessage());
|
||||
} catch (WebApplicationException e) {
|
||||
logger.warn("Bad federated response for receipt: {}", e.getResponse().getStatus());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("Could not parse UUID: {}", message.getSourceUuid());
|
||||
} catch (Exception e) {
|
||||
logger.warn("Failed to send receipt", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,9 +426,26 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
messagesManager.getMessagesForDeviceReactive(auth.getAccount().getUuid(), device.getId(), cachedMessagesOnly);
|
||||
|
||||
final Disposable subscription = Flux.from(messages)
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.metrics()
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
.flatMapSequential(envelope ->
|
||||
Mono.fromFuture(sendMessage(envelope).orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS)))
|
||||
Mono.fromFuture(sendMessage(envelope)
|
||||
.orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS))
|
||||
.doOnError(e -> {
|
||||
final String errorType;
|
||||
if (!(e instanceof TimeoutException)) {
|
||||
// TimeoutExceptions are expected, no need to log
|
||||
logger.warn("Send message failed", e);
|
||||
errorType = "other";
|
||||
} else {
|
||||
errorType = "timeout";
|
||||
}
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of(ERROR_TYPE_TAG, errorType));
|
||||
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, tags).increment();
|
||||
}))
|
||||
.doOnError(queueCleared::completeExceptionally)
|
||||
.doOnComplete(() -> queueCleared.complete(null))
|
||||
.subscribeOn(reactiveScheduler)
|
||||
|
||||
+1
-1
@@ -186,7 +186,7 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager);
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
|
||||
+2
-2
@@ -186,9 +186,9 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager);
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
|
||||
+2
-2
@@ -187,9 +187,9 @@ public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperSer
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager);
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
DeletedAccountsManager deletedAccountsManager = new DeletedAccountsManager(deletedAccounts,
|
||||
deletedAccountsLockDynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
|
||||
+67
-25
@@ -6,12 +6,14 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.anyLong;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.eq;
|
||||
@@ -21,7 +23,6 @@ import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -33,14 +34,12 @@ import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -48,6 +47,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
@@ -93,6 +93,7 @@ import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMa
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberResponse;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotification;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient;
|
||||
@@ -112,6 +113,7 @@ import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.Hex;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class AccountControllerTest {
|
||||
@@ -144,26 +146,28 @@ class AccountControllerTest {
|
||||
private static final String TEST_NUMBER = "+14151111113";
|
||||
|
||||
private static StoredVerificationCodeManager pendingAccountsManager = mock(StoredVerificationCodeManager.class);
|
||||
private static AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private static AbusiveHostRules abusiveHostRules = mock(AbusiveHostRules.class);
|
||||
private static RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter pinLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter smsVoiceIpLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter smsVoicePrefixLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter autoBlockLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter usernameSetLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter usernameReserveLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter usernameLookupLimiter = mock(RateLimiter.class);
|
||||
private static AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private static AbusiveHostRules abusiveHostRules = mock(AbusiveHostRules.class);
|
||||
private static RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter pinLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter smsVoiceIpLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter smsVoicePrefixLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter autoBlockLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter usernameSetLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter usernameReserveLimiter = mock(RateLimiter.class);
|
||||
private static RateLimiter usernameLookupLimiter = mock(RateLimiter.class);
|
||||
private static RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
|
||||
private static TurnTokenGenerator turnTokenGenerator = mock(TurnTokenGenerator.class);
|
||||
private static Account senderPinAccount = mock(Account.class);
|
||||
private static Account senderRegLockAccount = mock(Account.class);
|
||||
private static Account senderHasStorage = mock(Account.class);
|
||||
private static Account senderTransfer = mock(Account.class);
|
||||
private static RecaptchaClient recaptchaClient = mock(RecaptchaClient.class);
|
||||
private static TurnTokenGenerator turnTokenGenerator = mock(TurnTokenGenerator.class);
|
||||
private static Account senderPinAccount = mock(Account.class);
|
||||
private static Account senderRegLockAccount = mock(Account.class);
|
||||
private static Account senderHasStorage = mock(Account.class);
|
||||
private static Account senderTransfer = mock(Account.class);
|
||||
private static RecaptchaClient recaptchaClient = mock(RecaptchaClient.class);
|
||||
private static PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
private static ChangeNumberManager changeNumberManager = mock(ChangeNumberManager.class);
|
||||
private static ChangeNumberManager changeNumberManager = mock(ChangeNumberManager.class);
|
||||
private static ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
private static TestClock testClock = TestClock.now();
|
||||
|
||||
private static DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
|
||||
@@ -192,7 +196,9 @@ class AccountControllerTest {
|
||||
recaptchaClient,
|
||||
pushNotificationManager,
|
||||
changeNumberManager,
|
||||
storageCredentialGenerator))
|
||||
storageCredentialGenerator,
|
||||
clientPresenceManager,
|
||||
testClock))
|
||||
.build();
|
||||
|
||||
|
||||
@@ -338,7 +344,8 @@ class AccountControllerTest {
|
||||
senderTransfer,
|
||||
recaptchaClient,
|
||||
pushNotificationManager,
|
||||
changeNumberManager);
|
||||
changeNumberManager,
|
||||
clientPresenceManager);
|
||||
|
||||
clearInvocations(AuthHelper.DISABLED_DEVICE);
|
||||
}
|
||||
@@ -1061,6 +1068,8 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(423);
|
||||
|
||||
// verify(senderRegLockAccount).lockAuthenticationCredentials();
|
||||
// verify(clientPresenceManager, times(1)).disconnectAllPresences(eq(SENDER_REG_LOCK_UUID), any());
|
||||
verify(pinLimiter).validate(eq(SENDER_REG_LOCK));
|
||||
}
|
||||
|
||||
@@ -1083,6 +1092,8 @@ class AccountControllerTest {
|
||||
assertThat(failure.getBackupCredentials().getPassword().startsWith(SENDER_REG_LOCK_UUID.toString())).isTrue();
|
||||
assertThat(failure.getTimeRemaining()).isGreaterThan(0);
|
||||
|
||||
// verify(senderRegLockAccount).lockAuthenticationCredentials();
|
||||
// verify(clientPresenceManager, atLeastOnce()).disconnectAllPresences(eq(SENDER_REG_LOCK_UUID), any());
|
||||
verifyNoInteractions(pinLimiter);
|
||||
}
|
||||
|
||||
@@ -1309,9 +1320,10 @@ class AccountControllerTest {
|
||||
final StoredRegistrationLock existingRegistrationLock = mock(StoredRegistrationLock.class);
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock()).thenReturn(true);
|
||||
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
final Account existingAccount = mock(Account.class);
|
||||
when(existingAccount.getNumber()).thenReturn(number);
|
||||
when(existingAccount.getUuid()).thenReturn(UUID.randomUUID());
|
||||
when(existingAccount.getUuid()).thenReturn(existingUuid);
|
||||
when(existingAccount.getRegistrationLock()).thenReturn(existingRegistrationLock);
|
||||
|
||||
when(accountsManager.getByE164(number)).thenReturn(Optional.of(existingAccount));
|
||||
@@ -1325,6 +1337,9 @@ class AccountControllerTest {
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(423);
|
||||
|
||||
// verify(existingAccount).lockAuthenticationCredentials();
|
||||
// verify(clientPresenceManager, atLeastOnce()).disconnectAllPresences(eq(existingUuid), any());
|
||||
verify(changeNumberManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@@ -1345,9 +1360,10 @@ class AccountControllerTest {
|
||||
when(existingRegistrationLock.requiresClientRegistrationLock()).thenReturn(true);
|
||||
when(existingRegistrationLock.verify(anyString())).thenReturn(false);
|
||||
|
||||
UUID existingUuid = UUID.randomUUID();
|
||||
final Account existingAccount = mock(Account.class);
|
||||
when(existingAccount.getNumber()).thenReturn(number);
|
||||
when(existingAccount.getUuid()).thenReturn(UUID.randomUUID());
|
||||
when(existingAccount.getUuid()).thenReturn(existingUuid);
|
||||
when(existingAccount.getRegistrationLock()).thenReturn(existingRegistrationLock);
|
||||
|
||||
when(accountsManager.getByE164(number)).thenReturn(Optional.of(existingAccount));
|
||||
@@ -1361,6 +1377,9 @@ class AccountControllerTest {
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(423);
|
||||
|
||||
// verify(existingAccount).lockAuthenticationCredentials();
|
||||
// verify(clientPresenceManager, atLeastOnce()).disconnectAllPresences(eq(existingUuid), any());
|
||||
verify(changeNumberManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@@ -1397,6 +1416,8 @@ class AccountControllerTest {
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
verify(senderRegLockAccount, never()).lockAuthenticationCredentials();
|
||||
verify(clientPresenceManager, never()).disconnectAllPresences(eq(SENDER_REG_LOCK_UUID), any());
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@@ -1940,4 +1961,25 @@ class AccountControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(413);
|
||||
assertThat(response.getHeaderString("Retry-After")).isEqualTo(String.valueOf(Duration.ofSeconds(13).toSeconds()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void pushTokensMatch(@Nullable final String pushChallenge, @Nullable final StoredVerificationCode storedVerificationCode, final boolean expectMatch) {
|
||||
final String number = "+18005550123";
|
||||
final Optional<String> maybePushChallenge = Optional.ofNullable(pushChallenge);
|
||||
final Optional<StoredVerificationCode> maybeStoredVerificationCode = Optional.ofNullable(storedVerificationCode);
|
||||
|
||||
assertEquals(expectMatch, AccountController.pushChallengeMatches(number, maybePushChallenge, maybeStoredVerificationCode));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> pushTokensMatch() {
|
||||
return Stream.of(
|
||||
Arguments.of(null, null, false),
|
||||
Arguments.of("123456", null, false),
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, null, null, null), false),
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, "123456", null, null), false),
|
||||
Arguments.of("654321", new StoredVerificationCode(null, 0, "123456", null, null), false),
|
||||
Arguments.of("123456", new StoredVerificationCode(null, 0, "123456", null, null), true)
|
||||
);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package org.whispersystems.textsecuregcm.currency;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CoinMarketCapClientTest {
|
||||
|
||||
private static final String RESPONSE_JSON = """
|
||||
{
|
||||
"status": {
|
||||
"timestamp": "2022-11-09T17:15:06.356Z",
|
||||
"error_code": 0,
|
||||
"error_message": null,
|
||||
"elapsed": 41,
|
||||
"credit_count": 1,
|
||||
"notice": null
|
||||
},
|
||||
"data": {
|
||||
"id": 7878,
|
||||
"symbol": "MOB",
|
||||
"name": "MobileCoin",
|
||||
"amount": 1,
|
||||
"last_updated": "2022-11-09T17:14:00.000Z",
|
||||
"quote": {
|
||||
"USD": {
|
||||
"price": 0.6625319895827952,
|
||||
"last_updated": "2022-11-09T17:14:00.000Z"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@Test
|
||||
void parseResponse() throws JsonProcessingException {
|
||||
final CoinMarketCapClient.CoinMarketCapResponse parsedResponse = CoinMarketCapClient.parseResponse(RESPONSE_JSON);
|
||||
|
||||
assertEquals(7878, parsedResponse.priceConversionResponse().id());
|
||||
assertEquals("MOB", parsedResponse.priceConversionResponse().symbol());
|
||||
|
||||
final Map<String, CoinMarketCapClient.PriceConversionQuote> quote =
|
||||
parsedResponse.priceConversionResponse().quote();
|
||||
|
||||
assertEquals(1, quote.size());
|
||||
assertEquals(new BigDecimal("0.6625319895827952"), quote.get("USD").price());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractConversionRate() throws IOException {
|
||||
final CoinMarketCapClient.CoinMarketCapResponse parsedResponse = CoinMarketCapClient.parseResponse(RESPONSE_JSON);
|
||||
|
||||
assertEquals(new BigDecimal("0.6625319895827952"), CoinMarketCapClient.extractConversionRate(parsedResponse, "USD"));
|
||||
assertThrows(IOException.class, () -> CoinMarketCapClient.extractConversionRate(parsedResponse, "CAD"));
|
||||
}
|
||||
}
|
||||
+49
-25
@@ -7,27 +7,35 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
|
||||
class CurrencyConversionManagerTest {
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
@Test
|
||||
void testCurrencyCalculations() throws IOException {
|
||||
FixerClient fixerClient = mock(FixerClient.class);
|
||||
FtxClient ftxClient = mock(FtxClient.class);
|
||||
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
|
||||
"EUR", new BigDecimal("0.822876"),
|
||||
"FJD", new BigDecimal("2.0577"),
|
||||
"FKP", new BigDecimal("0.743446")
|
||||
));
|
||||
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, ftxClient, List.of("FOO"));
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
List.of("FOO"), Clock.systemUTC());
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
@@ -45,9 +53,9 @@ class CurrencyConversionManagerTest {
|
||||
@Test
|
||||
void testCurrencyCalculations_noTrailingZeros() throws IOException {
|
||||
FixerClient fixerClient = mock(FixerClient.class);
|
||||
FtxClient ftxClient = mock(FtxClient.class);
|
||||
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("1.00000"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("1.00000"));
|
||||
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
|
||||
"EUR", new BigDecimal("0.200000"),
|
||||
"FJD", new BigDecimal("3.00000"),
|
||||
@@ -55,7 +63,8 @@ class CurrencyConversionManagerTest {
|
||||
"CAD", new BigDecimal("700.000")
|
||||
));
|
||||
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, ftxClient, List.of("FOO"));
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
List.of("FOO"), Clock.systemUTC());
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
@@ -74,16 +83,17 @@ class CurrencyConversionManagerTest {
|
||||
@Test
|
||||
void testCurrencyCalculations_accuracy() throws IOException {
|
||||
FixerClient fixerClient = mock(FixerClient.class);
|
||||
FtxClient ftxClient = mock(FtxClient.class);
|
||||
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("0.999999"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("0.999999"));
|
||||
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
|
||||
"EUR", new BigDecimal("1.000001"),
|
||||
"FJD", new BigDecimal("0.000001"),
|
||||
"FKP", new BigDecimal("1")
|
||||
));
|
||||
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, ftxClient, List.of("FOO"));
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
List.of("FOO"), Clock.systemUTC());
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
@@ -102,20 +112,21 @@ class CurrencyConversionManagerTest {
|
||||
@Test
|
||||
void testCurrencyCalculationsTimeoutNoRun() throws IOException {
|
||||
FixerClient fixerClient = mock(FixerClient.class);
|
||||
FtxClient ftxClient = mock(FtxClient.class);
|
||||
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
|
||||
"EUR", new BigDecimal("0.822876"),
|
||||
"FJD", new BigDecimal("2.0577"),
|
||||
"FKP", new BigDecimal("0.743446")
|
||||
));
|
||||
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, ftxClient, List.of("FOO"));
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
List.of("FOO"), Clock.systemUTC());
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
@@ -131,23 +142,26 @@ class CurrencyConversionManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCurrencyCalculationsFtxTimeoutWithRun() throws IOException {
|
||||
void testCurrencyCalculationsCoinMarketCapTimeoutWithRun() throws IOException {
|
||||
FixerClient fixerClient = mock(FixerClient.class);
|
||||
FtxClient ftxClient = mock(FtxClient.class);
|
||||
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
|
||||
"EUR", new BigDecimal("0.822876"),
|
||||
"FJD", new BigDecimal("2.0577"),
|
||||
"FKP", new BigDecimal("0.743446")
|
||||
));
|
||||
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, ftxClient, List.of("FOO"));
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
List.of("FOO"), Clock.systemUTC());
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
|
||||
manager.setFtxUpdatedTimestamp(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2) - TimeUnit.SECONDS.toMillis(1));
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().del(CurrencyConversionManager.COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY));
|
||||
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
CurrencyConversionEntityList conversions = manager.getCurrencyConversions().orElseThrow();
|
||||
@@ -165,27 +179,37 @@ class CurrencyConversionManagerTest {
|
||||
@Test
|
||||
void testCurrencyCalculationsFixerTimeoutWithRun() throws IOException {
|
||||
FixerClient fixerClient = mock(FixerClient.class);
|
||||
FtxClient ftxClient = mock(FtxClient.class);
|
||||
CoinMarketCapClient coinMarketCapClient = mock(CoinMarketCapClient.class);
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("2.35"));
|
||||
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
|
||||
"EUR", new BigDecimal("0.822876"),
|
||||
"FJD", new BigDecimal("2.0577"),
|
||||
"FKP", new BigDecimal("0.743446")
|
||||
));
|
||||
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, ftxClient, List.of("FOO"));
|
||||
final Instant currentTime = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
|
||||
final Clock clock = mock(Clock.class);
|
||||
when(clock.instant()).thenReturn(currentTime);
|
||||
when(clock.millis()).thenReturn(currentTime.toEpochMilli());
|
||||
|
||||
CurrencyConversionManager manager = new CurrencyConversionManager(fixerClient, coinMarketCapClient, REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
List.of("FOO"), clock);
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
when(ftxClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
|
||||
when(coinMarketCapClient.getSpotPrice(eq("FOO"), eq("USD"))).thenReturn(new BigDecimal("3.50"));
|
||||
when(fixerClient.getConversionsForBase(eq("USD"))).thenReturn(Map.of(
|
||||
"EUR", new BigDecimal("0.922876"),
|
||||
"FJD", new BigDecimal("2.0577"),
|
||||
"FKP", new BigDecimal("0.743446")
|
||||
));
|
||||
|
||||
manager.setFixerUpdatedTimestamp(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2) - TimeUnit.SECONDS.toMillis(1));
|
||||
final Instant afterFixerExpiration = currentTime.plus(CurrencyConversionManager.FIXER_REFRESH_INTERVAL).plusMillis(1);
|
||||
when(clock.instant()).thenReturn(afterFixerExpiration);
|
||||
when(clock.millis()).thenReturn(afterFixerExpiration.toEpochMilli());
|
||||
|
||||
manager.updateCacheIfNecessary();
|
||||
|
||||
CurrencyConversionEntityList conversions = manager.getCurrencyConversions().orElseThrow();
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.currency;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.jsonFixture;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandler;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class FtxClientTest {
|
||||
|
||||
@Test
|
||||
public void testGetSpotPrice() throws IOException, InterruptedException {
|
||||
HttpResponse<String> httpResponse = mock(HttpResponse.class);
|
||||
when(httpResponse.statusCode()).thenReturn(200);
|
||||
when(httpResponse.body()).thenReturn(jsonFixture("fixtures/ftx.res.json"));
|
||||
|
||||
HttpClient httpClient = mock(HttpClient.class);
|
||||
when(httpClient.send(any(HttpRequest.class), any(BodyHandler.class))).thenReturn(httpResponse);
|
||||
|
||||
FtxClient ftxClient = new FtxClient(httpClient);
|
||||
BigDecimal spotPrice = ftxClient.getSpotPrice("FOO", "BAR");
|
||||
assertThat(spotPrice).isEqualTo(new BigDecimal("0.8017"));
|
||||
}
|
||||
|
||||
}
|
||||
+15
-1
@@ -12,6 +12,7 @@ import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
@@ -37,6 +38,8 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
.writeCapacityUnits(20L)
|
||||
.build();
|
||||
|
||||
private static final AtomicBoolean libraryLoaded = new AtomicBoolean();
|
||||
|
||||
private DynamoDBProxyServer server;
|
||||
private int port;
|
||||
|
||||
@@ -77,6 +80,17 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
return new DynamoDbExtensionBuilder();
|
||||
}
|
||||
|
||||
private static void loadLibrary() {
|
||||
// to avoid noise in the logs from “library already loaded” warnings, we make sure we only set it once
|
||||
if (libraryLoaded.get()) {
|
||||
return;
|
||||
}
|
||||
if (libraryLoaded.compareAndSet(false, true)) {
|
||||
// if you see a library failed to load error, you need to run mvn test-compile at least once first
|
||||
SQLite.setLibraryPath("target/lib");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterEach(ExtensionContext context) {
|
||||
stopServer();
|
||||
@@ -135,7 +149,7 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
|
||||
// Even though we're using AWS SDK v2, Dynamo's local implementation's canonical location
|
||||
// is within v1 (https://github.com/aws/aws-sdk-java-v2/issues/982). This does support
|
||||
// v2 clients, though.
|
||||
SQLite.setLibraryPath("target/lib"); // if you see a library failed to load error, you need to run mvn test-compile at least once first
|
||||
loadLibrary();
|
||||
ServerSocket serverSocket = new ServerSocket(0);
|
||||
serverSocket.setReuseAddress(false);
|
||||
port = serverSocket.getLocalPort();
|
||||
|
||||
+2
-1
@@ -77,7 +77,8 @@ class MessagePersisterIntegrationTest {
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster(), Clock.systemUTC(), notificationExecutorService,
|
||||
messageDeletionExecutorService);
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class));
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY);
|
||||
|
||||
|
||||
+2
-1
@@ -12,6 +12,7 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
|
||||
@@ -22,7 +23,7 @@ class MessagesManagerTest {
|
||||
private final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
|
||||
|
||||
private final MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager);
|
||||
reportMessageManager, Executors.newSingleThreadExecutor());
|
||||
|
||||
@Test
|
||||
void insert() {
|
||||
|
||||
@@ -132,6 +132,7 @@ public class AccountsHelper {
|
||||
case "getRegistrationLock" -> when(updatedAccount.getRegistrationLock()).thenAnswer(stubbing);
|
||||
case "getIdentityKey" -> when(updatedAccount.getIdentityKey()).thenAnswer(stubbing);
|
||||
case "getBadges" -> when(updatedAccount.getBadges()).thenAnswer(stubbing);
|
||||
case "getLastSeen" -> when(updatedAccount.getLastSeen()).thenAnswer(stubbing);
|
||||
default -> throw new IllegalArgumentException("unsupported method: Account#" + stubbing.getInvocation().getMethod().getName());
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -122,7 +122,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
final boolean useReactive) {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
|
||||
new AuthenticatedAccount(() -> new Pair<>(account, device)),
|
||||
device,
|
||||
webSocketClient,
|
||||
@@ -207,7 +207,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessagesClientClosed(final boolean useReactive) {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
|
||||
new AuthenticatedAccount(() -> new Pair<>(account, device)),
|
||||
device,
|
||||
webSocketClient,
|
||||
@@ -273,7 +273,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessagesSendFutureTimeout(final boolean useReactive) {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService),
|
||||
new AuthenticatedAccount(() -> new Pair<>(account, device)),
|
||||
device,
|
||||
webSocketClient,
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"success":true,"result":{"name":"CAD/USD","enabled":true,"postOnly":false,"priceIncrement":0.0001,"sizeIncrement":1.0,"minProvideSize":1.0,"last":0.8024,"bid":0.8014,"ask":0.8017,"price":0.8017,"type":"spot","baseCurrency":"CAD","quoteCurrency":"USD","underlying":null,"restricted":false,"highLeverageFeeExempt":true,"change1h":-0.000872382851445663,"change24h":-0.0007478499314470896,"changeBod":-0.0007478499314470896,"quoteVolume24h":116.3474,"volumeUsd24h":116.3474}}
|
||||
Reference in new issue
Block a user