mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 08:06:47 +00:00
Compare commits
52
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e04cac800 | ||
|
|
1db9258d39 | ||
|
|
2803c2acdb | ||
|
|
8be43566a4 | ||
|
|
d865cec2a4 | ||
|
|
6f0370a073 | ||
|
|
5b9f8177f2 | ||
|
|
6967e4e54b | ||
|
|
96fb0ac3ae | ||
|
|
7201938793 | ||
|
|
cdd6f78c73 | ||
|
|
ab94d3045d | ||
|
|
ff4e2bdfb7 | ||
|
|
ffed19d198 | ||
|
|
49d6a5e32d | ||
|
|
3ba7ba4f92 | ||
|
|
43ffc996db | ||
|
|
27f5f94c60 | ||
|
|
1d9734c824 | ||
|
|
717fb57a14 | ||
|
|
af1d21c225 | ||
|
|
3c8b2a82a3 | ||
|
|
0cb6f662c6 | ||
|
|
739ed56b4c | ||
|
|
9a19ef82fd | ||
|
|
5627ed141b | ||
|
|
e4a2af67b1 | ||
|
|
cba56f3263 | ||
|
|
1c3cf39b8a | ||
|
|
6421438f64 | ||
|
|
8a63682c16 | ||
|
|
13a8c6256d | ||
|
|
8c9cc4cce5 | ||
|
|
0023cb2521 | ||
|
|
010ed77345 | ||
|
|
00c11f5dd0 | ||
|
|
637e424506 | ||
|
|
eb55b80bdc | ||
|
|
73812b06be | ||
|
|
d135957f0d | ||
|
|
815fd44ab3 | ||
|
|
4e8a48ab3d | ||
|
|
ea75c39b58 | ||
|
|
085f013bf9 | ||
|
|
c6b8d890e5 | ||
|
|
66783c9381 | ||
|
|
b32e67ff9e | ||
|
|
ba55d6caeb | ||
|
|
1eba04d37b | ||
|
|
ecbb2f1399 | ||
|
|
93f4a91ebf | ||
|
|
a1ac5bd74c |
No files matched your search
@@ -8,6 +8,7 @@ package org.signal.integration;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.integration.config.Config;
|
||||
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
|
||||
@@ -19,7 +20,6 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class IntegrationTools {
|
||||
|
||||
@@ -34,11 +34,8 @@ public class IntegrationTools {
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient =
|
||||
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final DynamoDbClient dynamoDbClient =
|
||||
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, dynamoDbAsyncClient);
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbAsyncClient, Clock.systemUTC());
|
||||
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(
|
||||
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
|
||||
@@ -56,8 +53,8 @@ public class IntegrationTools {
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> populateRecoveryPassword(final String e164, final byte[] password) {
|
||||
return registrationRecoveryPasswordsManager.storeForCurrentNumber(e164, password);
|
||||
public CompletableFuture<Void> populateRecoveryPassword(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
return registrationRecoveryPasswordsManager.store(phoneNumberIdentifier, password);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
|
||||
@@ -78,7 +78,7 @@ public final class Operations {
|
||||
final TestUser user = TestUser.create(number, accountPassword, registrationPassword);
|
||||
final AccountAttributes accountAttributes = user.accountAttributes();
|
||||
|
||||
INTEGRATION_TOOLS.populateRecoveryPassword(number, registrationPassword).join();
|
||||
INTEGRATION_TOOLS.populateRecoveryPassword(user.pniUuid(), registrationPassword).join();
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
|
||||
@@ -8,5 +8,6 @@ package org.signal.integration.config;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record DynamoDbTables(@NotBlank String registrationRecovery,
|
||||
@NotBlank String verificationSessions) {
|
||||
@NotBlank String verificationSessions,
|
||||
@NotBlank String phoneNumberIdentifiers) {
|
||||
}
|
||||
@@ -58,7 +58,7 @@
|
||||
<kotlin.version>1.9.24</kotlin.version>
|
||||
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
|
||||
<lettuce.version>6.4.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.13.49</libphonenumber.version>
|
||||
<libphonenumber.version>8.13.50</libphonenumber.version>
|
||||
<logstash.logback.version>7.3</logstash.logback.version>
|
||||
<log4j-bom.version>2.23.1</log4j-bom.version>
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
@@ -484,7 +484,12 @@
|
||||
<version>3.8.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<!-- Set dependencies as properties for use in argLine property for mockito jar -->
|
||||
<!--
|
||||
Set dependencies as properties for use in argLine property for mockito jar.
|
||||
The property isn't needed until the test phase, and deferring it from the default
|
||||
`initialize` addresses issues running lifecycle phases that precede `test` in isolation.
|
||||
-->
|
||||
<phase>process-test-classes</phase>
|
||||
<goals>
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
|
||||
@@ -256,12 +256,15 @@ import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.workers.BackfillBeninPhoneNumberFormsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteE164RegistrationRecoveryPasswordsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MigrateDeletedAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
@@ -329,6 +332,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
|
||||
bootstrap.addCommand(new MigrateDeletedAccountsCommand());
|
||||
bootstrap.addCommand(new DeleteE164RegistrationRecoveryPasswordsCommand());
|
||||
bootstrap.addCommand(new BackfillBeninPhoneNumberFormsCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -404,7 +411,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
|
||||
ClientReleases clientReleases = new ClientReleases(dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getClientReleases().getTableName());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getProfiles().getTableName());
|
||||
@@ -429,9 +436,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient
|
||||
);
|
||||
dynamoDbAsyncClient,
|
||||
clock);
|
||||
ClientPublicKeys clientPublicKeys =
|
||||
new ClientPublicKeys(dynamoDbAsyncClient, config.getDynamoDbTables().getClientPublicKeys().getTableName());
|
||||
|
||||
@@ -583,8 +589,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
|
||||
registrationRecoveryPasswords);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
|
||||
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
|
||||
@@ -603,7 +609,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, clock, dynamicConfigurationManager);
|
||||
messageDeletionAsyncExecutor, clock);
|
||||
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
|
||||
recurringJobExecutor,
|
||||
config.getClientReleaseConfiguration().refreshInterval(),
|
||||
@@ -1074,7 +1080,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, turnTokenGenerator, registrationRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
@@ -1117,8 +1123,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
|
||||
config.getCdnConfiguration().bucket()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters,
|
||||
accountsManager, registrationFraudChecker, dynamicConfigurationManager, clock)
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, registrationFraudChecker,
|
||||
dynamicConfigurationManager, clock)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
|
||||
+7
-2
@@ -25,6 +25,7 @@ import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
|
||||
public class PhoneVerificationTokenManager {
|
||||
@@ -33,13 +34,17 @@ public class PhoneVerificationTokenManager {
|
||||
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
private static final long VERIFICATION_TIMEOUT_SECONDS = REGISTRATION_RPC_TIMEOUT.plusSeconds(1).getSeconds();
|
||||
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final RegistrationRecoveryChecker registrationRecoveryChecker;
|
||||
|
||||
public PhoneVerificationTokenManager(final RegistrationServiceClient registrationServiceClient,
|
||||
public PhoneVerificationTokenManager(final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final RegistrationServiceClient registrationServiceClient,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final RegistrationRecoveryChecker registrationRecoveryChecker) {
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.registrationRecoveryChecker = registrationRecoveryChecker;
|
||||
@@ -109,7 +114,7 @@ public class PhoneVerificationTokenManager {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
}
|
||||
try {
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(number, recoveryPassword)
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(), recoveryPassword)
|
||||
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!verified) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
|
||||
+2
-2
@@ -23,11 +23,11 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.Svr3Credentials;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -157,7 +157,7 @@ public class RegistrationLockVerificationManager {
|
||||
// This allows users to re-register via registration recovery password
|
||||
// instead of always being forced to fall back to SMS verification.
|
||||
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(updatedAccount.getNumber());
|
||||
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
|
||||
}
|
||||
|
||||
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
|
||||
+2
-2
@@ -48,7 +48,7 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
*/
|
||||
public class BackupAuthManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BackupManager.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(BackupAuthManager.class);
|
||||
|
||||
|
||||
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
|
||||
@@ -238,7 +238,7 @@ public class BackupAuthManager {
|
||||
return accountsManager.updateAsync(account, a -> {
|
||||
final Account.BackupVoucher newPayment = new Account.BackupVoucher(receiptLevel, receiptExpiration);
|
||||
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
|
||||
account.setBackupVoucher(merge(existingPayment, newPayment));
|
||||
a.setBackupVoucher(merge(existingPayment, newPayment));
|
||||
});
|
||||
})
|
||||
.thenRun(Util.NOOP);
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.databind.util.StdConverter;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
final class URLDeserializationConverter extends StdConverter<String, URL> {
|
||||
|
||||
@Override
|
||||
public URL convert(final String value) {
|
||||
try {
|
||||
return new URL(value);
|
||||
} catch (MalformedURLException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
-8
@@ -68,10 +68,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagesConfiguration messagesConfiguration = new DynamicMessagesConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
|
||||
@@ -130,10 +126,6 @@ public class DynamicConfiguration {
|
||||
return metricsConfiguration;
|
||||
}
|
||||
|
||||
public DynamicMessagesConfiguration getMessagesConfiguration() {
|
||||
return messagesConfiguration;
|
||||
}
|
||||
|
||||
public List<String> getSvrStatusCodesToIgnoreForAccountDeletion() {
|
||||
return svrStatusCodesToIgnoreForAccountDeletion;
|
||||
}
|
||||
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicMessagesConfiguration(boolean useSharedMrmData) {
|
||||
|
||||
public DynamicMessagesConfiguration() {
|
||||
this(false);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameHashResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameLinkHandle;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -259,7 +260,7 @@ public class AccountController {
|
||||
|
||||
// if registration recovery password was sent to us, store it (or refresh its expiration)
|
||||
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
|
||||
registrationRecoveryPasswordsManager.storeForCurrentNumber(updatedAccount.getNumber(), registrationRecoveryPassword));
|
||||
registrationRecoveryPasswordsManager.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword));
|
||||
}
|
||||
|
||||
@GET
|
||||
|
||||
+2
-17
@@ -11,7 +11,6 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.DefaultValue;
|
||||
@@ -39,7 +38,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@@ -56,8 +54,6 @@ public class CertificateController {
|
||||
public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
|
||||
private static final String GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME = name(CertificateGenerator.class, "generateCertificate");
|
||||
private static final String INCLUDE_E164_TAG_NAME = "includeE164";
|
||||
private static final String GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME = name(CertificateController.class,
|
||||
"getGroupAuthenticationCredentials");
|
||||
|
||||
public CertificateController(
|
||||
@Nonnull CertificateGenerator certificateGenerator,
|
||||
@@ -91,8 +87,7 @@ public class CertificateController {
|
||||
@ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds,
|
||||
@QueryParam("zkcCredential") boolean zkcCredential) {
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds) {
|
||||
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant redemptionStart = Instant.ofEpochSecond(startSeconds);
|
||||
@@ -107,11 +102,6 @@ public class CertificateController {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
Metrics
|
||||
.counter(GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)).and("zkcCredential", String.valueOf(zkcCredential)))
|
||||
.increment();
|
||||
|
||||
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
|
||||
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
|
||||
|
||||
@@ -121,12 +111,7 @@ public class CertificateController {
|
||||
ServiceId.Pni pni = new ServiceId.Pni(auth.getAccount().getPhoneNumberIdentifier());
|
||||
|
||||
while (!redemption.isAfter(redemptionEnd)) {
|
||||
AuthCredentialWithPniResponse authCredentialWithPni;
|
||||
if (zkcCredential) {
|
||||
authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
|
||||
} else {
|
||||
authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniAsServiceId(aci, pni, redemption);
|
||||
}
|
||||
AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
|
||||
credentials.add(new GroupCredentials.GroupCredential(
|
||||
authCredentialWithPni.serialize(),
|
||||
(int) redemption.getEpochSecond()));
|
||||
|
||||
+11
-4
@@ -65,8 +65,10 @@ import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
@@ -522,8 +524,10 @@ public class DeviceController {
|
||||
@Operation(
|
||||
summary = "Signals that a transfer archive has been uploaded for a specific linked device",
|
||||
description = """
|
||||
Signals that a transfer archive has been uploaded for a specific linked device. Devices waiting via the "wait
|
||||
for transfer archive" endpoint will be notified that the new archive is available.
|
||||
Signals that a transfer archive has been uploaded or failed for a specific linked device. Devices waiting via
|
||||
the "wait for transfer archive" endpoint will be notified that the new archive is available.
|
||||
|
||||
If the uploader cannot upload the transfer archive, they must signal an error.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "Success")
|
||||
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
|
||||
@@ -546,8 +550,11 @@ public class DeviceController {
|
||||
Waits for a new transfer archive to be uploaded for the authenticated device and returns the location of the
|
||||
archive when available.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "A new transfer archive was uploaded for the authenticated device",
|
||||
content = @Content(schema = @Schema(implementation = RemoteAttachment.class)))
|
||||
@ApiResponse(responseCode = "200", description = "Either a new transfer archive was uploaded for the authenticated device, or the upload has failed",
|
||||
content = @Content(schema = @Schema(description = """
|
||||
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
|
||||
the upload has failed and the destination device should stop waiting
|
||||
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})))
|
||||
@ApiResponse(responseCode = "204", description = "No transfer archive was uploaded before the call completed; clients may repeat the call to continue waiting")
|
||||
@ApiResponse(responseCode = "400", description = "The given timeout was invalid")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
|
||||
|
||||
-3
@@ -952,9 +952,6 @@ public class MessageController {
|
||||
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
|
||||
|
||||
// mrm views phase 3: always set content
|
||||
messageBuilder.setContent(ByteString.copyFrom(payload));
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "OneTimeDonations")
|
||||
public class OneTimeDonationController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SubscriptionController.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(OneTimeDonationController.class);
|
||||
|
||||
private static final String EURO_CURRENCY_CODE = "EUR";
|
||||
|
||||
|
||||
+8
-4
@@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker.VerificationCheck;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
@@ -116,6 +117,7 @@ public class VerificationController {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final RegistrationCaptchaManager registrationCaptchaManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final AccountsManager accountsManager;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
@@ -127,6 +129,7 @@ public class VerificationController {
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RegistrationCaptchaManager registrationCaptchaManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final RateLimiters rateLimiters,
|
||||
final AccountsManager accountsManager,
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
@@ -137,6 +140,7 @@ public class VerificationController {
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.registrationCaptchaManager = registrationCaptchaManager;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
@@ -598,7 +602,7 @@ public class VerificationController {
|
||||
}
|
||||
|
||||
if (resultSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
Metrics.counter(VERIFIED_COUNTER_NAME, Tags.of(
|
||||
@@ -626,8 +630,8 @@ public class VerificationController {
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ClientErrorException with {@code 422} status if the ID cannot be decoded
|
||||
* @throws javax.ws.rs.NotFoundException if the ID cannot be found
|
||||
* @throws ClientErrorException with {@code 422} status if the ID cannot be decoded
|
||||
* @throws NotFoundException if the ID cannot be found
|
||||
*/
|
||||
private RegistrationServiceSession retrieveRegistrationServiceSession(final String encodedSessionId) {
|
||||
final byte[] sessionId;
|
||||
@@ -644,7 +648,7 @@ public class VerificationController {
|
||||
.orElseThrow(NotFoundException::new);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
return registrationServiceSession;
|
||||
|
||||
+2
@@ -20,6 +20,7 @@ import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.E164;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
|
||||
|
||||
@@ -34,6 +35,7 @@ public record ChangeNumberRequest(
|
||||
Must not be combined with `sessionId`.""")
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class) byte[] recoveryPassword,
|
||||
|
||||
@E164
|
||||
@Schema(description="the new phone number for this account")
|
||||
@NotBlank String number,
|
||||
|
||||
|
||||
+5
-2
@@ -9,8 +9,11 @@ import java.util.Base64;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.registration.rpc.RegistrationSessionMetadata;
|
||||
|
||||
public record RegistrationServiceSession(byte[] id, String number, boolean verified,
|
||||
@Nullable Long nextSms, @Nullable Long nextVoiceCall,
|
||||
public record RegistrationServiceSession(byte[] id,
|
||||
String number,
|
||||
boolean verified,
|
||||
@Nullable Long nextSms,
|
||||
@Nullable Long nextVoiceCall,
|
||||
@Nullable Long nextVerificationAttempt,
|
||||
long expiration) {
|
||||
|
||||
|
||||
+4
-3
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.whispersystems.textsecuregcm.util.ValidBase64URLString;
|
||||
|
||||
public record RemoteAttachment(
|
||||
@@ -17,6 +18,6 @@ public record RemoteAttachment(
|
||||
|
||||
@NotBlank
|
||||
@ValidBase64URLString
|
||||
@Schema(description = "The attachment key")
|
||||
String key) {
|
||||
}
|
||||
@Size(max = 64)
|
||||
@Schema(description = "The attachment key", maxLength = 64)
|
||||
String key) implements TransferArchiveResult {}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
@Schema(description = "Indicates an attachment failed to upload")
|
||||
public record RemoteAttachmentError(
|
||||
@Schema(description = "The type of error encountered")
|
||||
@Valid @NotNull ErrorType error)
|
||||
implements TransferArchiveResult {
|
||||
|
||||
public enum ErrorType {
|
||||
RELINK_REQUESTED,
|
||||
CONTINUE_WITHOUT_UPLOAD;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = RemoteAttachment.class, name = "success"),
|
||||
@JsonSubTypes.Type(value = RemoteAttachmentError.class, name = "error"),
|
||||
})
|
||||
public sealed interface TransferArchiveResult permits RemoteAttachment, RemoteAttachmentError {}
|
||||
+16
-11
@@ -9,19 +9,24 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
public record TransferArchiveUploadedRequest(@Min(1)
|
||||
@Max(Device.MAXIMUM_DEVICE_ID)
|
||||
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
|
||||
byte destinationDeviceId,
|
||||
public record TransferArchiveUploadedRequest(
|
||||
@Min(1)
|
||||
@Max(Device.MAXIMUM_DEVICE_ID)
|
||||
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
|
||||
byte destinationDeviceId,
|
||||
|
||||
@Positive
|
||||
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
|
||||
long destinationDeviceCreated,
|
||||
@Positive
|
||||
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
|
||||
long destinationDeviceCreated,
|
||||
|
||||
@Schema(description = "The location of the transfer archive")
|
||||
@Valid
|
||||
RemoteAttachment transferArchive) {
|
||||
}
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(description = """
|
||||
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
|
||||
the upload has failed and the destination device should stop waiting
|
||||
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
|
||||
TransferArchiveResult transferArchive) {}
|
||||
+2
-1
@@ -47,6 +47,7 @@ import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -336,7 +337,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.storeForCurrentNumber(account.getNumber(), request.getRegistrationRecoveryPassword().toByteArray())))
|
||||
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI), request.getRegistrationRecoveryPassword().toByteArray())))
|
||||
.thenReturn(SetRegistrationRecoveryPasswordResponse.newBuilder().build());
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -4,16 +4,15 @@ import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import software.amazon.awssdk.metrics.MetricCollection;
|
||||
import software.amazon.awssdk.metrics.MetricPublisher;
|
||||
import software.amazon.awssdk.metrics.MetricRecord;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import software.amazon.awssdk.metrics.MetricCollection;
|
||||
import software.amazon.awssdk.metrics.MetricPublisher;
|
||||
import software.amazon.awssdk.metrics.MetricRecord;
|
||||
|
||||
/**
|
||||
* A Micrometer AWS SDK metric publisher consumes {@link MetricCollection} instances provided by the AWS SDK when it
|
||||
@@ -80,6 +79,9 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
|
||||
private static final String CONCURRENT_REQUESTS_DISTRIBUTION_NAME =
|
||||
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "concurrentRequests");
|
||||
|
||||
private static final String MAX_CONCURRENCY_GAUGE_NAME =
|
||||
MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class, "maxConcurrency");
|
||||
|
||||
private static final String CLIENT_NAME_TAG = "clientName";
|
||||
|
||||
/**
|
||||
@@ -93,7 +95,7 @@ public class MicrometerAwsSdkMetricPublisher implements MetricPublisher {
|
||||
this.recordMetricsExecutorService = recordMetricsExecutorService;
|
||||
this.awsClientName = awsClientName;
|
||||
|
||||
mostRecentMaxConcurrency = Metrics.gauge("maxConcurrency",
|
||||
mostRecentMaxConcurrency = Metrics.gauge(MAX_CONCURRENCY_GAUGE_NAME,
|
||||
Tags.of(CLIENT_NAME_TAG, awsClientName),
|
||||
new AtomicInteger(0));
|
||||
}
|
||||
|
||||
-4
@@ -124,10 +124,6 @@ public class IdentityTokenCallCredentials extends CallCredentials implements Man
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void thisUsesUnstableApi() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
synchronized (this) {
|
||||
|
||||
+32
-31
@@ -8,6 +8,7 @@ import com.amazonaws.services.dynamodbv2.ReleaseLockOptions;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -19,12 +20,12 @@ public class AccountLockManager {
|
||||
|
||||
private final AmazonDynamoDBLockClient lockClient;
|
||||
|
||||
static final String KEY_ACCOUNT_E164 = "P";
|
||||
static final String KEY_ACCOUNT_PNI = "P";
|
||||
|
||||
public AccountLockManager(final DynamoDbClient lockDynamoDb, final String lockTableName) {
|
||||
this(new AmazonDynamoDBLockClient(
|
||||
AmazonDynamoDBLockClientOptions.builder(lockDynamoDb, lockTableName)
|
||||
.withPartitionKeyName(KEY_ACCOUNT_E164)
|
||||
.withPartitionKeyName(KEY_ACCOUNT_PNI)
|
||||
.withLeaseDuration(15L)
|
||||
.withHeartbeatPeriod(2L)
|
||||
.withTimeUnit(TimeUnit.SECONDS)
|
||||
@@ -38,33 +39,34 @@ public class AccountLockManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone numbers. By design, the
|
||||
* accounts need not actually exist in order to acquire a lock; this allows lock acquisition for operations that span
|
||||
* account lifecycle changes (like deleting an account or changing a phone number). The given task runs once locks for
|
||||
* all given phone numbers have been acquired, and the locks are released as soon as the task completes by any means.
|
||||
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone number identifiers. By
|
||||
* design, the accounts need not actually exist in order to acquire a lock; this allows lock acquisition for
|
||||
* operations that span account lifecycle changes (like deleting an account or changing a phone number). The given
|
||||
* task runs once locks for all given identifiers have been acquired, and the locks are released as soon as the task
|
||||
* completes by any means.
|
||||
*
|
||||
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
|
||||
* @param task the task to execute once locks have been acquired
|
||||
* @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
|
||||
* @param task the task to execute once locks have been acquired
|
||||
* @param lockAcquisitionExecutor the executor on which to run blocking lock acquire/release tasks. this executor
|
||||
* should not use virtual threads.
|
||||
*
|
||||
* @throws InterruptedException if interrupted while acquiring a lock
|
||||
*/
|
||||
public void withLock(final List<String> e164s, final Runnable task, final Executor lockAcquisitionExecutor) {
|
||||
if (e164s.isEmpty()) {
|
||||
throw new IllegalArgumentException("List of e164s to lock must not be empty");
|
||||
public void withLock(final List<UUID> phoneNumberIdentifiers, final Runnable task,
|
||||
final Executor lockAcquisitionExecutor) {
|
||||
if (phoneNumberIdentifiers.isEmpty()) {
|
||||
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
|
||||
}
|
||||
|
||||
final List<LockItem> lockItems = new ArrayList<>(e164s.size());
|
||||
final List<LockItem> lockItems = new ArrayList<>(phoneNumberIdentifiers.size());
|
||||
|
||||
try {
|
||||
// Offload the acquire/release tasks to the dedicated lock acquisition executor. The lock client performs blocking
|
||||
// operations while holding locks which forces thread pinning when this method runs on a virtual thread.
|
||||
// https://github.com/awslabs/amazon-dynamodb-lock-client/issues/97
|
||||
CompletableFuture.runAsync(() -> {
|
||||
for (final String e164 : e164s) {
|
||||
for (final UUID pni : phoneNumberIdentifiers) {
|
||||
try {
|
||||
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(e164)
|
||||
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
|
||||
.withAcquireReleasedLocksConsistently(true)
|
||||
.build()));
|
||||
} catch (final InterruptedException e) {
|
||||
@@ -86,32 +88,31 @@ public class AccountLockManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone numbers. By design, the
|
||||
* accounts need not actually exist in order to acquire a lock; this allows lock acquisition for operations that span
|
||||
* account lifecycle changes (like deleting an account or changing a phone number). The given task runs once locks for
|
||||
* all given phone numbers have been acquired, and the locks are released as soon as the task completes by any means.
|
||||
*
|
||||
* @param e164s the phone numbers for which to acquire a distributed, pessimistic lock
|
||||
* @param taskSupplier a supplier for the task to execute once locks have been acquired
|
||||
* @param executor the executor on which to acquire and release locks
|
||||
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone number identifiers. By
|
||||
* design, the accounts need not actually exist in order to acquire a lock; this allows lock acquisition for
|
||||
* operations that span account lifecycle changes (like deleting an account or changing a phone number). The given
|
||||
* task runs once locks for all given identifiers have been acquired, and the locks are released as soon as the task
|
||||
* completes by any means.
|
||||
*
|
||||
* @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
|
||||
* @param taskSupplier a supplier for the task to execute once locks have been acquired
|
||||
* @param executor the executor on which to acquire and release locks
|
||||
* @return a future that completes normally when the given task has executed successfully and all locks have been
|
||||
* released; the returned future may fail with an {@link InterruptedException} if interrupted while acquiring a lock
|
||||
*/
|
||||
public <T> CompletableFuture<T> withLockAsync(final List<String> e164s,
|
||||
final Supplier<CompletableFuture<T>> taskSupplier,
|
||||
final Executor executor) {
|
||||
public <T> CompletableFuture<T> withLockAsync(final List<UUID> phoneNumberIdentifiers,
|
||||
final Supplier<CompletableFuture<T>> taskSupplier, final Executor executor) {
|
||||
|
||||
if (e164s.isEmpty()) {
|
||||
throw new IllegalArgumentException("List of e164s to lock must not be empty");
|
||||
if (phoneNumberIdentifiers.isEmpty()) {
|
||||
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
|
||||
}
|
||||
|
||||
final List<LockItem> lockItems = new ArrayList<>(e164s.size());
|
||||
final List<LockItem> lockItems = new ArrayList<>(phoneNumberIdentifiers.size());
|
||||
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
for (final String e164 : e164s) {
|
||||
for (final UUID pni : phoneNumberIdentifiers) {
|
||||
try {
|
||||
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(e164)
|
||||
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
|
||||
.withAcquireReleasedLocksConsistently(true)
|
||||
.build()));
|
||||
} catch (final InterruptedException e) {
|
||||
|
||||
@@ -47,6 +47,8 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple3;
|
||||
import reactor.util.function.Tuples;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -57,6 +59,7 @@ import software.amazon.awssdk.services.dynamodb.model.Delete;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Put;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
@@ -240,9 +243,10 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
// Clear any "recently deleted account" record for this number since, if it existed, we've used its old ACI for
|
||||
// the newly-created account.
|
||||
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getNumber());
|
||||
final TransactWriteItem deletedAccountDeletePNI = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier());
|
||||
|
||||
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
|
||||
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete));
|
||||
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDeletePNI, deletedAccountDelete));
|
||||
|
||||
writeItems.addAll(additionalWriteItems);
|
||||
|
||||
@@ -266,8 +270,9 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
if (conditionalCheckFailed(phoneNumberConstraintCancellationReason)
|
||||
|| conditionalCheckFailed(phoneNumberIdentifierConstraintCancellationReason)) {
|
||||
|
||||
// In theory, both reasons should trip in tandem and either should give us the information we need. Even so,
|
||||
// we'll be cautious here and make sure we're choosing a condition check that really failed.
|
||||
// Both reasons should trip in tandem and either should give us the information we need. However, phone number
|
||||
// canonicalization can cause multiple e164s to have the same PNI, so we make sure we're choosing a condition
|
||||
// check that really failed.
|
||||
final CancellationReason reason = conditionalCheckFailed(phoneNumberConstraintCancellationReason)
|
||||
? phoneNumberConstraintCancellationReason
|
||||
: phoneNumberIdentifierConstraintCancellationReason;
|
||||
@@ -436,8 +441,11 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
writeItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, originalPni));
|
||||
writeItems.add(buildConstraintTablePut(phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniAttr));
|
||||
writeItems.add(buildRemoveDeletedAccount(number));
|
||||
maybeDisplacedAccountIdentifier.ifPresent(displacedAccountIdentifier ->
|
||||
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalNumber)));
|
||||
writeItems.add(buildRemoveDeletedAccount(phoneNumberIdentifier));
|
||||
maybeDisplacedAccountIdentifier.ifPresent(displacedAccountIdentifier -> {
|
||||
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalNumber));
|
||||
writeItems.add(buildPutDeletedAccount(displacedAccountIdentifier, originalPni));
|
||||
});
|
||||
|
||||
// The `catch (TransactionCanceledException) block needs to check whether the cancellation reason is the account
|
||||
// update write item
|
||||
@@ -1160,7 +1168,19 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.item(Map.of(
|
||||
DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164),
|
||||
DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
|
||||
DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(Instant.now().plus(DELETED_ACCOUNTS_TIME_TO_LIVE).getEpochSecond())))
|
||||
DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(clock.instant().plus(DELETED_ACCOUNTS_TIME_TO_LIVE).getEpochSecond())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private TransactWriteItem buildPutDeletedAccount(final UUID aci, final UUID pni) {
|
||||
return TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.item(Map.of(
|
||||
DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(pni.toString()),
|
||||
DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(aci),
|
||||
DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(clock.instant().plus(DELETED_ACCOUNTS_TIME_TO_LIVE).getEpochSecond())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
@@ -1174,6 +1194,15 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.build();
|
||||
}
|
||||
|
||||
private TransactWriteItem buildRemoveDeletedAccount(final UUID pni) {
|
||||
return TransactWriteItem.builder()
|
||||
.delete(Delete.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(pni.toString())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public CompletableFuture<Optional<Account>> getByAccountIdentifierAsync(final UUID uuid) {
|
||||
return AsyncTimerUtil.record(GET_BY_UUID_TIMER, () -> itemByKeyAsync(accountsTableName, KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid))
|
||||
@@ -1191,6 +1220,16 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
return Optional.ofNullable(AttributeValues.getUUID(response.item(), DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, null));
|
||||
}
|
||||
|
||||
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final UUID phoneNumberIdentifier) {
|
||||
final GetItemResponse response = db().getItem(GetItemRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.build());
|
||||
|
||||
return Optional.ofNullable(AttributeValues.getUUID(response.item(), DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, null));
|
||||
}
|
||||
|
||||
public Optional<String> findRecentlyDeletedE164(final UUID uuid) {
|
||||
final QueryResponse response = db().query(QueryRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
@@ -1205,11 +1244,10 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (response.count() > 1) {
|
||||
throw new RuntimeException("Impossible result: more than one phone number returned for UUID: " + uuid);
|
||||
}
|
||||
|
||||
return Optional.ofNullable(response.items().get(0).get(DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s());
|
||||
return response.items().stream()
|
||||
.map(item -> item.get(DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s())
|
||||
.filter(e164OrPni -> e164OrPni.startsWith("+"))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> delete(final UUID uuid, final List<TransactWriteItem> additionalWriteItems) {
|
||||
@@ -1221,7 +1259,8 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
|
||||
buildDelete(accountsTableName, KEY_ACCOUNT_UUID, uuid),
|
||||
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
|
||||
buildPutDeletedAccount(uuid, account.getNumber())
|
||||
buildPutDeletedAccount(uuid, account.getNumber()),
|
||||
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
|
||||
));
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
|
||||
@@ -1257,6 +1296,68 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.sequential();
|
||||
}
|
||||
|
||||
public Flux<Tuple3<String, UUID, Long>> getE164KeyedDeletedAccounts(final int segments, final Scheduler scheduler) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> asyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.consistentRead(true)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.build())
|
||||
.items())
|
||||
.map(item ->
|
||||
Tuples.of(
|
||||
item.get(DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s(),
|
||||
AttributeValues.getUUID(item, DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, null),
|
||||
AttributeValues.getLong(item, DELETED_ACCOUNTS_ATTR_EXPIRES, 0)))
|
||||
.filter(item -> item.getT1().startsWith("+"))
|
||||
.sequential();
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> insertPniDeletedAccount(final String e164, final UUID pni, final UUID aci, final long expiration) {
|
||||
// This happens under a pessimistic lock, but that wasn't taken before we found the record we want to migrate,
|
||||
// so make sure the e164 record is unchanged before updating the PNI record
|
||||
return asyncClient.getItem(GetItemRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164.toString())))
|
||||
.build())
|
||||
.thenComposeAsync(getItemResponse ->
|
||||
getItemResponse.hasItem()
|
||||
&& AttributeValues.getString(
|
||||
getItemResponse.item(), DELETED_ACCOUNTS_KEY_ACCOUNT_E164, "").equals(e164)
|
||||
&& AttributeValues.getUUID(
|
||||
getItemResponse.item(), DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, UUID.randomUUID()).equals(aci)
|
||||
&& AttributeValues.getLong(
|
||||
getItemResponse.item(), DELETED_ACCOUNTS_ATTR_EXPIRES, 0) == expiration
|
||||
? asyncClient.putItem(
|
||||
PutItemRequest.builder()
|
||||
.tableName(deletedAccountsTableName)
|
||||
.item(
|
||||
Map.of(
|
||||
DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(pni.toString()),
|
||||
DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(aci),
|
||||
DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(expiration)))
|
||||
.conditionExpression("attribute_not_exists(#key)")
|
||||
.expressionAttributeNames(Map.of("#key", DELETED_ACCOUNTS_KEY_ACCOUNT_E164))
|
||||
.build())
|
||||
.thenApply(ignored -> true)
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) {
|
||||
// there was already a PNI record; no problem, do nothing
|
||||
return false;
|
||||
}
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
})
|
||||
: CompletableFuture.completedFuture(false));
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private Optional<Account> getByIndirectLookup(
|
||||
final Timer timer,
|
||||
@@ -1407,9 +1508,9 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.conditionExpression("attribute_not_exists(#number) OR #number = :number")
|
||||
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164))
|
||||
.expressionAttributeValues(Map.of(":number", numberAttr))
|
||||
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
|
||||
.expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID))
|
||||
.expressionAttributeValues(Map.of(":pni", pniUuidAttr))
|
||||
.tableName(accountsTableName)
|
||||
.item(item)
|
||||
.build())
|
||||
|
||||
+75
-36
@@ -72,8 +72,8 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
@@ -90,6 +90,7 @@ import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple3;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
|
||||
@@ -140,7 +141,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final Map<String, CompletableFuture<Optional<DeviceInfo>>> waitForDeviceFuturesByTokenIdentifier =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<RemoteAttachment>>> waitForTransferArchiveFuturesByDeviceIdentifier =
|
||||
private final Map<TimestampedDeviceIdentifier, CompletableFuture<Optional<TransferArchiveResult>>> waitForTransferArchiveFuturesByDeviceIdentifier =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
private final Map<String, CompletableFuture<Optional<RestoreAccountRequest>>> waitForRestoreAccountRequestFuturesByToken =
|
||||
@@ -163,8 +164,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private static final ObjectWriter ACCOUNT_REDIS_JSON_WRITER = SystemMapper.jsonMapper()
|
||||
.writer(SystemMapper.excludingField(Account.class, List.of("uuid")));
|
||||
|
||||
private static Duration MESSAGE_POLL_INTERVAL = Duration.ofSeconds(1);
|
||||
private static Duration MAX_SERVER_CLOCK_DRIFT = Duration.ofSeconds(5);
|
||||
private static final Duration MESSAGE_POLL_INTERVAL = Duration.ofSeconds(1);
|
||||
private static final Duration MAX_SERVER_CLOCK_DRIFT = Duration.ofSeconds(5);
|
||||
|
||||
// An account that's used at least daily will get reset in the cache at least once per day when its "last seen"
|
||||
// timestamp updates; expiring entries after two days will help clear out "zombie" cache entries that are read
|
||||
@@ -271,16 +272,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
@Nullable final String userAgent) throws InterruptedException {
|
||||
|
||||
final Account account = new Account();
|
||||
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
|
||||
|
||||
return createTimer.record(() -> {
|
||||
accountLockManager.withLock(List.of(number), () -> {
|
||||
accountLockManager.withLock(List.of(pni), () -> {
|
||||
final Optional<UUID> maybeRecentlyDeletedAccountIdentifier =
|
||||
accounts.findRecentlyDeletedAccountIdentifier(number);
|
||||
|
||||
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is
|
||||
// re-registering.
|
||||
account.setNumber(number, phoneNumberIdentifiers.getPhoneNumberIdentifier(number));
|
||||
account.setUuid(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
|
||||
account.setNumber(number, pni);
|
||||
account.setIdentityKey(aciIdentityKey);
|
||||
account.setPhoneNumberIdentityKey(pniIdentityKey);
|
||||
account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock));
|
||||
@@ -292,6 +294,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
String accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent() ? "recently-deleted" : "new";
|
||||
|
||||
final String pushTokenType;
|
||||
|
||||
if (primaryDeviceSpec.apnRegistrationId().isPresent()) {
|
||||
pushTokenType = "apns";
|
||||
} else if (primaryDeviceSpec.gcmRegistrationId().isPresent()) {
|
||||
pushTokenType = "fcm";
|
||||
} else {
|
||||
pushTokenType = "none";
|
||||
}
|
||||
|
||||
String previousPushTokenType = null;
|
||||
|
||||
try {
|
||||
accounts.create(account, keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI),
|
||||
account.getIdentifier(IdentityType.PNI),
|
||||
@@ -303,11 +317,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
} catch (final AccountAlreadyExistsException e) {
|
||||
accountCreationType = "re-registration";
|
||||
|
||||
final UUID aci = e.getExistingAccount().getIdentifier(IdentityType.ACI);
|
||||
final UUID pni = e.getExistingAccount().getIdentifier(IdentityType.PNI);
|
||||
if (StringUtils.isNotBlank(e.getExistingAccount().getPrimaryDevice().getApnId())) {
|
||||
previousPushTokenType = "apns";
|
||||
} else if (StringUtils.isNotBlank(e.getExistingAccount().getPrimaryDevice().getGcmId())) {
|
||||
previousPushTokenType = "fcm";
|
||||
} else {
|
||||
previousPushTokenType = "none";
|
||||
}
|
||||
|
||||
final UUID aci = e.getExistingAccount().getIdentifier(IdentityType.ACI);
|
||||
account.setUuid(aci);
|
||||
account.setNumber(e.getExistingAccount().getNumber(), pni);
|
||||
|
||||
final List<TransactWriteItem> additionalWriteItems = Stream.concat(
|
||||
keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI),
|
||||
@@ -343,23 +362,31 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
// We exclude the primary device's repeated-use keys from deletion because new keys were provided as
|
||||
// part of the account creation process, and we don't want to delete the keys that just got added.
|
||||
return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci),
|
||||
keysManager.deleteSingleUsePreKeys(pni),
|
||||
messagesManager.clear(aci),
|
||||
profilesManager.deleteAll(aci));
|
||||
keysManager.deleteSingleUsePreKeys(pni),
|
||||
messagesManager.clear(aci),
|
||||
profilesManager.deleteAll(aci));
|
||||
})
|
||||
.join();
|
||||
}
|
||||
|
||||
redisSet(account);
|
||||
|
||||
Metrics.counter(CREATE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("type", accountCreationType),
|
||||
Tag.of("hasPushToken", String.valueOf(
|
||||
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId().isPresent()))))
|
||||
.increment();
|
||||
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("type", accountCreationType),
|
||||
Tag.of("hasPushToken", String.valueOf(
|
||||
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId()
|
||||
.isPresent())),
|
||||
Tag.of("pushTokenType", pushTokenType));
|
||||
|
||||
if (StringUtils.isNotBlank(previousPushTokenType)) {
|
||||
tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType));
|
||||
}
|
||||
|
||||
Metrics.counter(CREATE_COUNTER_NAME, tags).increment();
|
||||
|
||||
accountAttributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
|
||||
registrationRecoveryPasswordsManager.storeForCurrentNumber(account.getNumber(), registrationRecoveryPassword));
|
||||
registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI),
|
||||
registrationRecoveryPassword));
|
||||
}, accountLockExecutor);
|
||||
|
||||
return account;
|
||||
@@ -367,7 +394,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
public CompletableFuture<Pair<Account, Device>> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken) {
|
||||
return accountLockManager.withLockAsync(List.of(account.getNumber()),
|
||||
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
|
||||
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
|
||||
accountLockExecutor);
|
||||
}
|
||||
@@ -555,7 +582,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
throw new IllegalArgumentException("Cannot remove primary device");
|
||||
}
|
||||
|
||||
return accountLockManager.withLockAsync(List.of(account.getNumber()),
|
||||
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
|
||||
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
|
||||
accountLockExecutor);
|
||||
}
|
||||
@@ -608,10 +635,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
@Nullable final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
|
||||
@Nullable final Map<Byte, Integer> pniRegistrationIds) throws InterruptedException, MismatchedDevicesException {
|
||||
|
||||
final String originalNumber = account.getNumber();
|
||||
final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifier();
|
||||
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
|
||||
|
||||
if (originalNumber.equals(targetNumber)) {
|
||||
if (originalPhoneNumberIdentifier.equals(targetPhoneNumberIdentifier)) {
|
||||
if (pniIdentityKey != null) {
|
||||
throw new IllegalArgumentException("change number must supply a changed phone number; otherwise use updatePniKeys");
|
||||
}
|
||||
@@ -622,7 +649,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
final AtomicReference<Account> updatedAccount = new AtomicReference<>();
|
||||
|
||||
accountLockManager.withLock(List.of(account.getNumber(), targetNumber), () -> {
|
||||
accountLockManager.withLock(List.of(account.getPhoneNumberIdentifier(), targetPhoneNumberIdentifier), () -> {
|
||||
redisDelete(account);
|
||||
|
||||
// There are three possible states for accounts associated with the target phone number:
|
||||
@@ -648,15 +675,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
final UUID uuid = account.getUuid();
|
||||
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber);
|
||||
|
||||
CompletableFuture.allOf(
|
||||
keysManager.deleteSingleUsePreKeys(phoneNumberIdentifier),
|
||||
keysManager.deleteSingleUsePreKeys(targetPhoneNumberIdentifier),
|
||||
keysManager.deleteSingleUsePreKeys(originalPhoneNumberIdentifier))
|
||||
.join();
|
||||
|
||||
final Collection<TransactWriteItem> keyWriteItems =
|
||||
buildPniKeyWriteItems(uuid, phoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
|
||||
buildPniKeyWriteItems(uuid, targetPhoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
|
||||
|
||||
final Account numberChangedAccount = updateWithRetries(
|
||||
account,
|
||||
@@ -664,7 +690,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
setPniKeys(account, pniIdentityKey, pniRegistrationIds);
|
||||
return true;
|
||||
},
|
||||
a -> accounts.changeNumber(a, targetNumber, phoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
|
||||
a -> accounts.changeNumber(a, targetNumber, targetPhoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
|
||||
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
|
||||
AccountChangeValidator.NUMBER_CHANGE_VALIDATOR);
|
||||
|
||||
@@ -738,7 +764,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
account.getDevices()
|
||||
.stream()
|
||||
.forEach(device -> device.setPhoneNumberIdentityRegistrationId(pniRegistrationIds.get(device.getId())));
|
||||
|
||||
account.setPhoneNumberIdentityKey(pniIdentityKey);
|
||||
@@ -1177,7 +1202,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
public UUID getPhoneNumberIdentifier(String e164) {
|
||||
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164);
|
||||
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164).join();
|
||||
}
|
||||
|
||||
public Optional<UUID> findRecentlyDeletedAccountIdentifier(final String e164) {
|
||||
@@ -1192,10 +1217,24 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return accounts.getAll(segments, scheduler);
|
||||
}
|
||||
|
||||
public Flux<Tuple3<String, UUID, Long>> getE164KeyedDeletedAccounts(final int segments, final Scheduler scheduler) {
|
||||
return accounts.getE164KeyedDeletedAccounts(segments, scheduler);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> migrateDeletedAccount(final String e164, final UUID aci, final long expiration) {
|
||||
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164)
|
||||
.thenCompose(
|
||||
pni -> accountLockManager.withLockAsync(
|
||||
List.of(pni),
|
||||
() -> accounts.insertPniDeletedAccount(e164, pni, aci, expiration),
|
||||
accountLockExecutor));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> delete(final Account account, final DeletionReason deletionReason) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return accountLockManager.withLockAsync(List.of(account.getNumber()), () -> delete(account), accountLockExecutor)
|
||||
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()), () -> delete(account),
|
||||
accountLockExecutor)
|
||||
.whenComplete((ignored, throwable) -> {
|
||||
sample.stop(deleteTimer);
|
||||
|
||||
@@ -1240,7 +1279,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
|
||||
messagesManager.clear(account.getUuid()),
|
||||
profilesManager.deleteAll(account.getUuid()),
|
||||
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber()))
|
||||
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
|
||||
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
|
||||
.thenCompose(ignored -> redisDeleteAsync(account))
|
||||
.thenRun(() -> disconnectionRequestManager.requestDisconnection(account.getUuid()));
|
||||
@@ -1523,7 +1562,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return LINKED_DEVICE_PREFIX + linkDeviceTokenIdentifier;
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RemoteAttachment>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
|
||||
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
|
||||
final TimestampedDeviceIdentifier deviceIdentifier =
|
||||
new TimestampedDeviceIdentifier(account.getIdentifier(IdentityType.ACI),
|
||||
device.getId(),
|
||||
@@ -1539,14 +1578,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
public CompletableFuture<Void> recordTransferArchiveUpload(final Account account,
|
||||
final byte destinationDeviceId,
|
||||
final Instant destinationDeviceCreationTimestamp,
|
||||
final RemoteAttachment transferArchive) {
|
||||
final TransferArchiveResult transferArchiveResult) {
|
||||
|
||||
final String key = getTransferArchiveKey(account.getIdentifier(IdentityType.ACI),
|
||||
destinationDeviceId,
|
||||
destinationDeviceCreationTimestamp);
|
||||
|
||||
try {
|
||||
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchive);
|
||||
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
|
||||
|
||||
return pubSubRedisClient.withConnection(connection ->
|
||||
connection.async().set(key, transferArchiveJson, SetArgs.Builder.ex(RECENTLY_ADDED_TRANSFER_ARCHIVE_TTL)))
|
||||
@@ -1558,9 +1597,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
}
|
||||
|
||||
private void handleTransferArchiveAdded(final CompletableFuture<Optional<RemoteAttachment>> future, final String transferArchiveJson) {
|
||||
private void handleTransferArchiveAdded(final CompletableFuture<Optional<TransferArchiveResult>> future, final String transferArchiveJson) {
|
||||
try {
|
||||
future.complete(Optional.of(SystemMapper.jsonMapper().readValue(transferArchiveJson, RemoteAttachment.class)));
|
||||
future.complete(Optional.of(SystemMapper.jsonMapper().readValue(transferArchiveJson, TransferArchiveResult.class)));
|
||||
} catch (final JsonProcessingException e) {
|
||||
logger.error("Could not parse transfer archive json", e);
|
||||
future.completeExceptionally(e);
|
||||
|
||||
+2
-2
@@ -16,7 +16,6 @@ import org.apache.commons.lang3.ObjectUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
|
||||
@@ -29,7 +28,8 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
|
||||
public class ChangeNumberManager {
|
||||
private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
|
||||
private final MessageSender messageSender;
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ public class ClientPublicKeysManager {
|
||||
* @return a future that completes when the given key has been stored
|
||||
*/
|
||||
public CompletableFuture<Void> setPublicKey(final Account account, final byte deviceId, final ECPublicKey publicKey) {
|
||||
return accountLockManager.withLockAsync(List.of(account.getNumber()),
|
||||
return accountLockManager.withLockAsync(List.of(account.getPhoneNumberIdentifier()),
|
||||
() -> clientPublicKeys.setPublicKey(account.getIdentifier(IdentityType.ACI), deviceId, publicKey),
|
||||
accountLockExecutor);
|
||||
}
|
||||
|
||||
@@ -36,10 +36,7 @@ import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.Experiment;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -116,8 +113,6 @@ public class MessagesCache {
|
||||
// messageDeletionExecutorService wrapped into a reactor Scheduler
|
||||
private final Scheduler messageDeletionScheduler;
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private final MessagesCacheInsertScript insertScript;
|
||||
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
|
||||
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
|
||||
@@ -137,10 +132,8 @@ public class MessagesCache {
|
||||
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "staleEphemeralMessages"));
|
||||
private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved"));
|
||||
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = "mrmRetrievalError";
|
||||
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = name(MessagesCache.class, "mrmRetrievalError");
|
||||
private final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
private final Counter mrmPhaseTwoMissingContentCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "mrmPhaseTwoMissingContent"));
|
||||
private final Counter skippedStaleEphemeralMrmCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "skippedStaleEphemeralMrm"));
|
||||
private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter(
|
||||
@@ -149,8 +142,6 @@ public class MessagesCache {
|
||||
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
|
||||
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final String MRM_VIEWS_EXPERIMENT_NAME = "mrmViews";
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
|
||||
|
||||
@@ -164,8 +155,7 @@ public class MessagesCache {
|
||||
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService,
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager)
|
||||
final Clock clock)
|
||||
throws IOException {
|
||||
|
||||
this(
|
||||
@@ -173,7 +163,6 @@ public class MessagesCache {
|
||||
messageDeliveryScheduler,
|
||||
messageDeletionExecutorService,
|
||||
clock,
|
||||
dynamicConfigurationManager,
|
||||
new MessagesCacheInsertScript(redisCluster),
|
||||
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster),
|
||||
new MessagesCacheGetItemsScript(redisCluster),
|
||||
@@ -189,7 +178,6 @@ public class MessagesCache {
|
||||
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
@@ -205,8 +193,6 @@ public class MessagesCache {
|
||||
this.messageDeletionExecutorService = messageDeletionExecutorService;
|
||||
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
|
||||
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
|
||||
this.insertScript = insertScript;
|
||||
this.insertMrmScript = insertMrmScript;
|
||||
this.removeByGuidScript = removeByGuidScript;
|
||||
@@ -371,8 +357,6 @@ public class MessagesCache {
|
||||
messageMono = Mono.just(message.toBuilder().clearSharedMrmKey().build());
|
||||
skippedStaleEphemeralMrmCounter.increment();
|
||||
} else {
|
||||
// mrm views phase 3: fetch shared MRM data -- internally depends on dynamic config that
|
||||
// enables using it (the stored messages still always have `content` set upstream)
|
||||
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
|
||||
}
|
||||
|
||||
@@ -393,27 +377,18 @@ public class MessagesCache {
|
||||
|
||||
/**
|
||||
* Returns the given message with its shared MRM data.
|
||||
*
|
||||
* @see DynamicMessagesConfiguration#useSharedMrmData()
|
||||
*/
|
||||
private Mono<MessageProtos.Envelope> getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage,
|
||||
final byte destinationDevice) {
|
||||
|
||||
assert mrmMessage.hasSharedMrmKey();
|
||||
|
||||
// mrm views phase 2: messages have content
|
||||
if (!mrmMessage.hasContent()) {
|
||||
mrmPhaseTwoMissingContentCounter.increment();
|
||||
}
|
||||
|
||||
final Experiment experiment = new Experiment(MRM_VIEWS_EXPERIMENT_NAME);
|
||||
|
||||
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
|
||||
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
|
||||
// the message might be addressed to the account's PNI, so use the service ID from the envelope
|
||||
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
|
||||
|
||||
final Mono<MessageProtos.Envelope> messageFromRedisMono = Mono.from(redisCluster.withBinaryClusterReactive(
|
||||
return Mono.from(redisCluster.withBinaryClusterReactive(
|
||||
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
|
||||
.collectList()
|
||||
.publishOn(messageDeliveryScheduler)))
|
||||
@@ -444,18 +419,6 @@ public class MessagesCache {
|
||||
return Mono.empty();
|
||||
})
|
||||
.share();
|
||||
|
||||
if (mrmMessage.hasContent()) {
|
||||
experiment.compareMonoResult(mrmMessage.toBuilder().clearSharedMrmKey().build(), messageFromRedisMono);
|
||||
}
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagesConfiguration().useSharedMrmData()
|
||||
|| !mrmMessage.hasContent()) {
|
||||
return messageFromRedisMono;
|
||||
}
|
||||
|
||||
// if fetching or using shared data is disabled, fallback to just() with the existing message
|
||||
return Mono.just(mrmMessage.toBuilder().clearSharedMrmKey().build());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -529,8 +492,6 @@ public class MessagesCache {
|
||||
.concatMap(message -> {
|
||||
final Mono<MessageProtos.Envelope> messageMono;
|
||||
if (message.hasSharedMrmKey()) {
|
||||
// mrm views phase 2: fetch shared MRM data -- internally depends on dynamic config that
|
||||
// enables fetching and using it (the stored messages still always have `content` set upstream)
|
||||
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
|
||||
} else {
|
||||
messageMono = Mono.just(message);
|
||||
|
||||
+219
-70
@@ -10,18 +10,34 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuple2;
|
||||
import reactor.util.function.Tuples;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
|
||||
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
|
||||
/**
|
||||
* Manages a global, persistent mapping of phone numbers to phone number identifiers regardless of whether those
|
||||
@@ -29,7 +45,7 @@ import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
*/
|
||||
public class PhoneNumberIdentifiers {
|
||||
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final DynamoDbAsyncClient dynamoDbClient;
|
||||
private final String tableName;
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -39,81 +55,214 @@ public class PhoneNumberIdentifiers {
|
||||
@VisibleForTesting
|
||||
static final String ATTR_PHONE_NUMBER_IDENTIFIER = "PNI";
|
||||
|
||||
private static final String CONDITIONAL_CHECK_FAILED = "ConditionalCheckFailed";
|
||||
|
||||
private static final Timer GET_PNI_TIMER = Metrics.timer(name(PhoneNumberIdentifiers.class, "get"));
|
||||
private static final Timer SET_PNI_TIMER = Metrics.timer(name(PhoneNumberIdentifiers.class, "set"));
|
||||
private static final int MAX_RETRIES = 10;
|
||||
|
||||
public PhoneNumberIdentifiers(final DynamoDbClient dynamoDbClient, final String tableName) {
|
||||
private static final Logger logger = LoggerFactory.getLogger(PhoneNumberIdentifiers.class);
|
||||
|
||||
public PhoneNumberIdentifiers(final DynamoDbAsyncClient dynamoDbClient, final String tableName) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the phone number identifier (PNI) associated with the given phone number.
|
||||
* Returns the phone number identifier (PNI) associated with the given phone number. If one doesn't exist, it is
|
||||
* created.
|
||||
*
|
||||
* @param phoneNumber the phone number for which to retrieve a phone number identifier
|
||||
* @return the phone number identifier associated with the given phone number
|
||||
*/
|
||||
public UUID getPhoneNumberIdentifier(final String phoneNumber) {
|
||||
final GetItemResponse response = GET_PNI_TIMER.record(() -> dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
|
||||
.projectionExpression(ATTR_PHONE_NUMBER_IDENTIFIER)
|
||||
.build()));
|
||||
public CompletableFuture<UUID> getPhoneNumberIdentifier(final String phoneNumber) {
|
||||
// Each e164 phone number string represents a potential equivalence class e164s that represent the same number. If
|
||||
// this is a new phone number, we'll want to set all the numbers in the equivalence class to the same PNI
|
||||
final List<String> allPhoneNumberForms = Util.getAlternateForms(phoneNumber);
|
||||
|
||||
final UUID phoneNumberIdentifier;
|
||||
|
||||
if (response.hasItem()) {
|
||||
phoneNumberIdentifier = AttributeValues.getUUID(response.item(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
|
||||
} else {
|
||||
phoneNumberIdentifier = generatePhoneNumberIdentifierIfNotExists(phoneNumber);
|
||||
}
|
||||
|
||||
if (phoneNumberIdentifier == null) {
|
||||
throw new RuntimeException("Could not retrieve phone number identifier from stored item");
|
||||
}
|
||||
|
||||
return phoneNumberIdentifier;
|
||||
return retry(MAX_RETRIES, TransactionConflictException.class, () -> fetchPhoneNumbers(allPhoneNumberForms)
|
||||
.thenCompose(mappings -> setPniIfRequired(phoneNumber, allPhoneNumberForms, mappings)));
|
||||
}
|
||||
|
||||
public Optional<String> getPhoneNumber(final UUID phoneNumberIdentifier) {
|
||||
final QueryResponse response = dynamoDbClient.query(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.indexName(INDEX_NAME)
|
||||
.keyConditionExpression("#pni = :pni")
|
||||
.projectionExpression("#phone_number")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#phone_number", KEY_E164,
|
||||
"#pni", ATTR_PHONE_NUMBER_IDENTIFIER
|
||||
))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":pni", AttributeValues.fromUUID(phoneNumberIdentifier)
|
||||
))
|
||||
.build());
|
||||
|
||||
if (response.count() == 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (response.count() > 1) {
|
||||
throw new RuntimeException(
|
||||
"Impossible result: more than one phone number returned for PNI: " + phoneNumberIdentifier);
|
||||
}
|
||||
|
||||
return Optional.ofNullable(response.items().get(0).get(KEY_E164).s());
|
||||
}
|
||||
|
||||
|
||||
@VisibleForTesting
|
||||
UUID generatePhoneNumberIdentifierIfNotExists(final String phoneNumber) {
|
||||
final UpdateItemResponse response = SET_PNI_TIMER.record(() -> dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
|
||||
.updateExpression("SET #pni = if_not_exists(#pni, :pni)")
|
||||
.expressionAttributeNames(Map.of("#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
|
||||
.expressionAttributeValues(Map.of(":pni", AttributeValues.fromUUID(UUID.randomUUID())))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
.build()));
|
||||
|
||||
return AttributeValues.getUUID(response.attributes(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
|
||||
static <T, E extends Exception> CompletableFuture<T> retry(
|
||||
final int numRetries, final Class<E> exceptionToRetry, final Supplier<CompletableFuture<T>> supplier) {
|
||||
return supplier.get().exceptionallyCompose(ExceptionUtils.exceptionallyHandler(exceptionToRetry, e -> {
|
||||
if (numRetries - 1 <= 0) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
return retry(numRetries - 1, exceptionToRetry, supplier);
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine what PNI to set for the provided numbers, and set them if required
|
||||
*
|
||||
* @param phoneNumber The original e164 the operation is for
|
||||
* @param allPhoneNumberForms The e164s to set. The first e164 in this list should be phoneNumber
|
||||
* @param existingAssociations The current associations of allPhoneNumberForms in the table
|
||||
* @return The PNI now associated with phoneNumber
|
||||
*/
|
||||
@VisibleForTesting
|
||||
CompletableFuture<UUID> setPniIfRequired(
|
||||
final String phoneNumber,
|
||||
final List<String> allPhoneNumberForms,
|
||||
Map<String, UUID> existingAssociations) {
|
||||
if (!phoneNumber.equals(allPhoneNumberForms.getFirst())) {
|
||||
throw new IllegalArgumentException("allPhoneNumberForms must start with the target phoneNumber");
|
||||
}
|
||||
|
||||
if (existingAssociations.containsKey(phoneNumber)) {
|
||||
// If the provided phone number already has an association, just return that
|
||||
return CompletableFuture.completedFuture(existingAssociations.get(phoneNumber));
|
||||
}
|
||||
|
||||
if (allPhoneNumberForms.size() == 1 || existingAssociations.isEmpty()) {
|
||||
// Easy case, if we're the only phone number in our equivalence class or there are no existing associations,
|
||||
// we can just make an association for a new PNI
|
||||
return setPni(phoneNumber, allPhoneNumberForms, UUID.randomUUID());
|
||||
}
|
||||
|
||||
// Otherwise, what members of the equivalence class have a PNI association?
|
||||
final Map<UUID, List<String>> byPni = existingAssociations.entrySet().stream().collect(Collectors.groupingBy(
|
||||
Map.Entry::getValue,
|
||||
Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
|
||||
|
||||
// Usually there should be only a single PNI associated with the equivalence class, but it's possible there's
|
||||
// more. This could only happen if an equivalence class had more than two numbers, and had accumulated 2 unique
|
||||
// PNI associations before they were merged into a single class. In this case we've picked one of those pnis
|
||||
// arbitrarily (according to their ordering as returned by getAlternateForms)
|
||||
final UUID existingPni = allPhoneNumberForms.stream()
|
||||
.filter(existingAssociations::containsKey)
|
||||
.findFirst()
|
||||
.map(existingAssociations::get)
|
||||
.orElseThrow(() -> new IllegalStateException("Previously checked that a mapping existed"));
|
||||
|
||||
if (byPni.size() > 1) {
|
||||
logger.warn("More than one PNI existed in the PNI table for the numbers that map to {}. " +
|
||||
"Arbitrarily picking {} to be the representative PNI for the numbers without PNI associations",
|
||||
phoneNumber, existingPni);
|
||||
}
|
||||
|
||||
// Find all the unmapped phoneNumbers and set them to the PNI we chose from another member of the equivalence class
|
||||
final List<String> unmappedNumbers = allPhoneNumberForms.stream()
|
||||
.filter(number -> !existingAssociations.containsKey(number))
|
||||
.toList();
|
||||
|
||||
return setPni(phoneNumber, unmappedNumbers, existingPni);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Attempt to associate phoneNumbers with the provided pni. If any of the phoneNumbers have an existing association
|
||||
* that is not the target pni, no update will occur. If the first phoneNumber in phoneNumbers has an existing
|
||||
* association, it will be returned, otherwise an exception will be thrown.
|
||||
*
|
||||
* @param originalPhoneNumber The original e164 the operation is for
|
||||
* @param allPhoneNumberForms The e164s to set. The first e164 in this list should be originalPhoneNumber
|
||||
* @param pni The PNI to set
|
||||
* @return The provided PNI if the update occurred, or the existing PNI associated with originalPhoneNumber
|
||||
*/
|
||||
@VisibleForTesting
|
||||
CompletableFuture<UUID> setPni(final String originalPhoneNumber, final List<String> allPhoneNumberForms,
|
||||
final UUID pni) {
|
||||
if (!originalPhoneNumber.equals(allPhoneNumberForms.getFirst())) {
|
||||
throw new IllegalArgumentException("allPhoneNumberForms must start with the target phoneNumber");
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final List<TransactWriteItem> transactWriteItems = allPhoneNumberForms
|
||||
.stream()
|
||||
.map(phoneNumber -> TransactWriteItem.builder()
|
||||
.update(Update.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
|
||||
.updateExpression("SET #pni = :pni")
|
||||
// It's possible we're racing with someone else to update, but both of us selected the same PNI because
|
||||
// an equivalent number already had it. That's fine, as long as the association happens.
|
||||
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
|
||||
.expressionAttributeNames(Map.of("#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
|
||||
.expressionAttributeValues(Map.of(":pni", AttributeValues.fromUUID(pni)))
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.build()).build())
|
||||
.toList();
|
||||
|
||||
return dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
|
||||
.transactItems(transactWriteItems)
|
||||
.build())
|
||||
.thenApply(ignored -> pni)
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(TransactionCanceledException.class, e -> {
|
||||
if (e.hasCancellationReasons()) {
|
||||
// Get the cancellation reason for the number that we were primarily trying to associate with a PNI
|
||||
final CancellationReason cancelReason = e.cancellationReasons().getFirst();
|
||||
if (CONDITIONAL_CHECK_FAILED.equals(cancelReason.code())) {
|
||||
// Someone else beat us to the update, use the PNI they set.
|
||||
return AttributeValues.getUUID(cancelReason.item(), ATTR_PHONE_NUMBER_IDENTIFIER, null);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}))
|
||||
.whenComplete((ignored, throwable) -> sample.stop(SET_PNI_TIMER));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Map<String, UUID>> fetchPhoneNumbers(List<String> phoneNumbers) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
return dynamoDbClient.batchGetItem(
|
||||
BatchGetItemRequest.builder().requestItems(Map.of(tableName, KeysAndAttributes.builder()
|
||||
// If we have a stale value, the subsequent conditional update will fail
|
||||
.consistentRead(false)
|
||||
.projectionExpression("#number,#pni")
|
||||
.expressionAttributeNames(Map.of("#number", KEY_E164, "#pni", ATTR_PHONE_NUMBER_IDENTIFIER))
|
||||
.keys(phoneNumbers.stream()
|
||||
.map(number -> Map.of(KEY_E164, AttributeValues.fromString(number)))
|
||||
.toArray(Map[]::new))
|
||||
.build()))
|
||||
.build())
|
||||
.thenApply(batchResponse -> batchResponse.responses().get(tableName).stream().collect(Collectors.toMap(
|
||||
item -> AttributeValues.getString(item, KEY_E164, null),
|
||||
item -> AttributeValues.getUUID(item, ATTR_PHONE_NUMBER_IDENTIFIER, null))))
|
||||
.whenComplete((ignored, throwable) -> sample.stop(GET_PNI_TIMER));
|
||||
}
|
||||
|
||||
public Flux<Tuple2<String, UUID>> getPhoneNumberIdentifiers(final String prefix, final int segments,
|
||||
final Scheduler scheduler) {
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> dynamoDbClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.filterExpression("begins_with(#key, :e164Prefix)")
|
||||
.expressionAttributeNames(Map.of("#key", KEY_E164))
|
||||
.expressionAttributeValues(Map.of(":e164Prefix", AttributeValue.fromS(prefix)))
|
||||
.build())
|
||||
.items()
|
||||
.map(item -> Tuples.of(item.get(KEY_E164).s(),
|
||||
AttributeValues.getUUID(item, ATTR_PHONE_NUMBER_IDENTIFIER, null))))
|
||||
.sequential();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> backfillAlternatePhoneNumbers(final String e164, final UUID pni) {
|
||||
final List<String> alternateForms = new ArrayList<>(Util.getAlternateForms(e164));
|
||||
if (alternateForms.size() == 1) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
return retry(MAX_RETRIES, TransactionConflictException.class,
|
||||
() -> setPniIfRequired(e164, alternateForms, Map.of(e164, pni)))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(TransactionCanceledException.class, e -> {
|
||||
logger.error("Tried to backfill {} with pni: {}, but there were existing numbers with a different pni", e164,
|
||||
pni);
|
||||
throw e;
|
||||
}))
|
||||
.thenAccept(newPni -> {
|
||||
if (!newPni.equals(pni)) {
|
||||
logger.error("Tried to backfill {} with pni: {}, but there were existing numbers with pni: {}", pni,
|
||||
newPni);
|
||||
throw new IllegalArgumentException("Wrong PNI in backfill");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+70
-31
@@ -7,24 +7,33 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
|
||||
public class RegistrationRecoveryPasswords extends AbstractDynamoDbStore {
|
||||
public class RegistrationRecoveryPasswords {
|
||||
|
||||
static final String KEY_E164 = "P";
|
||||
// For historical reasons, we record the PNI as a UUID string rather than a compact byte array
|
||||
static final String KEY_PNI = "P";
|
||||
static final String ATTR_EXP = "E";
|
||||
static final String ATTR_SALT = "S";
|
||||
static final String ATTR_HASH = "H";
|
||||
@@ -40,62 +49,92 @@ public class RegistrationRecoveryPasswords extends AbstractDynamoDbStore {
|
||||
public RegistrationRecoveryPasswords(
|
||||
final String tableName,
|
||||
final Duration expiration,
|
||||
final DynamoDbClient dynamoDbClient,
|
||||
final DynamoDbAsyncClient asyncClient) {
|
||||
this(tableName, expiration, dynamoDbClient, asyncClient, Clock.systemUTC());
|
||||
}
|
||||
|
||||
RegistrationRecoveryPasswords(
|
||||
final String tableName,
|
||||
final Duration expiration,
|
||||
final DynamoDbClient dynamoDbClient,
|
||||
final DynamoDbAsyncClient asyncClient,
|
||||
final Clock clock) {
|
||||
super(dynamoDbClient);
|
||||
this.tableName = requireNonNull(tableName);
|
||||
this.expiration = requireNonNull(expiration);
|
||||
this.asyncClient = requireNonNull(asyncClient);
|
||||
this.clock = requireNonNull(clock);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final String number) {
|
||||
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final UUID phoneNumberIdentifier) {
|
||||
return asyncClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.thenApply(getItemResponse -> {
|
||||
final Map<String, AttributeValue> item = getItemResponse.item();
|
||||
if (item == null || !item.containsKey(ATTR_SALT) || !item.containsKey(ATTR_HASH)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
final String salt = item.get(ATTR_SALT).s();
|
||||
final String hash = item.get(ATTR_HASH).s();
|
||||
return Optional.of(new SaltedTokenHash(hash, salt));
|
||||
});
|
||||
.build())
|
||||
.thenApply(getItemResponse -> Optional.ofNullable(getItemResponse.item())
|
||||
.filter(item -> item.containsKey(ATTR_SALT))
|
||||
.filter(item -> item.containsKey(ATTR_HASH))
|
||||
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> addOrReplace(final String number, final SaltedTokenHash data) {
|
||||
public CompletableFuture<Void> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
|
||||
final long expirationSeconds = expirationSeconds();
|
||||
|
||||
return asyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_E164, AttributeValues.fromString(number),
|
||||
ATTR_EXP, AttributeValues.fromLong(expirationSeconds()),
|
||||
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
|
||||
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
|
||||
ATTR_SALT, AttributeValues.fromString(data.salt()),
|
||||
ATTR_HASH, AttributeValues.fromString(data.hash())))
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> removeEntry(final String number) {
|
||||
CompletableFuture<Void> removeEntry(final String number) {
|
||||
return asyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(number)))
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
private long expirationSeconds() {
|
||||
public CompletableFuture<Void> removeEntry(final UUID phoneNumberIdentifier) {
|
||||
return asyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
long expirationSeconds() {
|
||||
return clock.instant().plus(expiration).getEpochSecond();
|
||||
}
|
||||
|
||||
Flux<String> getE164sWithRegistrationRecoveryPasswords(final int segments, final int bufferSize, final Scheduler scheduler) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> asyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.filterExpression("begins_with(#key, :e164Prefix)")
|
||||
.expressionAttributeNames(Map.of("#key", KEY_PNI))
|
||||
.expressionAttributeValues(Map.of(":e164Prefix", AttributeValue.fromS("+")))
|
||||
.build())
|
||||
.items()
|
||||
.map(item -> item.get(KEY_PNI).s()))
|
||||
.sequential()
|
||||
.buffer(bufferSize)
|
||||
.map(source -> {
|
||||
final List<String> shuffled = new ArrayList<>(source);
|
||||
Collections.shuffle(shuffled);
|
||||
return shuffled;
|
||||
})
|
||||
.limitRate(2)
|
||||
.flatMapIterable(Function.identity());
|
||||
}
|
||||
|
||||
private static SaltedTokenHash saltedTokenHashFromItem(final Map<String, AttributeValue> item) {
|
||||
return new SaltedTokenHash(item.get(ATTR_HASH).s(), item.get(ATTR_SALT).s());
|
||||
}
|
||||
}
|
||||
+25
-8
@@ -10,10 +10,13 @@ import static java.util.Objects.requireNonNull;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
|
||||
|
||||
public class RegistrationRecoveryPasswordsManager {
|
||||
@@ -22,13 +25,12 @@ public class RegistrationRecoveryPasswordsManager {
|
||||
|
||||
private final RegistrationRecoveryPasswords registrationRecoveryPasswords;
|
||||
|
||||
|
||||
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords) {
|
||||
this.registrationRecoveryPasswords = requireNonNull(registrationRecoveryPasswords);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> verify(final String number, final byte[] password) {
|
||||
return registrationRecoveryPasswords.lookup(number)
|
||||
public CompletableFuture<Boolean> verify(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
return registrationRecoveryPasswords.lookup(phoneNumberIdentifier)
|
||||
.thenApply(maybeHash -> maybeHash.filter(hash -> hash.verify(bytesToString(password))))
|
||||
.whenComplete((result, error) -> {
|
||||
if (error != null) {
|
||||
@@ -38,10 +40,11 @@ public class RegistrationRecoveryPasswordsManager {
|
||||
.thenApply(Optional::isPresent);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> storeForCurrentNumber(final String number, final byte[] password) {
|
||||
public CompletableFuture<Void> store(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
final String token = bytesToString(password);
|
||||
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
|
||||
return registrationRecoveryPasswords.addOrReplace(number, tokenHash)
|
||||
|
||||
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash)
|
||||
.whenComplete((result, error) -> {
|
||||
if (error != null) {
|
||||
logger.warn("Failed to store Registration Recovery Password", error);
|
||||
@@ -49,9 +52,7 @@ public class RegistrationRecoveryPasswordsManager {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> removeForNumber(final String number) {
|
||||
// remove is a "fire-and-forget" operation,
|
||||
// there is no action to be taken on its completion
|
||||
public CompletableFuture<Void> removeForE164(final String number) {
|
||||
return registrationRecoveryPasswords.removeEntry(number)
|
||||
.whenComplete((ignored, error) -> {
|
||||
if (error instanceof ResourceNotFoundException) {
|
||||
@@ -63,6 +64,22 @@ public class RegistrationRecoveryPasswordsManager {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> remove(final UUID phoneNumberIdentifier) {
|
||||
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier)
|
||||
.whenComplete((ignored, error) -> {
|
||||
if (error instanceof ResourceNotFoundException) {
|
||||
// These will naturally happen if a recovery password is already deleted. Since we can remove
|
||||
// the recovery password through many flows, we avoid creating log messages for these exceptions
|
||||
} else if (error != null) {
|
||||
logger.warn("Failed to remove Registration Recovery Password", error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Flux<String> getE164sWithRegistrationRecoveryPasswords(final int segments, final int bufferSize, final Scheduler scheduler) {
|
||||
return registrationRecoveryPasswords.getE164sWithRegistrationRecoveryPasswords(segments, bufferSize, scheduler);
|
||||
}
|
||||
|
||||
private static String bytesToString(final byte[] bytes) {
|
||||
return HexFormat.of().formatHex(bytes);
|
||||
}
|
||||
|
||||
+47
-24
@@ -453,7 +453,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
// not prorated. Braintree subscriptions cannot change their next billing date,
|
||||
// so we must end the existing one and create a new one
|
||||
return cancelSubscriptionAtEndOfCurrentPeriod(subscription)
|
||||
return endSubscription(subscription)
|
||||
.thenCompose(ignored -> {
|
||||
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
@@ -504,19 +504,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
final Instant anchor = subscription.getFirstBillingDate().toInstant();
|
||||
final Instant endOfCurrentPeriod = subscription.getBillingPeriodEndDate().toInstant();
|
||||
|
||||
boolean paymentProcessing = false;
|
||||
ChargeFailure chargeFailure = null;
|
||||
|
||||
final Optional<Transaction> latestTransaction = getLatestTransactionForSubscription(subscription);
|
||||
|
||||
boolean latestTransactionFailed = false;
|
||||
if (latestTransaction.isPresent()){
|
||||
paymentProcessing = isPaymentProcessing(latestTransaction.get().getStatus());
|
||||
if (getPaymentStatus(latestTransaction.get().getStatus()) != PaymentStatus.SUCCEEDED) {
|
||||
latestTransactionFailed = true;
|
||||
chargeFailure = createChargeFailure(latestTransaction.get());
|
||||
}
|
||||
}
|
||||
final TransactionInfo latestTransactionInfo = getLatestTransactionForSubscription(subscription)
|
||||
.map(this::getTransactionInfo)
|
||||
.orElse(new TransactionInfo(PaymentMethod.PAYPAL, false, false, null));
|
||||
|
||||
return new SubscriptionInformation(
|
||||
new SubscriptionPrice(plan.getCurrencyIsoCode().toUpperCase(Locale.ROOT),
|
||||
@@ -526,16 +516,31 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
endOfCurrentPeriod,
|
||||
Subscription.Status.ACTIVE == subscription.getStatus(),
|
||||
!subscription.neverExpires(),
|
||||
getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed),
|
||||
getSubscriptionStatus(subscription.getStatus(), latestTransactionInfo.transactionFailed()),
|
||||
PaymentProvider.BRAINTREE,
|
||||
latestTransaction.map(this::getPaymentMethodFromTransaction).orElse(PaymentMethod.PAYPAL),
|
||||
paymentProcessing,
|
||||
chargeFailure
|
||||
latestTransactionInfo.paymentMethod(),
|
||||
latestTransactionInfo.paymentProcessing(),
|
||||
latestTransactionInfo.chargeFailure()
|
||||
);
|
||||
|
||||
}, executor);
|
||||
}
|
||||
|
||||
private record TransactionInfo(
|
||||
PaymentMethod paymentMethod,
|
||||
boolean paymentProcessing,
|
||||
boolean transactionFailed,
|
||||
@Nullable ChargeFailure chargeFailure) {}
|
||||
|
||||
private TransactionInfo getTransactionInfo(final Transaction transaction) {
|
||||
final boolean paymentProcessing = isPaymentProcessing(transaction.getStatus());
|
||||
final PaymentMethod paymentMethod = getPaymentMethodFromTransaction(transaction);
|
||||
if (getPaymentStatus(transaction.getStatus()) != PaymentStatus.SUCCEEDED) {
|
||||
return new TransactionInfo(paymentMethod, paymentProcessing, true, createChargeFailure(transaction));
|
||||
}
|
||||
return new TransactionInfo(paymentMethod, paymentProcessing, false, null);
|
||||
}
|
||||
|
||||
private PaymentMethod getPaymentMethodFromTransaction(Transaction transaction) {
|
||||
if (transaction.getPayPalDetails() != null) {
|
||||
return PaymentMethod.PAYPAL;
|
||||
@@ -583,19 +588,37 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
.map(com.braintreegateway.PaymentMethod::getSubscriptions)
|
||||
.orElse(Collections.emptyList())
|
||||
.stream()
|
||||
.map(this::cancelSubscriptionAtEndOfCurrentPeriod)
|
||||
.map(this::endSubscription)
|
||||
.toList();
|
||||
|
||||
return CompletableFuture.allOf(subscriptionCancelFutures.toArray(new CompletableFuture[0]));
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> endSubscription(Subscription subscription) {
|
||||
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
|
||||
.map(this::getTransactionInfo)
|
||||
.map(TransactionInfo::transactionFailed)
|
||||
.orElse(false);
|
||||
return switch (getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed)) {
|
||||
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
|
||||
// going through.
|
||||
case INCOMPLETE, PAST_DUE, UNPAID -> cancelSubscriptionImmediately(subscription);
|
||||
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
|
||||
// continue to be used until the end of the period.
|
||||
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
|
||||
};
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
braintreeGateway.subscription().update(subscription.getId(),
|
||||
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
|
||||
return null;
|
||||
}, executor);
|
||||
return CompletableFuture.runAsync(() -> braintreeGateway
|
||||
.subscription()
|
||||
.update(subscription.getId(),
|
||||
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle())), executor);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> cancelSubscriptionImmediately(Subscription subscription) {
|
||||
return CompletableFuture.runAsync(() -> braintreeGateway.subscription().cancel(subscription.getId()), executor);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+15
-3
@@ -385,7 +385,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}).thenCompose(subscriptions -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
|
||||
.map(this::cancelSubscriptionAtEndOfCurrentPeriod).toArray(CompletableFuture[]::new);
|
||||
.map(this::endSubscription).toArray(CompletableFuture[]::new);
|
||||
return CompletableFuture.allOf(futures);
|
||||
});
|
||||
}
|
||||
@@ -404,7 +404,19 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}, executor);
|
||||
}
|
||||
|
||||
public CompletableFuture<Subscription> cancelSubscriptionImmediately(Subscription subscription) {
|
||||
private CompletableFuture<Subscription> endSubscription(Subscription subscription) {
|
||||
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
|
||||
return switch (status) {
|
||||
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
|
||||
// going through.
|
||||
case UNPAID, PAST_DUE, INCOMPLETE -> cancelSubscriptionImmediately(subscription);
|
||||
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
|
||||
// continue to be used until the end of the period.
|
||||
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
|
||||
};
|
||||
}
|
||||
|
||||
private CompletableFuture<Subscription> cancelSubscriptionImmediately(Subscription subscription) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
try {
|
||||
@@ -415,7 +427,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}, executor);
|
||||
}
|
||||
|
||||
public CompletableFuture<Subscription> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
private CompletableFuture<Subscription> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.setCancelAtPeriodEnd(true)
|
||||
|
||||
@@ -24,15 +24,11 @@ import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class Util {
|
||||
|
||||
private static final RandomGenerator rng = new Random();
|
||||
|
||||
private static final Pattern COUNTRY_CODE_PATTERN = Pattern.compile("^\\+([17]|2[07]|3[0123469]|4[013456789]|5[12345678]|6[0123456]|8[1246]|9[0123458]|\\d{3})");
|
||||
private static final RandomGenerator RANDOM_GENERATOR = new Random();
|
||||
|
||||
private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();
|
||||
|
||||
@@ -89,10 +85,11 @@ public class Util {
|
||||
}
|
||||
|
||||
public static String getCountryCode(String number) {
|
||||
Matcher matcher = COUNTRY_CODE_PATTERN.matcher(number);
|
||||
|
||||
if (matcher.find()) return matcher.group(1);
|
||||
else return "0";
|
||||
try {
|
||||
return String.valueOf(PHONE_NUMBER_UTIL.parse(number, null).getCountryCode());
|
||||
} catch (final NumberParseException e) {
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
public static String getRegion(final String number) {
|
||||
@@ -104,12 +101,77 @@ public class Util {
|
||||
}
|
||||
}
|
||||
|
||||
public static String getNumberPrefix(String number) {
|
||||
String countryCode = getCountryCode(number);
|
||||
int remaining = number.length() - (1 + countryCode.length());
|
||||
int prefixLength = Math.min(4, remaining);
|
||||
/**
|
||||
* Returns a list of equivalent phone numbers to the given phone number. This is useful in cases where a numbering
|
||||
* authority has changed the numbering format for a region or in cases where multiple formats of a number may be valid
|
||||
* in different circumstances. Numbers are considered equivalent if a call/message sent to each number will generally
|
||||
* arrive at the same device.
|
||||
*
|
||||
* @apiNote This method is intended to support number format transitions in cases where we do not already have
|
||||
* multiple accounts registered with different forms of the same number. As a result, this method does not cover all
|
||||
* possible cases of equivalent formats, but instead focuses on the cases where we can and choose to prevent multiple
|
||||
* accounts from using different formats of the same number.
|
||||
*
|
||||
* @param number the e164-formatted phone number for which to find equivalent forms
|
||||
*
|
||||
* @return a list of phone numbers equivalent to the given phone number, including the given number. The given number
|
||||
* will always be the first element of the list.
|
||||
*/
|
||||
public static List<String> getAlternateForms(final String number) {
|
||||
try {
|
||||
final PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(number, null);
|
||||
|
||||
return number.substring(0, 1 + countryCode.length() + prefixLength);
|
||||
// Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024
|
||||
if ("BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber))) {
|
||||
final String nationalSignificantNumber = PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
|
||||
final String alternateE164;
|
||||
|
||||
if (nationalSignificantNumber.length() == 10) {
|
||||
// This is a new-format number; we can get the old-format version by stripping the leading "01" from the
|
||||
// national number
|
||||
alternateE164 = "+229" + StringUtils.removeStart(nationalSignificantNumber, "01");
|
||||
} else {
|
||||
// This is an old-format number; we can get the new-format version by adding a "01" prefix to the national
|
||||
// number
|
||||
alternateE164 = "+22901" + nationalSignificantNumber;
|
||||
}
|
||||
|
||||
return List.of(number, alternateE164);
|
||||
}
|
||||
|
||||
return List.of(number);
|
||||
} catch (final NumberParseException e) {
|
||||
return List.of(number);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether the decimal form of the given number (without leading zeroes) begins with the decimal form of the
|
||||
* given prefix (without leading zeroes).
|
||||
*
|
||||
* @param number the number to check for the given prefix
|
||||
* @param prefix the prefix
|
||||
*
|
||||
* @return {@code true} if the given number starts with the given prefix or {@code false} otherwise
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code number} is negative or if {@code prefix} is zero or negative
|
||||
*/
|
||||
public static boolean startsWithDecimal(final long number, final long prefix) {
|
||||
if (number < 0) {
|
||||
throw new IllegalArgumentException("Number must be non-negative");
|
||||
}
|
||||
|
||||
if (prefix <= 0) {
|
||||
throw new IllegalArgumentException("Prefix must be positive");
|
||||
}
|
||||
|
||||
long workingCopy = number;
|
||||
|
||||
while (workingCopy > prefix) {
|
||||
workingCopy /= 10;
|
||||
}
|
||||
|
||||
return workingCopy == prefix;
|
||||
}
|
||||
|
||||
public static byte[] truncate(byte[] element, int length) {
|
||||
@@ -122,7 +184,8 @@ public class Util {
|
||||
public static void sleep(long i) {
|
||||
try {
|
||||
Thread.sleep(i);
|
||||
} catch (InterruptedException ie) {}
|
||||
} catch (final InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public static long todayInMillis() {
|
||||
@@ -196,8 +259,8 @@ public class Util {
|
||||
return values;
|
||||
}
|
||||
|
||||
Set<Integer> indices = new HashSet<>(rng.ints(0, values.size()).distinct().limit(n).boxed().toList());
|
||||
List<E> result = new ArrayList<E>(n);
|
||||
Set<Integer> indices = new HashSet<>(RANDOM_GENERATOR.ints(0, values.size()).distinct().limit(n).boxed().toList());
|
||||
List<E> result = new ArrayList<>(n);
|
||||
for(int i = 0; i < values.size() && result.size() < n; i++) {
|
||||
if(indices.contains(i)) {
|
||||
result.add(values.get(i));
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.function.Tuple2;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class BackfillBeninPhoneNumberFormsCommand extends AbstractCommandWithDependencies {
|
||||
private static final String BENIN_PREFIX = "+229";
|
||||
private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();
|
||||
|
||||
private static final String SEGMENT_COUNT_ARGUMENT = "segments";
|
||||
private static final String PREFIX_ARGUMENT = "prefix";
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
private static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
private static final String BUFFER_ARGUMENT = "buffer";
|
||||
|
||||
private static final String PHONE_NUMBERS_INSPECTED = MetricsUtil.name(BackfillBeninPhoneNumberFormsCommand.class, "phoneNumbersInspected");
|
||||
private static final String PHONE_NUMBERS_BACKFILLED = MetricsUtil.name(BackfillBeninPhoneNumberFormsCommand.class, "phoneNumbersBackfilled");
|
||||
private static final String DRY_RUN_TAG = "dryRun";
|
||||
private static final String IS_OLD_FORMAT_TAG = "oldFormat";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BackfillBeninPhoneNumberFormsCommand.class);
|
||||
|
||||
public BackfillBeninPhoneNumberFormsCommand() {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration whisperServerConfiguration, final Environment environment)
|
||||
throws Exception {
|
||||
|
||||
}
|
||||
}, "backfill-alternate-phone-number-forms", "Inserts alternate forms of existing phone numbers");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--segments")
|
||||
.type(Integer.class)
|
||||
.dest(SEGMENT_COUNT_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(1)
|
||||
.help("The total number of segments for a DynamoDB scan");
|
||||
|
||||
subparser.addArgument("--prefix")
|
||||
.type(String.class)
|
||||
.dest(PREFIX_ARGUMENT)
|
||||
.required(true)
|
||||
.help("The phone number prefix (including +) to filter by");
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(16)
|
||||
.help("Max concurrency for backfilling PNI for alternate phone number forms");
|
||||
|
||||
subparser.addArgument("--buffer")
|
||||
.type(Integer.class)
|
||||
.dest(BUFFER_ARGUMENT)
|
||||
.setDefault(16_384)
|
||||
.help("Records to buffer");
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don’t actually insert any new PNI records");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
final int segments = namespace.getInt(SEGMENT_COUNT_ARGUMENT);
|
||||
final int concurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final int bufferSize = namespace.getInt(BUFFER_ARGUMENT);
|
||||
final boolean dryRun = namespace.getBoolean(DRY_RUN_ARGUMENT);
|
||||
|
||||
final Counter phoneNumbersInspectedCounter =
|
||||
Metrics.counter(PHONE_NUMBERS_INSPECTED, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final Counter phoneNumbersBackfilledCounter =
|
||||
Metrics.counter(PHONE_NUMBERS_BACKFILLED, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = commandDependencies.phoneNumberIdentifiers();
|
||||
|
||||
phoneNumberIdentifiers.getPhoneNumberIdentifiers(BENIN_PREFIX, segments, Schedulers.parallel())
|
||||
.doOnNext(ignored -> phoneNumbersInspectedCounter.increment())
|
||||
.buffer(bufferSize)
|
||||
.map(source -> {
|
||||
final ArrayList<Tuple2<String, UUID>> shuffled = new ArrayList<>(source);
|
||||
Collections.shuffle(shuffled);
|
||||
return shuffled;
|
||||
})
|
||||
.limitRate(2)
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(tuple -> {
|
||||
final String e164 = tuple.getT1();
|
||||
final UUID pni = tuple.getT2();
|
||||
|
||||
final boolean isNew = isNewFormatBeninNumber(e164);
|
||||
Metrics.counter(PHONE_NUMBERS_INSPECTED,
|
||||
DRY_RUN_TAG, String.valueOf(dryRun),
|
||||
IS_OLD_FORMAT_TAG, String.valueOf(!isNew));
|
||||
|
||||
if (isNew) {
|
||||
// only old format numbers need to be backfilled
|
||||
return Mono.just(false);
|
||||
}
|
||||
|
||||
return dryRun
|
||||
? Mono.just(true)
|
||||
: Mono.fromFuture( () ->
|
||||
phoneNumberIdentifiers.backfillAlternatePhoneNumbers(e164, pni).thenApply(ignored -> true))
|
||||
.onErrorResume(t -> {
|
||||
logger.warn("Failed to insert PNI for alternate forms of number {}", e164, t);
|
||||
return Mono.just(false);
|
||||
});
|
||||
}, concurrency)
|
||||
.filter(succeeded -> succeeded)
|
||||
.doOnNext(ignored -> phoneNumbersBackfilledCounter.increment())
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
private static boolean isNewFormatBeninNumber(final String number) {
|
||||
final Phonenumber.PhoneNumber phoneNumber;
|
||||
try {
|
||||
phoneNumber = PHONE_NUMBER_UTIL.parse(number, null);
|
||||
if ("BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber))) {
|
||||
final String nationalSignificantNumber = PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
|
||||
return nationalSignificantNumber.length() == 10 && nationalSignificantNumber.startsWith("01");
|
||||
}
|
||||
} catch (NumberParseException e) {
|
||||
logger.error("Failed to parse benin phone number {}", number);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+12
-10
@@ -78,6 +78,7 @@ record CommandDependencies(
|
||||
MessagesCache messagesCache,
|
||||
MessagesManager messagesManager,
|
||||
KeysManager keysManager,
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
APNSender apnSender,
|
||||
FcmSender fcmSender,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
@@ -87,7 +88,8 @@ record CommandDependencies(
|
||||
ClientResources.Builder redisClusterClientResourcesBuilder,
|
||||
BackupManager backupManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient) {
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers) {
|
||||
|
||||
static CommandDependencies build(
|
||||
final String name,
|
||||
@@ -166,12 +168,8 @@ record CommandDependencies(
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient
|
||||
);
|
||||
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = new RegistrationRecoveryPasswordsManager(
|
||||
registrationRecoveryPasswords);
|
||||
dynamoDbAsyncClient,
|
||||
clock);
|
||||
|
||||
ClientPublicKeys clientPublicKeys =
|
||||
new ClientPublicKeys(dynamoDbAsyncClient, configuration.getDynamoDbTables().getClientPublicKeys().getTableName());
|
||||
@@ -185,7 +183,7 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getAccounts().getUsernamesTableName(),
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName(),
|
||||
configuration.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfiles().getTableName());
|
||||
@@ -212,7 +210,7 @@ record CommandDependencies(
|
||||
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster,
|
||||
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
@@ -225,6 +223,8 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
@@ -278,6 +278,7 @@ record CommandDependencies(
|
||||
messagesCache,
|
||||
messagesManager,
|
||||
keys,
|
||||
registrationRecoveryPasswordsManager,
|
||||
apnSender,
|
||||
fcmSender,
|
||||
pushNotificationManager,
|
||||
@@ -287,7 +288,8 @@ record CommandDependencies(
|
||||
redisClientResourcesBuilder,
|
||||
backupManager,
|
||||
dynamicConfigurationManager,
|
||||
dynamoDbAsyncClient
|
||||
dynamoDbAsyncClient,
|
||||
phoneNumberIdentifiers
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class DeleteE164RegistrationRecoveryPasswordsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
private static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
private static final String SEGMENTS_ARGUMENT = "segments";
|
||||
private static final String BUFFER_ARGUMENT = "buffer";
|
||||
|
||||
private static final String RECORDS_INSPECTED_COUNTER_NAME =
|
||||
MetricsUtil.name(DeleteE164RegistrationRecoveryPasswordsCommand.class, "recordsInspected");
|
||||
|
||||
private static final String RECORDS_DELETED_COUNTER_NAME =
|
||||
MetricsUtil.name(DeleteE164RegistrationRecoveryPasswordsCommand.class, "recordsDeleted");
|
||||
|
||||
private static final String DRY_RUN_TAG = "dryRun";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DeleteE164RegistrationRecoveryPasswordsCommand.class);
|
||||
|
||||
public DeleteE164RegistrationRecoveryPasswordsCommand() {
|
||||
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "delete-e164-registration-recovery-passwords", "Delete e164-associated registration recovery passwords");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don’t actually delete any registration recovery passwords");
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(16)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--segments")
|
||||
.type(Integer.class)
|
||||
.dest(SEGMENTS_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(1)
|
||||
.help("The total number of segments for a DynamoDB scan");
|
||||
|
||||
subparser.addArgument("--buffer")
|
||||
.type(Integer.class)
|
||||
.dest(BUFFER_ARGUMENT)
|
||||
.setDefault(16_384)
|
||||
.help("Records to buffer");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
|
||||
final boolean dryRun = namespace.getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final int segments = namespace.getInt(SEGMENTS_ARGUMENT);
|
||||
final int bufferSize = namespace.getInt(BUFFER_ARGUMENT);
|
||||
|
||||
final Counter recordsInspectedCounter =
|
||||
Metrics.counter(RECORDS_INSPECTED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final Counter recordsDeletedCounter =
|
||||
Metrics.counter(RECORDS_DELETED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
commandDependencies.registrationRecoveryPasswordsManager();
|
||||
|
||||
registrationRecoveryPasswordsManager.getE164sWithRegistrationRecoveryPasswords(segments, bufferSize, Schedulers.parallel())
|
||||
.doOnNext(e164 -> recordsInspectedCounter.increment())
|
||||
.flatMap(e164 -> {
|
||||
final Mono<Void> deleteMono = dryRun
|
||||
? Mono.empty()
|
||||
: Mono.fromFuture(() -> registrationRecoveryPasswordsManager.removeForE164(e164))
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to migrate record for {}", e164, throwable);
|
||||
return Mono.empty();
|
||||
});
|
||||
|
||||
return deleteMono.doOnSuccess(ignored -> recordsDeletedCounter.increment());
|
||||
}, maxConcurrency)
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.retry.Retry;
|
||||
import java.time.Duration;
|
||||
|
||||
public class MigrateDeletedAccountsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private static final String RECORDS_INSPECTED_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateDeletedAccountsCommand.class, "recordsInspected");
|
||||
|
||||
private static final String RECORDS_MIGRATED_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateDeletedAccountsCommand.class, "recordsMigrated");
|
||||
|
||||
private static final String DRY_RUN_TAG = "dryRun";
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private static final String SEGMENT_COUNT_ARGUMENT = "segments";
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
private static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
private static final int DEFAULT_SEGMENT_COUNT = 1;
|
||||
private static final int DEFAULT_CONCURRENCY = 16;
|
||||
|
||||
public MigrateDeletedAccountsCommand() {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "migrate-deleted-accounts", "Migrates recently-deleted account records from E164 to PNI-keyed schema");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--segments")
|
||||
.type(Integer.class)
|
||||
.dest(SEGMENT_COUNT_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_SEGMENT_COUNT)
|
||||
.help("The total number of segments for a DynamoDB scan");
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_CONCURRENCY)
|
||||
.help("Max concurrency for migrations.");
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don’t actually migrate any deleted accounts records");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
final int segments = namespace.getInt(SEGMENT_COUNT_ARGUMENT);
|
||||
final int concurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final boolean dryRun = namespace.getBoolean(DRY_RUN_ARGUMENT);
|
||||
|
||||
logger.info("Crawling deleted accounts with {} segments and {} processors",
|
||||
segments,
|
||||
Runtime.getRuntime().availableProcessors());
|
||||
|
||||
final Counter recordsInspectedCounter =
|
||||
Metrics.counter(RECORDS_INSPECTED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final Counter recordsMigratedCounter =
|
||||
Metrics.counter(RECORDS_MIGRATED_COUNTER_NAME, DRY_RUN_TAG, String.valueOf(dryRun));
|
||||
|
||||
final AccountsManager accounts = commandDependencies.accountsManager();
|
||||
|
||||
accounts.getE164KeyedDeletedAccounts(segments, Schedulers.parallel())
|
||||
.doOnNext(tuple -> recordsInspectedCounter.increment())
|
||||
.flatMap(
|
||||
tuple -> dryRun
|
||||
? Mono.just(false)
|
||||
: Mono.fromFuture(
|
||||
accounts.migrateDeletedAccount(
|
||||
tuple.getT1(), tuple.getT2(), tuple.getT3()))
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to migrate record for {}", tuple.getT1(), throwable);
|
||||
return Mono.empty();
|
||||
}),
|
||||
concurrency)
|
||||
.filter(migrated -> migrated)
|
||||
.doOnNext(ignored -> recordsMigratedCounter.increment())
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -64,14 +64,14 @@ public class BufferingInterceptorIntegrationTest {
|
||||
@Path("/virtual/{size}")
|
||||
@ManagedAsync
|
||||
public String getVirtual(@PathParam("size") int size) {
|
||||
return RandomStringUtils.randomAscii(size);
|
||||
return RandomStringUtils.secure().nextAscii(size);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/platform/{size}")
|
||||
public String getPlatform(@PathParam("size") int size) {
|
||||
return RandomStringUtils.randomAscii(size);
|
||||
return RandomStringUtils.secure().nextAscii(size);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -123,7 +123,7 @@ public class WebsocketResourceProviderIntegrationTest {
|
||||
@Path("/{size}")
|
||||
@ManagedAsync
|
||||
public String get(@PathParam("size") int size) {
|
||||
return RandomStringUtils.randomAscii(size);
|
||||
return RandomStringUtils.secure().nextAscii(size);
|
||||
}
|
||||
|
||||
@PUT
|
||||
|
||||
@@ -51,7 +51,7 @@ class OptionalAccessTest {
|
||||
}
|
||||
|
||||
private static List<Arguments> verify() {
|
||||
final String unidentifiedAccessKey = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String unidentifiedAccessKey = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
final Anonymous correctUakHeader =
|
||||
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey.getBytes()));
|
||||
@@ -180,7 +180,7 @@ class OptionalAccessTest {
|
||||
|
||||
@Test
|
||||
void testTargetIdentifierIllegalArgument() {
|
||||
final String unidentifiedAccessKey = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String unidentifiedAccessKey = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
final Anonymous correctUakHeader =
|
||||
new Anonymous(Base64.getEncoder().encodeToString(unidentifiedAccessKey.getBytes()));
|
||||
|
||||
+12
-8
@@ -31,11 +31,11 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -53,7 +53,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
ExternalServiceCredentialsGenerator.class);
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
|
||||
RegistrationRecoveryPasswordsManager.class);
|
||||
private static PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
private final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator,
|
||||
@@ -103,14 +103,15 @@ class RegistrationLockVerificationManagerTest {
|
||||
if (e instanceof WebApplicationException wae) {
|
||||
assertEquals(RegistrationLockVerificationManager.FAILURE_HTTP_STATUS, wae.getResponse().getStatus());
|
||||
if (!verificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
|
||||
verify(registrationRecoveryPasswordsManager).removeForNumber(account.getNumber());
|
||||
verify(registrationRecoveryPasswordsManager).remove(account.getIdentifier(IdentityType.PNI));
|
||||
} else {
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
verify(registrationRecoveryPasswordsManager, never()).remove(any());
|
||||
}
|
||||
verify(disconnectionRequestManager).requestDisconnection(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
try {
|
||||
verify(pushNotificationManager).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
|
||||
} catch (NotPushRegisteredException npre) {}
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
if (alreadyLocked) {
|
||||
verify(account, never()).lockAuthTokenHash();
|
||||
} else {
|
||||
@@ -126,10 +127,13 @@ class RegistrationLockVerificationManagerTest {
|
||||
doThrow(RateLimitExceededException.class).when(pinLimiter).validate(anyString());
|
||||
yield new Pair<>(RateLimitExceededException.class, ignored -> {
|
||||
verify(account, never()).lockAuthTokenHash();
|
||||
|
||||
try {
|
||||
verify(pushNotificationManager, never()).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
|
||||
} catch (NotPushRegisteredException npre) {}
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
} catch (final NotPushRegisteredException ignored2) {
|
||||
}
|
||||
|
||||
verify(registrationRecoveryPasswordsManager, never()).remove(any());
|
||||
verify(disconnectionRequestManager, never()).requestDisconnection(any(), any());
|
||||
});
|
||||
}
|
||||
@@ -167,7 +171,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
PhoneVerificationRequest.VerificationType.SESSION));
|
||||
|
||||
verify(account, never()).lockAuthTokenHash();
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
verify(registrationRecoveryPasswordsManager, never()).remove(any());
|
||||
verify(disconnectionRequestManager, never()).requestDisconnection(any(), any());
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -786,7 +786,7 @@ class AccountControllerTest {
|
||||
.withRecoveryPassword(recoveryPassword)))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
verify(registrationRecoveryPasswordsManager).storeForCurrentNumber(eq(AuthHelper.UNDISCOVERABLE_NUMBER), eq(recoveryPassword));
|
||||
verify(registrationRecoveryPasswordsManager).store(AuthHelper.UNDISCOVERABLE_PNI, recoveryPassword);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+26
-2
@@ -86,6 +86,7 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
@@ -105,6 +106,7 @@ class AccountControllerV2Test {
|
||||
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final ChangeNumberManager changeNumberManager = mock(ChangeNumberManager.class);
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
|
||||
RegistrationRecoveryPasswordsManager.class);
|
||||
@@ -125,8 +127,8 @@ class AccountControllerV2Test {
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new AccountControllerV2(accountsManager, changeNumberManager,
|
||||
new PhoneVerificationTokenManager(registrationServiceClient, registrationRecoveryPasswordsManager,
|
||||
registrationRecoveryChecker),
|
||||
new PhoneVerificationTokenManager(phoneNumberIdentifiers, registrationServiceClient,
|
||||
registrationRecoveryPasswordsManager, registrationRecoveryChecker),
|
||||
registrationLockVerificationManager, rateLimiters))
|
||||
.build();
|
||||
|
||||
@@ -217,6 +219,24 @@ class AccountControllerV2Test {
|
||||
assertEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberNonNormalizedNumber() throws Exception {
|
||||
try (Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION,
|
||||
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(
|
||||
// +4407700900111 is a valid number but not normalized - it has an optional '0' after the country code
|
||||
new ChangeNumberRequest(encodeSessionId("session"), null, "+4407700900111", null,
|
||||
new IdentityKey(Curve.generateKeyPair().getPublicKey()),
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(), null, Collections.emptyMap()),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unprocessableRequestJson() {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -383,6 +403,8 @@ class AccountControllerV2Test {
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationTrue() throws Exception {
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any()))
|
||||
@@ -425,6 +447,8 @@ class AccountControllerV2Test {
|
||||
|
||||
@Test
|
||||
void registrationRecoveryCheckerAllowsAttempt() {
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
+53
-8
@@ -72,6 +72,7 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
|
||||
@@ -1005,8 +1006,8 @@ class DeviceControllerTest {
|
||||
}
|
||||
|
||||
private static List<String> waitForLinkedDeviceBadTokenIdentifierLength() {
|
||||
return List.of(RandomStringUtils.randomAlphanumeric(DeviceController.MIN_TOKEN_IDENTIFIER_LENGTH - 1),
|
||||
RandomStringUtils.randomAlphanumeric(DeviceController.MAX_TOKEN_IDENTIFIER_LENGTH + 1));
|
||||
return List.of(RandomStringUtils.secure().nextAlphanumeric(DeviceController.MIN_TOKEN_IDENTIFIER_LENGTH - 1),
|
||||
RandomStringUtils.secure().nextAlphanumeric(DeviceController.MAX_TOKEN_IDENTIFIER_LENGTH + 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1050,6 +1051,30 @@ class DeviceControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordTransferArchiveFailed() {
|
||||
final byte deviceId = Device.PRIMARY_ID + 1;
|
||||
final Instant deviceCreated = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
final RemoteAttachmentError transferFailure = new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
|
||||
|
||||
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(accountsManager.recordTransferArchiveUpload(AuthHelper.VALID_ACCOUNT, deviceId, deviceCreated, transferFailure))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/transfer_archive")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.toEpochMilli(), transferFailure),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
|
||||
verify(accountsManager)
|
||||
.recordTransferArchiveUpload(AuthHelper.VALID_ACCOUNT, deviceId, deviceCreated, transferFailure);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void recordTransferArchiveUploadedBadRequest(final TransferArchiveUploadedRequest request) {
|
||||
@@ -1130,6 +1155,26 @@ class DeviceControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForTransferArchiveUploadFailed() {
|
||||
final RemoteAttachment transferArchive =
|
||||
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
when(rateLimiter.validateAsync(anyString())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(accountsManager.waitForTransferArchive(eq(AuthHelper.VALID_ACCOUNT), eq(AuthHelper.VALID_DEVICE), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(transferArchive)));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/transfer_archive/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get()) {
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(transferArchive, response.readEntity(RemoteAttachment.class));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForTransferArchiveNoArchiveUploaded() {
|
||||
when(rateLimiter.validateAsync(anyString())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -1177,7 +1222,7 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void recordRestoreAccountRequest() {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
|
||||
|
||||
@@ -1195,7 +1240,7 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void recordRestoreAccountRequestBadToken() {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(128);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(128);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
|
||||
|
||||
@@ -1210,7 +1255,7 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void recordRestoreAccountRequestInvalidRequest() {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest = new RestoreAccountRequest(null);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
@@ -1224,7 +1269,7 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void waitForDeviceTransferRequest() {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.LOCAL_BACKUP);
|
||||
|
||||
@@ -1243,7 +1288,7 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void waitForDeviceTransferRequestNoRequestIssued() {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
when(accountsManager.waitForRestoreAccountRequest(eq(token), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
@@ -1260,7 +1305,7 @@ class DeviceControllerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, -1, 3601})
|
||||
void waitForDeviceTransferRequestBadTimeout(final int timeoutSeconds) {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/restore_account/" + token)
|
||||
|
||||
+11
-2
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
@@ -77,6 +78,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
@@ -94,6 +96,7 @@ class RegistrationControllerTest {
|
||||
private static final String PASSWORD = "password";
|
||||
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager = mock(
|
||||
RegistrationLockVerificationManager.class);
|
||||
@@ -113,8 +116,8 @@ class RegistrationControllerTest {
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new RegistrationController(accountsManager,
|
||||
new PhoneVerificationTokenManager(registrationServiceClient, registrationRecoveryPasswordsManager,
|
||||
registrationRecoveryChecker),
|
||||
new PhoneVerificationTokenManager(phoneNumberIdentifiers, registrationServiceClient,
|
||||
registrationRecoveryPasswordsManager, registrationRecoveryChecker),
|
||||
registrationLockVerificationManager, rateLimiters))
|
||||
.build();
|
||||
|
||||
@@ -243,6 +246,8 @@ class RegistrationControllerTest {
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationFailureOrTimeout() {
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
|
||||
@@ -289,6 +294,8 @@ class RegistrationControllerTest {
|
||||
|
||||
@Test
|
||||
void recoveryPasswordManagerVerificationTrue() throws InterruptedException {
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -325,6 +332,8 @@ class RegistrationControllerTest {
|
||||
|
||||
@Test
|
||||
void registrationRecoveryCheckerAllowsAttempt() throws InterruptedException {
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(UUID.randomUUID()));
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(any(), any())).thenReturn(true);
|
||||
when(registrationRecoveryPasswordsManager.verify(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
+15
-6
@@ -39,6 +39,7 @@ import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.stream.Stream;
|
||||
@@ -77,6 +78,7 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -87,7 +89,11 @@ class VerificationControllerTest {
|
||||
private static final long SESSION_EXPIRATION_SECONDS = Duration.ofMinutes(10).toSeconds();
|
||||
|
||||
private static final byte[] SESSION_ID = "session".getBytes(StandardCharsets.UTF_8);
|
||||
private static final String NUMBER = "+18005551212";
|
||||
private static final String NUMBER = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
private static final UUID PNI = UUID.randomUUID();
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient = mock(RegistrationServiceClient.class);
|
||||
private final VerificationSessionManager verificationSessionManager = mock(VerificationSessionManager.class);
|
||||
@@ -95,6 +101,7 @@ class VerificationControllerTest {
|
||||
private final RegistrationCaptchaManager registrationCaptchaManager = mock(RegistrationCaptchaManager.class);
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager = mock(
|
||||
RegistrationRecoveryPasswordsManager.class);
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final Clock clock = Clock.systemUTC();
|
||||
@@ -115,7 +122,7 @@ class VerificationControllerTest {
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new VerificationController(registrationServiceClient, verificationSessionManager, pushNotificationManager,
|
||||
registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters, accountsManager,
|
||||
registrationCaptchaManager, registrationRecoveryPasswordsManager, phoneNumberIdentifiers, rateLimiters, accountsManager,
|
||||
RegistrationFraudChecker.noop(), dynamicConfigurationManager, clock))
|
||||
.build();
|
||||
|
||||
@@ -131,6 +138,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(new DynamicRegistrationConfiguration(false));
|
||||
when(dynamicConfigurationManager.getConfiguration())
|
||||
.thenReturn(dynamicConfiguration);
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(NUMBER))
|
||||
.thenReturn(CompletableFuture.completedFuture(PNI));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -573,7 +582,7 @@ class VerificationControllerTest {
|
||||
assertTrue(verificationSessionResponse.verified());
|
||||
assertTrue(verificationSessionResponse.requestedInformation().isEmpty());
|
||||
|
||||
verify(registrationRecoveryPasswordsManager).removeForNumber(registrationServiceSession.number());
|
||||
verify(registrationRecoveryPasswordsManager).remove(PNI);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -870,7 +879,7 @@ class VerificationControllerTest {
|
||||
try (Response response = request.get()) {
|
||||
assertEquals(HttpStatus.SC_OK, response.getStatus());
|
||||
|
||||
verify(registrationRecoveryPasswordsManager).removeForNumber(registrationServiceSession.number());
|
||||
verify(registrationRecoveryPasswordsManager).remove(PNI);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1195,7 +1204,7 @@ class VerificationControllerTest {
|
||||
VerificationSessionResponse.class);
|
||||
assertTrue(verificationSessionResponse.verified());
|
||||
|
||||
verify(registrationRecoveryPasswordsManager).removeForNumber(registrationServiceSession.number());
|
||||
verify(registrationRecoveryPasswordsManager).remove(PNI);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1327,7 +1336,7 @@ class VerificationControllerTest {
|
||||
|
||||
assertTrue(verificationSessionResponse.verified());
|
||||
|
||||
verify(registrationRecoveryPasswordsManager).removeForNumber(verifiedSession.number());
|
||||
verify(registrationRecoveryPasswordsManager).remove(PNI);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
-7
@@ -65,6 +65,7 @@ import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -113,7 +114,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
when(rateLimiter.validateReactive(any(UUID.class))).thenReturn(Mono.empty());
|
||||
when(rateLimiter.validateReactive(anyString())).thenReturn(Mono.empty());
|
||||
|
||||
when(registrationRecoveryPasswordsManager.storeForCurrentNumber(anyString(), any()))
|
||||
when(registrationRecoveryPasswordsManager.store(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
return new AccountsGrpcService(accountsManager,
|
||||
@@ -261,7 +262,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
final List<byte[]> usernameHashes = invocation.getArgument(1);
|
||||
|
||||
return CompletableFuture.completedFuture(
|
||||
new AccountsManager.UsernameReservation(invocation.getArgument(0), usernameHashes.get(0)));
|
||||
new AccountsManager.UsernameReservation(invocation.getArgument(0), usernameHashes.getFirst()));
|
||||
});
|
||||
|
||||
final ReserveUsernameHashResponse expectedResponse = ReserveUsernameHashResponse.newBuilder()
|
||||
@@ -684,12 +685,10 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@Test
|
||||
void setRegistrationRecoveryPassword() {
|
||||
final String phoneNumber =
|
||||
PhoneNumberUtil.getInstance().format(PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
final UUID phoneNumberIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn(phoneNumber);
|
||||
when(account.getIdentifier(IdentityType.PNI)).thenReturn(phoneNumberIdentifier);
|
||||
|
||||
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
@@ -701,7 +700,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
.setRegistrationRecoveryPassword(ByteString.copyFrom(registrationRecoveryPassword))
|
||||
.build()));
|
||||
|
||||
verify(registrationRecoveryPasswordsManager).storeForCurrentNumber(phoneNumber, registrationRecoveryPassword);
|
||||
verify(registrationRecoveryPasswordsManager).store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-4
@@ -104,7 +104,7 @@ public class ValidatingInterceptorTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 2, 3, 4, 6, 1000})
|
||||
public void testExactlySizeValidationFailure(final int size) throws Exception {
|
||||
final String stringValue = RandomStringUtils.randomAlphanumeric(size);
|
||||
final String stringValue = RandomStringUtils.secure().nextAlphanumeric(size);
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(
|
||||
builderWithValidDefaults()
|
||||
.setFixedSizeString(stringValue)
|
||||
@@ -119,7 +119,7 @@ public class ValidatingInterceptorTest {
|
||||
));
|
||||
|
||||
final List<String> listValue = IntStream.range(0, size)
|
||||
.mapToObj(i -> RandomStringUtils.randomAlphabetic(10))
|
||||
.mapToObj(i -> RandomStringUtils.secure().nextAlphabetic(10))
|
||||
.toList();
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(
|
||||
builderWithValidDefaults()
|
||||
@@ -181,7 +181,7 @@ public class ValidatingInterceptorTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void testRangeSizeValidationFailure(final int size, final Status expectedStatus) throws Exception {
|
||||
final String stringValue = RandomStringUtils.randomAlphanumeric(size);
|
||||
final String stringValue = RandomStringUtils.secure().nextAlphanumeric(size);
|
||||
assertEquals(expectedStatus.getCode(), requestStatus(() -> stub.validationsEndpoint(
|
||||
builderWithValidDefaults()
|
||||
.setRangeSizeString(stringValue)
|
||||
@@ -196,7 +196,7 @@ public class ValidatingInterceptorTest {
|
||||
)).getCode());
|
||||
|
||||
final List<String> listValue = IntStream.range(0, size)
|
||||
.mapToObj(i -> RandomStringUtils.randomAlphabetic(10))
|
||||
.mapToObj(i -> RandomStringUtils.secure().nextAlphabetic(10))
|
||||
.toList();
|
||||
assertEquals(expectedStatus.getCode(), requestStatus(() -> stub.validationsEndpoint(
|
||||
builderWithValidDefaults()
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ class NoiseWebSocketTunnelServerIntegrationTest extends AbstractLeakDetectionTes
|
||||
private static final UUID ACCOUNT_IDENTIFIER = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.randomAlphanumeric(16);
|
||||
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
// Please note that this certificate/key are used only for testing and are not used anywhere outside of this test.
|
||||
// They were generated with:
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ class WebsocketHandshakeCompleteHandlerTest extends AbstractLeakDetectionTest {
|
||||
private UserEventRecordingHandler userEventRecordingHandler;
|
||||
private MutableRemoteAddressEmbeddedChannel embeddedChannel;
|
||||
|
||||
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.randomAlphanumeric(16);
|
||||
private static final String RECOGNIZED_PROXY_SECRET = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
private static class UserEventRecordingHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ import org.whispersystems.textsecuregcm.tests.util.SynchronousExecutorService;
|
||||
|
||||
class APNSenderTest {
|
||||
|
||||
private static final String DESTINATION_DEVICE_TOKEN = RandomStringUtils.randomAlphanumeric(32);
|
||||
private static final String DESTINATION_DEVICE_TOKEN = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
private static final String BUNDLE_ID = "org.signal.test";
|
||||
|
||||
private Account destinationAccount;
|
||||
|
||||
@@ -128,7 +128,7 @@ class MessageSenderTest {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(System.currentTimeMillis())
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build();
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ class PushNotificationSchedulerTest {
|
||||
private static final UUID ACCOUNT_UUID = UUID.randomUUID();
|
||||
private static final String ACCOUNT_NUMBER = "+18005551234";
|
||||
private static final byte DEVICE_ID = 1;
|
||||
private static final String APN_ID = RandomStringUtils.randomAlphanumeric(32);
|
||||
private static final String APN_ID = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
|
||||
+4
-4
@@ -122,8 +122,8 @@ class SecureStorageClientTest {
|
||||
@Test
|
||||
void deleteStoredData() {
|
||||
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
final String username = RandomStringUtils.secure().nextAlphabetic(16);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
@@ -139,8 +139,8 @@ class SecureStorageClientTest {
|
||||
@Test
|
||||
void deleteStoredDataFailure() {
|
||||
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
final String username = RandomStringUtils.secure().nextAlphabetic(16);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
+4
-4
@@ -121,8 +121,8 @@ class SecureValueRecovery2ClientTest {
|
||||
|
||||
@Test
|
||||
void deleteStoredData() {
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
final String username = RandomStringUtils.secure().nextAlphabetic(16);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
@@ -136,8 +136,8 @@ class SecureValueRecovery2ClientTest {
|
||||
|
||||
@Test
|
||||
void deleteStoredDataFailure() {
|
||||
final String username = RandomStringUtils.randomAlphabetic(16);
|
||||
final String password = RandomStringUtils.randomAlphanumeric(32);
|
||||
final String username = RandomStringUtils.secure().nextAlphabetic(16);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(32);
|
||||
|
||||
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
|
||||
new ExternalServiceCredentials(username, password));
|
||||
|
||||
+17
-18
@@ -23,7 +23,6 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
@@ -126,7 +125,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.PNI.tableName());
|
||||
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
@@ -138,7 +137,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
mock(RegistrationRecoveryPasswordsManager.class);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
|
||||
when(registrationRecoveryPasswordsManager.remove(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
@@ -182,12 +181,12 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String password = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String signalAgent = RandomStringUtils.randomAlphabetic(3);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3);
|
||||
final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
|
||||
final int pniRegistrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
|
||||
final byte[] deviceName = RandomStringUtils.randomAlphabetic(16).getBytes(StandardCharsets.UTF_8);
|
||||
final String registrationLockSecret = RandomStringUtils.randomAlphanumeric(16);
|
||||
final byte[] deviceName = RandomStringUtils.secure().nextAlphabetic(16).getBytes(StandardCharsets.UTF_8);
|
||||
final String registrationLockSecret = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
final Set<DeviceCapability> deviceCapabilities = Set.of();
|
||||
|
||||
@@ -200,7 +199,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
deviceCapabilities);
|
||||
|
||||
final List<AccountBadge> badges = new ArrayList<>(List.of(new AccountBadge(
|
||||
RandomStringUtils.randomAlphabetic(8),
|
||||
RandomStringUtils.secure().nextAlphabetic(8),
|
||||
CLOCK.instant().plus(Duration.ofDays(7)),
|
||||
true)));
|
||||
|
||||
@@ -323,12 +322,12 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
existingAccountUuid = originalAccount.getUuid();
|
||||
}
|
||||
|
||||
final String password = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String signalAgent = RandomStringUtils.randomAlphabetic(3);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3);
|
||||
final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
|
||||
final int pniRegistrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
|
||||
final byte[] deviceName = RandomStringUtils.randomAlphabetic(16).getBytes(StandardCharsets.UTF_8);
|
||||
final String registrationLockSecret = RandomStringUtils.randomAlphanumeric(16);
|
||||
final byte[] deviceName = RandomStringUtils.secure().nextAlphabetic(16).getBytes(StandardCharsets.UTF_8);
|
||||
final String registrationLockSecret = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
final Set<DeviceCapability> deviceCapabilities = Set.of();
|
||||
|
||||
@@ -341,7 +340,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
deviceCapabilities);
|
||||
|
||||
final List<AccountBadge> badges = new ArrayList<>(List.of(new AccountBadge(
|
||||
RandomStringUtils.randomAlphabetic(8),
|
||||
RandomStringUtils.secure().nextAlphabetic(8),
|
||||
CLOCK.instant().plus(Duration.ofDays(7)),
|
||||
true)));
|
||||
|
||||
@@ -412,12 +411,12 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String password = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String signalAgent = RandomStringUtils.randomAlphabetic(3);
|
||||
final String password = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3);
|
||||
final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
|
||||
final int pniRegistrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID);
|
||||
final byte[] deviceName = RandomStringUtils.randomAlphabetic(16).getBytes(StandardCharsets.UTF_8);
|
||||
final String registrationLockSecret = RandomStringUtils.randomAlphanumeric(16);
|
||||
final byte[] deviceName = RandomStringUtils.secure().nextAlphabetic(16).getBytes(StandardCharsets.UTF_8);
|
||||
final String registrationLockSecret = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
|
||||
final Set<DeviceCapability> deviceCapabilities = Set.of();
|
||||
|
||||
@@ -430,7 +429,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
deviceCapabilities);
|
||||
|
||||
final List<AccountBadge> badges = new ArrayList<>(List.of(new AccountBadge(
|
||||
RandomStringUtils.randomAlphabetic(8),
|
||||
RandomStringUtils.secure().nextAlphabetic(8),
|
||||
CLOCK.instant().plus(Duration.ofDays(7)),
|
||||
true)));
|
||||
|
||||
|
||||
+17
-16
@@ -9,9 +9,9 @@ import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClient;
|
||||
import com.amazonaws.services.dynamodbv2.ReleaseLockOptions;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -27,11 +27,8 @@ class AccountLockManagerTest {
|
||||
|
||||
private AccountLockManager accountLockManager;
|
||||
|
||||
private static final String FIRST_NUMBER = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
private static final String SECOND_NUMBER = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("JP"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
private static final UUID FIRST_PNI = UUID.randomUUID();
|
||||
private static final UUID SECOND_PNI = UUID.randomUUID();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -51,7 +48,8 @@ class AccountLockManagerTest {
|
||||
|
||||
@Test
|
||||
void withLock() throws InterruptedException {
|
||||
accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), () -> {}, executor);
|
||||
accountLockManager.withLock(List.of(FIRST_PNI, SECOND_PNI), () -> {
|
||||
}, executor);
|
||||
|
||||
verify(lockClient, times(2)).acquireLock(any());
|
||||
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
|
||||
@@ -59,8 +57,8 @@ class AccountLockManagerTest {
|
||||
|
||||
@Test
|
||||
void withLockTaskThrowsException() throws InterruptedException {
|
||||
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), () -> {
|
||||
throw new RuntimeException();
|
||||
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(List.of(FIRST_PNI, SECOND_PNI), () -> {
|
||||
throw new RuntimeException();
|
||||
}, executor));
|
||||
|
||||
verify(lockClient, times(2)).acquireLock(any());
|
||||
@@ -71,14 +69,16 @@ class AccountLockManagerTest {
|
||||
void withLockEmptyList() {
|
||||
final Runnable task = mock(Runnable.class);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptyList(), () -> {}, executor));
|
||||
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptyList(), () -> {
|
||||
},
|
||||
executor));
|
||||
verify(task, never()).run();
|
||||
}
|
||||
|
||||
@Test
|
||||
void withLockAsync() throws InterruptedException {
|
||||
accountLockManager.withLockAsync(List.of(FIRST_NUMBER, SECOND_NUMBER),
|
||||
() -> CompletableFuture.completedFuture(null), executor).join();
|
||||
accountLockManager.withLockAsync(
|
||||
List.of(FIRST_PNI, SECOND_PNI), () -> CompletableFuture.completedFuture(null), executor).join();
|
||||
|
||||
verify(lockClient, times(2)).acquireLock(any());
|
||||
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
|
||||
@@ -87,8 +87,9 @@ class AccountLockManagerTest {
|
||||
@Test
|
||||
void withLockAsyncTaskThrowsException() throws InterruptedException {
|
||||
assertThrows(RuntimeException.class,
|
||||
() -> accountLockManager.withLockAsync(List.of(FIRST_NUMBER, SECOND_NUMBER),
|
||||
() -> CompletableFuture.failedFuture(new RuntimeException()), executor).join());
|
||||
() -> accountLockManager.withLockAsync(
|
||||
List.of(FIRST_PNI, SECOND_PNI), () -> CompletableFuture.failedFuture(new RuntimeException()), executor)
|
||||
.join());
|
||||
|
||||
verify(lockClient, times(2)).acquireLock(any());
|
||||
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
|
||||
@@ -99,8 +100,8 @@ class AccountLockManagerTest {
|
||||
final Runnable task = mock(Runnable.class);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> accountLockManager.withLockAsync(Collections.emptyList(),
|
||||
() -> CompletableFuture.completedFuture(null), executor));
|
||||
() -> accountLockManager.withLockAsync(Collections.emptyList(), () -> CompletableFuture.completedFuture(null),
|
||||
executor));
|
||||
|
||||
verify(task, never()).run();
|
||||
}
|
||||
|
||||
+2
-2
@@ -119,7 +119,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(), Tables.PNI.tableName());
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
|
||||
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -130,7 +130,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
mock(RegistrationRecoveryPasswordsManager.class);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
|
||||
when(registrationRecoveryPasswordsManager.remove(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
|
||||
+4
-4
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
@@ -50,7 +51,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
@@ -111,9 +111,9 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
task.run();
|
||||
|
||||
return null;
|
||||
}).when(accountLockManager).withLock(any(), any(), any());
|
||||
}).when(accountLockManager).withLock(anyList(), any(), any());
|
||||
|
||||
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
|
||||
when(accountLockManager.withLockAsync(anyList(), any(), any())).thenAnswer(invocation -> {
|
||||
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
|
||||
taskSupplier.get().join();
|
||||
|
||||
@@ -122,7 +122,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString()))
|
||||
.thenAnswer((Answer<UUID>) invocation -> UUID.randomUUID());
|
||||
.thenAnswer((Answer<CompletableFuture<UUID>>) invocation -> CompletableFuture.completedFuture(UUID.randomUUID()));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
|
||||
+32
-6
@@ -12,10 +12,11 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -97,10 +98,10 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
|
||||
final CompletableFuture<Optional<RemoteAttachment>> displacedFuture =
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> displacedFuture =
|
||||
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5));
|
||||
|
||||
final CompletableFuture<Optional<RemoteAttachment>> activeFuture =
|
||||
final CompletableFuture<Optional<TransferArchiveResult>> activeFuture =
|
||||
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5));
|
||||
|
||||
assertEquals(Optional.empty(), displacedFuture.join());
|
||||
@@ -132,6 +133,30 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForErrorTransferArchive() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final long deviceCreated = System.currentTimeMillis();
|
||||
|
||||
final RemoteAttachmentError transferArchiveError =
|
||||
new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getCreated()).thenReturn(deviceCreated);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
|
||||
accountsManager
|
||||
.recordTransferArchiveUpload(account, deviceId, Instant.ofEpochMilli(deviceCreated), transferArchiveError)
|
||||
.join();
|
||||
|
||||
assertEquals(Optional.of(transferArchiveError),
|
||||
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForTransferArchiveTimeout() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
@@ -151,7 +176,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
|
||||
@Test
|
||||
void waitForRestoreAccountRequest() {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
|
||||
|
||||
@@ -170,7 +195,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
|
||||
@Test
|
||||
void waitForRestoreAccountRequestAlreadyRequested() {
|
||||
final String token = RandomStringUtils.randomAlphanumeric(16);
|
||||
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
|
||||
final RestoreAccountRequest restoreAccountRequest =
|
||||
new RestoreAccountRequest(RestoreAccountRequest.Method.DEVICE_TRANSFER);
|
||||
|
||||
@@ -183,6 +208,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
@Test
|
||||
void waitForRestoreAccountRequestTimeout() {
|
||||
assertEquals(Optional.empty(),
|
||||
accountsManager.waitForRestoreAccountRequest(RandomStringUtils.randomAlphanumeric(16), Duration.ofMillis(1)).join());
|
||||
accountsManager.waitForRestoreAccountRequest(RandomStringUtils.secure().nextAlphanumeric(16),
|
||||
Duration.ofMillis(1)).join());
|
||||
}
|
||||
}
|
||||
+37
-9
@@ -15,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -65,6 +66,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.stubbing.Answer;
|
||||
@@ -194,9 +196,9 @@ class AccountsManagerTest {
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
phoneNumberIdentifiersByE164 = new HashMap<>();
|
||||
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<UUID>) invocation -> {
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<CompletableFuture<UUID>>) invocation -> {
|
||||
final String number = invocation.getArgument(0, String.class);
|
||||
return phoneNumberIdentifiersByE164.computeIfAbsent(number, n -> UUID.randomUUID());
|
||||
return CompletableFuture.completedFuture(phoneNumberIdentifiersByE164.computeIfAbsent(number, n -> UUID.randomUUID()));
|
||||
});
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
@@ -212,9 +214,9 @@ class AccountsManagerTest {
|
||||
task.run();
|
||||
|
||||
return null;
|
||||
}).when(accountLockManager).withLock(any(), any(), any());
|
||||
}).when(accountLockManager).withLock(anyList(), any(), any());
|
||||
|
||||
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
|
||||
when(accountLockManager.withLockAsync(anyList(), any(), any())).thenAnswer(invocation -> {
|
||||
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
|
||||
return taskSupplier.get();
|
||||
});
|
||||
@@ -222,7 +224,7 @@ class AccountsManagerTest {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
mock(RegistrationRecoveryPasswordsManager.class);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.removeForNumber(anyString())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(registrationRecoveryPasswordsManager.remove(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(keysManager.deleteSingleUsePreKeys(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -836,11 +838,17 @@ class AccountsManagerTest {
|
||||
verifyNoInteractions(profilesManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReregisterAccount() throws InterruptedException, AccountAlreadyExistsException {
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"+18005550123, +18005550123",
|
||||
// the canonical form of numbers may change over time, so an existing account might have not-identical e164 that
|
||||
// maps to the same PNI, and the number used by the caller must be present on the re-registered account
|
||||
"+2290123456789, +22923456789"
|
||||
})
|
||||
void testReregisterAccount(final String e164, final String existingAccountE164)
|
||||
throws InterruptedException, AccountAlreadyExistsException {
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
|
||||
final String e164 = "+18005550123";
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null);
|
||||
|
||||
when(accounts.create(any(), any()))
|
||||
@@ -850,9 +858,10 @@ class AccountsManagerTest {
|
||||
final Account existingAccount = mock(Account.class);
|
||||
when(existingAccount.getUuid()).thenReturn(existingUuid);
|
||||
when(existingAccount.getIdentifier(IdentityType.ACI)).thenReturn(existingUuid);
|
||||
when(existingAccount.getNumber()).thenReturn(e164);
|
||||
when(existingAccount.getNumber()).thenReturn(existingAccountE164);
|
||||
when(existingAccount.getPhoneNumberIdentifier()).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI));
|
||||
when(existingAccount.getIdentifier(IdentityType.PNI)).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI));
|
||||
when(existingAccount.getPrimaryDevice()).thenReturn(mock(Device.class));
|
||||
|
||||
throw new AccountAlreadyExistsException(existingAccount);
|
||||
});
|
||||
@@ -862,6 +871,7 @@ class AccountsManagerTest {
|
||||
final Account reregisteredAccount = createAccount(e164, attributes);
|
||||
|
||||
assertTrue(phoneNumberIdentifiersByE164.containsKey(e164));
|
||||
assertEquals(e164, reregisteredAccount.getNumber());
|
||||
|
||||
verify(accounts)
|
||||
.create(argThat(account -> e164.equals(account.getNumber()) && existingUuid.equals(account.getUuid())), any());
|
||||
@@ -1052,17 +1062,35 @@ class AccountsManagerTest {
|
||||
final String number = "+14152222222";
|
||||
|
||||
Account account = AccountsHelper.generateTestAccount(number, UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
phoneNumberIdentifiersByE164.put(number, account.getPhoneNumberIdentifier());
|
||||
account = accountsManager.changeNumber(account, number, null, null, null, null);
|
||||
|
||||
assertEquals(number, account.getNumber());
|
||||
verify(keysManager, never()).deleteSingleUsePreKeys(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testChangePhoneNumberDifferentNumberSamePni() throws InterruptedException, MismatchedDevicesException {
|
||||
final String originalNumber = "+22923456789";
|
||||
// the canonical form of numbers may change over time, so we use PNIs as stable identifiers
|
||||
final String newNumber = "+2290123456789";
|
||||
|
||||
Account account = AccountsHelper.generateTestAccount(originalNumber, UUID.randomUUID(), UUID.randomUUID(),
|
||||
new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
phoneNumberIdentifiersByE164.put(originalNumber, account.getPhoneNumberIdentifier());
|
||||
phoneNumberIdentifiersByE164.put(newNumber, account.getPhoneNumberIdentifier());
|
||||
account = accountsManager.changeNumber(account, newNumber, null, null, null, null);
|
||||
|
||||
assertEquals(originalNumber, account.getNumber());
|
||||
verify(keysManager, never()).deleteSingleUsePreKeys(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testChangePhoneNumberSameNumberWithPniData() {
|
||||
final String number = "+14152222222";
|
||||
|
||||
Account account = AccountsHelper.generateTestAccount(number, UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
phoneNumberIdentifiersByE164.put(number, account.getPhoneNumberIdentifier());
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> accountsManager.changeNumber(
|
||||
|
||||
+4
-3
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -117,9 +118,9 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
task.run();
|
||||
|
||||
return null;
|
||||
}).when(accountLockManager).withLock(any(), any(), any());
|
||||
}).when(accountLockManager).withLock(anyList(), any(), any());
|
||||
|
||||
when(accountLockManager.withLockAsync(any(), any(), any())).thenAnswer(invocation -> {
|
||||
when(accountLockManager.withLockAsync(anyList(), any(), any())).thenAnswer(invocation -> {
|
||||
final Supplier<CompletableFuture<?>> taskSupplier = invocation.getArgument(1);
|
||||
taskSupplier.get().join();
|
||||
|
||||
@@ -127,7 +128,7 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
});
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(), Tables.PNI.tableName());
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
|
||||
|
||||
final MessagesManager messageManager = mock(MessagesManager.class);
|
||||
final ProfilesManager profileManager = mock(ProfilesManager.class);
|
||||
|
||||
@@ -65,6 +65,7 @@ import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.function.Tuples;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
@@ -74,6 +75,7 @@ import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Put;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
@@ -211,6 +213,7 @@ class AccountsTest {
|
||||
|
||||
accounts.delete(originalUuid, Collections.emptyList()).join();
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getNumber())).hasValue(originalUuid);
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier())).hasValue(originalUuid);
|
||||
|
||||
freshUser = createAccount(account);
|
||||
assertThat(freshUser).isTrue();
|
||||
@@ -220,6 +223,7 @@ class AccountsTest {
|
||||
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
|
||||
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getNumber())).isEmpty();
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier())).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -235,6 +239,45 @@ class AccountsTest {
|
||||
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStoreAciCollisionFails() {
|
||||
Device device = generateDevice(DEVICE_ID_1);
|
||||
Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device));
|
||||
|
||||
boolean freshUser = createAccount(account);
|
||||
|
||||
assertThat(freshUser).isTrue();
|
||||
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true);
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", account.getUuid());
|
||||
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getUuid());
|
||||
|
||||
account.setNumber("+14153334444", UUID.randomUUID());
|
||||
assertThrows(IllegalArgumentException.class, () -> createAccount(account),
|
||||
"Reusing ACI with different PNI should fail");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStorePniCollisionFails() {
|
||||
Device device1 = generateDevice(DEVICE_ID_1);
|
||||
Account account1 = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device1));
|
||||
|
||||
boolean freshUser = createAccount(account1);
|
||||
|
||||
assertThat(freshUser).isTrue();
|
||||
verifyStoredState("+14151112222", account1.getUuid(), account1.getPhoneNumberIdentifier(), null, account1, true);
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", account1.getUuid());
|
||||
assertPhoneNumberIdentifierConstraintExists(account1.getPhoneNumberIdentifier(), account1.getUuid());
|
||||
|
||||
Device device2 = generateDevice(DEVICE_ID_1);
|
||||
Account account2 = generateAccount("+14151112222", UUID.randomUUID(), account1.getPhoneNumberIdentifier(),
|
||||
List.of(device2));
|
||||
|
||||
assertThrows(AccountAlreadyExistsException.class, () -> accounts.create(account2, Collections.emptyList()),
|
||||
"New ACI with same PNI should fail");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetrieve() {
|
||||
final List<Device> devicesFirst = List.of(generateDevice(DEVICE_ID_1), generateDevice(DEVICE_ID_2));
|
||||
@@ -703,6 +746,7 @@ class AccountsTest {
|
||||
createAccount(retainedAccount);
|
||||
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getNumber())).isEmpty();
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier())).isEmpty();
|
||||
|
||||
assertPhoneNumberConstraintExists("+14151112222", deletedAccount.getUuid());
|
||||
assertPhoneNumberIdentifierConstraintExists(deletedAccount.getPhoneNumberIdentifier(), deletedAccount.getUuid());
|
||||
@@ -716,6 +760,7 @@ class AccountsTest {
|
||||
|
||||
assertThat(accounts.getByAccountIdentifier(deletedAccount.getUuid())).isNotPresent();
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getNumber())).hasValue(deletedAccount.getUuid());
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(deletedAccount.getPhoneNumberIdentifier())).hasValue(deletedAccount.getUuid());
|
||||
|
||||
assertPhoneNumberConstraintDoesNotExist(deletedAccount.getNumber());
|
||||
assertPhoneNumberIdentifierConstraintDoesNotExist(deletedAccount.getPhoneNumberIdentifier());
|
||||
@@ -725,7 +770,7 @@ class AccountsTest {
|
||||
|
||||
{
|
||||
final Account recreatedAccount = generateAccount(deletedAccount.getNumber(), UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
|
||||
deletedAccount.getPhoneNumberIdentifier(), List.of(generateDevice(DEVICE_ID_1)));
|
||||
|
||||
final boolean freshUser = createAccount(recreatedAccount);
|
||||
|
||||
@@ -854,6 +899,7 @@ class AccountsTest {
|
||||
}
|
||||
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(originalNumber)).isEqualTo(maybeDisplacedAccountIdentifier);
|
||||
assertThat(accounts.findRecentlyDeletedAccountIdentifier(originalPni)).isEqualTo(maybeDisplacedAccountIdentifier);
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testChangeNumber() {
|
||||
@@ -1658,7 +1704,142 @@ class AccountsTest {
|
||||
assertInstanceOf(DeviceIdDeserializer.DeviceIdDeserializationException.class, cause);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getE164KeyedDeletedAccounts() {
|
||||
final Account deletedAccount = generateAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID());
|
||||
createAccount(deletedAccount);
|
||||
accounts.delete(deletedAccount.getUuid(), List.of()).join();
|
||||
assertEquals(
|
||||
List.of(Tuples.of("+18005551234", deletedAccount.getUuid(), clock.instant().plus(Accounts.DELETED_ACCOUNTS_TIME_TO_LIVE).toEpochMilli() / 1000)),
|
||||
accounts.getE164KeyedDeletedAccounts(1, Schedulers.immediate()).collectList().block());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void insertPniDeletedAccount() throws Exception {
|
||||
final String e164 = "+18005551234";
|
||||
final UUID aci = UUID.randomUUID();
|
||||
final UUID pni = UUID.randomUUID();
|
||||
final Long expires = 1234567890L;
|
||||
|
||||
final ScanRequest scanRequest = ScanRequest.builder()
|
||||
.tableName(Tables.DELETED_ACCOUNTS.tableName())
|
||||
.build();
|
||||
assertThat(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items())
|
||||
.isEmpty();
|
||||
|
||||
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient().putItem(
|
||||
PutItemRequest.builder()
|
||||
.tableName(Tables.DELETED_ACCOUNTS.tableName())
|
||||
.item(Map.of(
|
||||
Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164),
|
||||
Accounts.DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(aci),
|
||||
Accounts.DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(expires)))
|
||||
.build());
|
||||
|
||||
assertThat(accounts.insertPniDeletedAccount(e164, pni, aci, expires).get()).isTrue();
|
||||
|
||||
List<Map<String, AttributeValue>> items =
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items();
|
||||
assertThat(items).hasSize(2);
|
||||
final Map<String, AttributeValue> item = items.stream().filter(i -> !i.get(Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s().equals(e164)).findFirst().get();
|
||||
assertThat(item.get(Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_E164).s())
|
||||
.isEqualTo(pni.toString());
|
||||
assertThat(AttributeValues.getUUID(item, Accounts.DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, null))
|
||||
.isEqualTo(aci);
|
||||
assertThat(AttributeValues.getLong(item, Accounts.DELETED_ACCOUNTS_ATTR_EXPIRES, 0))
|
||||
.isEqualTo(expires);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void insertPniDeletedAccount_concurrentChange() throws Exception {
|
||||
final String e164 = "+18005551234";
|
||||
final UUID aci = UUID.randomUUID();
|
||||
final UUID pni = UUID.randomUUID();
|
||||
final Long expires = 1234567890L;
|
||||
|
||||
final ScanRequest scanRequest = ScanRequest.builder()
|
||||
.tableName(Tables.DELETED_ACCOUNTS.tableName())
|
||||
.build();
|
||||
assertThat(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items())
|
||||
.isEmpty();
|
||||
|
||||
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient().putItem(
|
||||
PutItemRequest.builder()
|
||||
.tableName(Tables.DELETED_ACCOUNTS.tableName())
|
||||
.item(Map.of(
|
||||
Accounts.DELETED_ACCOUNTS_KEY_ACCOUNT_E164, AttributeValues.fromString(e164),
|
||||
Accounts.DELETED_ACCOUNTS_ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(aci),
|
||||
Accounts.DELETED_ACCOUNTS_ATTR_EXPIRES, AttributeValues.fromLong(expires + 1)))
|
||||
.build());
|
||||
|
||||
assertThat(accounts.insertPniDeletedAccount(e164, pni, aci, expires).get()).isFalse();
|
||||
|
||||
List<Map<String, AttributeValue>> items =
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items();
|
||||
assertThat(items).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void insertPniDeletedAccount_concurrentDeletion() throws Exception {
|
||||
final String e164 = "+18005551234";
|
||||
final UUID aci = UUID.randomUUID();
|
||||
final UUID pni = UUID.randomUUID();
|
||||
final Long expires = 1234567890L;
|
||||
|
||||
final ScanRequest scanRequest = ScanRequest.builder()
|
||||
.tableName(Tables.DELETED_ACCOUNTS.tableName())
|
||||
.build();
|
||||
assertThat(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items())
|
||||
.isEmpty();
|
||||
|
||||
assertThat(accounts.insertPniDeletedAccount(e164, pni, aci, expires).get()).isFalse();
|
||||
|
||||
List<Map<String, AttributeValue>> items =
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items();
|
||||
assertThat(items).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void insertPniDeletedAccount_alreadyMigrated() throws Exception {
|
||||
final Account deletedAccount = generateAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID());
|
||||
|
||||
createAccount(deletedAccount);
|
||||
accounts.delete(deletedAccount.getUuid(), List.of()).join();
|
||||
|
||||
final ScanRequest scanRequest = ScanRequest.builder()
|
||||
.tableName(Tables.DELETED_ACCOUNTS.tableName())
|
||||
.build();
|
||||
assertThat(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items())
|
||||
.hasSize(2);
|
||||
|
||||
assertThat(accounts.insertPniDeletedAccount(deletedAccount.getNumber(), deletedAccount.getPhoneNumberIdentifier(), deletedAccount.getUuid(), clock.instant().plus(Accounts.DELETED_ACCOUNTS_TIME_TO_LIVE).toEpochMilli() / 1000).get()).isFalse();
|
||||
|
||||
List<Map<String, AttributeValue>> items =
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.scan(scanRequest)
|
||||
.items();
|
||||
assertThat(items).hasSize(2);
|
||||
}
|
||||
|
||||
private static Device generateDevice(byte id) {
|
||||
return DevicesHelper.createDevice(id);
|
||||
|
||||
+2
-2
@@ -125,7 +125,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.PNI.tableName());
|
||||
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
@@ -137,7 +137,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
mock(RegistrationRecoveryPasswordsManager.class);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
|
||||
when(registrationRecoveryPasswordsManager.remove(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
PUBSUB_SERVER_EXTENSION.getRedisClient().useConnection(connection -> {
|
||||
|
||||
+4
-4
@@ -98,10 +98,10 @@ public final class DynamoDbExtensionSchema {
|
||||
),
|
||||
|
||||
DELETED_ACCOUNTS_LOCK("deleted_accounts_lock_test",
|
||||
AccountLockManager.KEY_ACCOUNT_E164,
|
||||
AccountLockManager.KEY_ACCOUNT_PNI,
|
||||
null,
|
||||
List.of(AttributeDefinition.builder()
|
||||
.attributeName(AccountLockManager.KEY_ACCOUNT_E164)
|
||||
.attributeName(AccountLockManager.KEY_ACCOUNT_PNI)
|
||||
.attributeType(ScalarAttributeType.S).build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
@@ -288,10 +288,10 @@ public final class DynamoDbExtensionSchema {
|
||||
List.of(), List.of()),
|
||||
|
||||
REGISTRATION_RECOVERY_PASSWORDS("registration_recovery_passwords_test",
|
||||
RegistrationRecoveryPasswords.KEY_E164,
|
||||
RegistrationRecoveryPasswords.KEY_PNI,
|
||||
null,
|
||||
List.of(AttributeDefinition.builder()
|
||||
.attributeName(RegistrationRecoveryPasswords.KEY_E164)
|
||||
.attributeName(RegistrationRecoveryPasswords.KEY_PNI)
|
||||
.attributeType(ScalarAttributeType.S)
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
+2
-2
@@ -81,7 +81,7 @@ class MessagePersisterIntegrationTest {
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
|
||||
@@ -197,7 +197,7 @@ class MessagePersisterIntegrationTest {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(serverTimestamp * 2) // client timestamp may not be accurate
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.setDestinationServiceId(UUID.randomUUID().toString())
|
||||
|
||||
+2
-2
@@ -99,7 +99,7 @@ class MessagePersisterTest {
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
@@ -353,7 +353,7 @@ class MessagePersisterTest {
|
||||
.setDestinationServiceId(accountUuid.toString())
|
||||
.setClientTimestamp(firstMessageTimestamp.toEpochMilli() + i)
|
||||
.setServerTimestamp(firstMessageTimestamp.toEpochMilli() + i)
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.build();
|
||||
|
||||
+17
-96
@@ -64,12 +64,8 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -98,26 +94,17 @@ class MessagesCacheTest {
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private MessagesCache messagesCache;
|
||||
|
||||
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private DynamicConfiguration dynamicConfiguration;
|
||||
|
||||
private static final UUID DESTINATION_UUID = UUID.randomUUID();
|
||||
|
||||
private static final byte DESTINATION_DEVICE_ID = 7;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(
|
||||
new DynamicMessagesConfiguration(true));
|
||||
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -321,7 +308,7 @@ class MessagesCacheTest {
|
||||
}
|
||||
|
||||
final MessagesCache messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, cacheClock, dynamicConfigurationManager);
|
||||
messageDeliveryScheduler, sharedExecutorService, cacheClock);
|
||||
|
||||
final List<MessageProtos.Envelope> actualMessages = Flux.from(
|
||||
messagesCache.get(DESTINATION_UUID, DESTINATION_DEVICE_ID))
|
||||
@@ -429,12 +416,9 @@ class MessagesCacheTest {
|
||||
assertEquals(DESTINATION_DEVICE_ID, MessagesCache.getDeviceIdFromQueueName(queues.getFirst()));
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void testMultiRecipientMessage(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
|
||||
|
||||
when(dynamicConfiguration.getMessagesConfiguration())
|
||||
.thenReturn(new DynamicMessagesConfiguration(useSharedMrmData));
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testMultiRecipientMessage(final boolean sharedMrmKeyPresent) {
|
||||
|
||||
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = 1;
|
||||
@@ -453,10 +437,8 @@ class MessagesCacheTest {
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
// mrm views phase 2: messages have content
|
||||
.setContent(
|
||||
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.clearContent()
|
||||
.build();
|
||||
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
|
||||
|
||||
@@ -464,7 +446,7 @@ class MessagesCacheTest {
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
|
||||
if (useSharedMrmData && !sharedMrmKeyPresent) {
|
||||
if (!sharedMrmKeyPresent) {
|
||||
assertTrue(messages.isEmpty());
|
||||
} else {
|
||||
|
||||
@@ -495,65 +477,7 @@ class MessagesCacheTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testMultiRecipientMessagePhase2MissingContentSafeguard(final boolean useSharedMrmData) {
|
||||
|
||||
when(dynamicConfiguration.getMessagesConfiguration())
|
||||
.thenReturn(new DynamicMessagesConfiguration(useSharedMrmData));
|
||||
|
||||
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = 1;
|
||||
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
|
||||
|
||||
final byte[] sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
|
||||
|
||||
final UUID guid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(guid, destinationServiceId, true)
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
// mrm views phase 2: there is a safeguard against missing content, even if the dynamic configuration
|
||||
// is to not fetch or use shared MRM data
|
||||
.clearContent()
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.build();
|
||||
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
|
||||
|
||||
assertEquals(1, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
|
||||
|
||||
assertEquals(1, messages.size());
|
||||
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
|
||||
assertFalse(messages.getFirst().hasSharedMrmKey());
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
|
||||
.get(destinationServiceId.toLibsignal());
|
||||
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
|
||||
|
||||
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid)
|
||||
.join();
|
||||
|
||||
assertTrue(removedMessage.isPresent());
|
||||
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
|
||||
assertTrue(get(destinationServiceId.uuid(), deviceId, 1).isEmpty());
|
||||
|
||||
// updating the shared MRM data is purely async, so we just wait for it
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
|
||||
boolean exists;
|
||||
do {
|
||||
exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey));
|
||||
} while (exists);
|
||||
}, "Shared MRM data should be deleted asynchronously");
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void testGetMessagesToPersist(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
|
||||
|
||||
when(dynamicConfiguration.getMessagesConfiguration())
|
||||
.thenReturn(new DynamicMessagesConfiguration(useSharedMrmData));
|
||||
void testGetMessagesToPersist(final boolean sharedMrmKeyPresent) {
|
||||
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(destinationUuid);
|
||||
@@ -578,24 +502,22 @@ class MessagesCacheTest {
|
||||
final MessageProtos.Envelope mrmMessage = generateRandomMessage(mrmMessageGuid, destinationServiceId, true)
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
// mrm views phase 2: messages have content
|
||||
.setContent(
|
||||
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(new ServiceId.Aci(destinationUuid)))))
|
||||
.clearContent()
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.build();
|
||||
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage);
|
||||
|
||||
final List<MessageProtos.Envelope> messages = messagesCache.getMessagesToPersist(destinationUuid, deviceId, 100);
|
||||
|
||||
if (useSharedMrmData && !sharedMrmKeyPresent) {
|
||||
if (!sharedMrmKeyPresent) {
|
||||
assertEquals(1, messages.size());
|
||||
} else {
|
||||
assertEquals(2, messages.size());
|
||||
|
||||
assertEquals(mrmMessage.toBuilder().
|
||||
clearSharedMrmKey().
|
||||
setServerGuid(mrmMessageGuid.toString())
|
||||
assertEquals(mrmMessage.toBuilder()
|
||||
.clearSharedMrmKey()
|
||||
.setContent(ByteString.copyFrom(
|
||||
mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
|
||||
.build(),
|
||||
messages.getLast());
|
||||
}
|
||||
@@ -636,7 +558,7 @@ class MessagesCacheTest {
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
|
||||
messagesCache = new MessagesCache(mockCluster, messageDeliveryScheduler,
|
||||
Executors.newSingleThreadExecutor(), Clock.systemUTC(), mock(DynamicConfigurationManager.class));
|
||||
Executors.newSingleThreadExecutor(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -822,12 +744,11 @@ class MessagesCacheTest {
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid,
|
||||
final ServiceIdentifier destinationServiceId, final boolean sealedSender,
|
||||
final long timestamp) {
|
||||
final ServiceIdentifier destinationServiceId, final boolean sealedSender, final long timestamp) {
|
||||
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(timestamp)
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.setDestinationServiceId(destinationServiceId.toServiceIdentifierString());
|
||||
|
||||
+146
-15
@@ -6,15 +6,23 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
import java.util.Optional;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
|
||||
class PhoneNumberIdentifiersTest {
|
||||
|
||||
@@ -25,7 +33,7 @@ class PhoneNumberIdentifiersTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
phoneNumberIdentifiers = new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
phoneNumberIdentifiers = new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
Tables.PNI.tableName());
|
||||
}
|
||||
|
||||
@@ -34,28 +42,151 @@ class PhoneNumberIdentifiersTest {
|
||||
final String number = "+18005551234";
|
||||
final String differentNumber = "+18005556789";
|
||||
|
||||
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
|
||||
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
|
||||
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
|
||||
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
|
||||
|
||||
assertEquals(firstPni, secondPni);
|
||||
assertNotEquals(firstPni, phoneNumberIdentifiers.getPhoneNumberIdentifier(differentNumber));
|
||||
assertNotEquals(firstPni, phoneNumberIdentifiers.getPhoneNumberIdentifier(differentNumber).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatePhoneNumberIdentifierIfNotExists() {
|
||||
final String number = "+18005551234";
|
||||
void generatePhoneNumberIdentifier() {
|
||||
final List<String> numbers = List.of("+18005551234", "+18005556789");
|
||||
// Should set both PNIs to a new random PNI
|
||||
final UUID pni = phoneNumberIdentifiers.setPniIfRequired(numbers.getFirst(), numbers, Collections.emptyMap()).join();
|
||||
|
||||
assertEquals(phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number),
|
||||
phoneNumberIdentifiers.generatePhoneNumberIdentifierIfNotExists(number));
|
||||
assertEquals(pni, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getFirst()).join());
|
||||
assertEquals(pni, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getLast()).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPhoneNumber() {
|
||||
final String number = "+18005551234";
|
||||
void generatePhoneNumberIdentifierOneFormExists() {
|
||||
final String firstNumber = "+18005551234";
|
||||
final String secondNumber = "+18005556789";
|
||||
final String thirdNumber = "+1800555456";
|
||||
final List<String> allNumbers = List.of(firstNumber, secondNumber, thirdNumber);
|
||||
|
||||
assertFalse(phoneNumberIdentifiers.getPhoneNumber(UUID.randomUUID()).isPresent());
|
||||
// Set one member of the "same" numbers to a new PNI
|
||||
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(secondNumber).join();
|
||||
|
||||
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
|
||||
assertEquals(Optional.of(number), phoneNumberIdentifiers.getPhoneNumber(pni));
|
||||
final Map<String, UUID> existingAssociations = phoneNumberIdentifiers.fetchPhoneNumbers(allNumbers).join();
|
||||
assertEquals(Map.of(secondNumber, pni), existingAssociations);
|
||||
|
||||
assertEquals(pni, phoneNumberIdentifiers.setPniIfRequired(firstNumber, allNumbers, existingAssociations).join());
|
||||
|
||||
for (String number : allNumbers) {
|
||||
assertEquals(pni, phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPhoneNumberIdentifierExistingMapping() {
|
||||
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
|
||||
final UUID oldFormatPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(oldFormatBeninE164).join();
|
||||
final UUID newFormatPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(newFormatBeninE164).join();
|
||||
assertEquals(oldFormatPni, newFormatPni);
|
||||
}
|
||||
|
||||
@Test
|
||||
void conflictingExistingPnis() {
|
||||
final String firstNumber = "+18005551234";
|
||||
final String secondNumber = "+18005556789";
|
||||
|
||||
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(firstNumber).join();
|
||||
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(secondNumber).join();
|
||||
assertNotEquals(firstPni, secondPni);
|
||||
|
||||
assertEquals(
|
||||
firstPni,
|
||||
phoneNumberIdentifiers.setPniIfRequired(
|
||||
firstNumber, List.of(firstNumber, secondNumber),
|
||||
phoneNumberIdentifiers.fetchPhoneNumbers(List.of(firstNumber, secondNumber)).join()).join());
|
||||
assertEquals(
|
||||
secondPni,
|
||||
phoneNumberIdentifiers.setPniIfRequired(
|
||||
secondNumber, List.of(secondNumber, firstNumber),
|
||||
phoneNumberIdentifiers.fetchPhoneNumbers(List.of(firstNumber, secondNumber)).join()).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void conflictOnOriginalNumber() {
|
||||
final List<String> numbers = List.of("+18005551234", "+18005556789");
|
||||
// Stale view of database where both numbers have no PNI
|
||||
final Map<String, UUID> existingAssociations = Collections.emptyMap();
|
||||
|
||||
// Both numbers have different PNIs
|
||||
final UUID pni1 = phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getFirst()).join();
|
||||
final UUID pni2 = phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getLast()).join();
|
||||
assertNotEquals(pni1, pni2);
|
||||
|
||||
// Should conflict and find that we now have a PNI
|
||||
assertEquals(pni1, phoneNumberIdentifiers.setPniIfRequired(numbers.getFirst(), numbers, existingAssociations).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void conflictOnAlternateNumber() {
|
||||
final List<String> numbers = List.of("+18005551234", "+18005556789");
|
||||
// Stale view of database where both numbers have no PNI
|
||||
final Map<String, UUID> existingAssociations = Collections.emptyMap();
|
||||
|
||||
// the alternate number has a PNI added
|
||||
phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.getLast()).join();
|
||||
|
||||
// Should conflict and fail
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
TransactionCanceledException.class,
|
||||
phoneNumberIdentifiers.setPniIfRequired(numbers.getFirst(), numbers, existingAssociations));
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleAssociations() {
|
||||
final List<String> numbers = List.of("+18005550000", "+18005551111", "+18005552222", "+18005553333", "+1800555444");
|
||||
|
||||
// Set pni1={number1, number2}, pni2={number3}, number0 and number 4 unset
|
||||
final UUID pni1 = phoneNumberIdentifiers.setPniIfRequired(numbers.get(1), numbers.subList(1, 3),
|
||||
Collections.emptyMap()).join();
|
||||
final UUID pni2 = phoneNumberIdentifiers.setPniIfRequired(numbers.get(3), List.of(numbers.get(3)),
|
||||
Collections.emptyMap()).join();
|
||||
|
||||
final Map<String, UUID> existingAssociations = phoneNumberIdentifiers.fetchPhoneNumbers(numbers).join();
|
||||
assertEquals(existingAssociations, Map.of(numbers.get(1), pni1, numbers.get(2), pni1, numbers.get(3), pni2));
|
||||
|
||||
// The unmapped phone numbers should map to the arbitrarily selected PNI (which is selected based on the order
|
||||
// of the numbers)
|
||||
assertEquals(pni1, phoneNumberIdentifiers.setPniIfRequired(numbers.get(0), numbers, existingAssociations).join());
|
||||
assertEquals(pni1, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.get(0)).join());
|
||||
assertEquals(pni1, phoneNumberIdentifiers.getPhoneNumberIdentifier(numbers.get(4)).join());
|
||||
}
|
||||
|
||||
private static class FailN implements Supplier<CompletableFuture<Integer>> {
|
||||
final AtomicInteger numFails;
|
||||
|
||||
FailN(final int numFails) {
|
||||
this.numFails = new AtomicInteger(numFails);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Integer> get() {
|
||||
if (numFails.getAndDecrement() == 0) {
|
||||
return CompletableFuture.completedFuture(7);
|
||||
}
|
||||
return CompletableFuture.failedFuture(new IOException("test"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetry() {
|
||||
assertEquals(7, PhoneNumberIdentifiers.retry(10, IOException.class, new FailN(9)).join());
|
||||
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
IOException.class,
|
||||
PhoneNumberIdentifiers.retry(10, IOException.class, new FailN(10)));
|
||||
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
IOException.class,
|
||||
PhoneNumberIdentifiers.retry(10, RuntimeException.class, new FailN(1)));
|
||||
}
|
||||
}
|
||||
+84
-50
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -12,101 +13,105 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
|
||||
public class RegistrationRecoveryTest {
|
||||
|
||||
private static final MutableClock CLOCK = MockUtils.mutableClock(0);
|
||||
|
||||
private static final Duration EXPIRATION = Duration.ofSeconds(1000);
|
||||
|
||||
private static final String NUMBER = "+18005555555";
|
||||
private static final UUID PNI = UUID.randomUUID();
|
||||
|
||||
private static final SaltedTokenHash ORIGINAL_HASH = SaltedTokenHash.generateFor("pass1");
|
||||
|
||||
private static final SaltedTokenHash ANOTHER_HASH = SaltedTokenHash.generateFor("pass2");
|
||||
|
||||
@RegisterExtension
|
||||
private static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
|
||||
Tables.REGISTRATION_RECOVERY_PASSWORDS);
|
||||
private static final DynamoDbExtension DYNAMO_DB_EXTENSION =
|
||||
new DynamoDbExtension(Tables.REGISTRATION_RECOVERY_PASSWORDS);
|
||||
|
||||
private RegistrationRecoveryPasswords store;
|
||||
private RegistrationRecoveryPasswords registrationRecoveryPasswords;
|
||||
|
||||
private RegistrationRecoveryPasswordsManager manager;
|
||||
|
||||
@BeforeEach
|
||||
public void before() throws Exception {
|
||||
CLOCK.setTimeMillis(Clock.systemUTC().millis());
|
||||
store = new RegistrationRecoveryPasswords(
|
||||
registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName(),
|
||||
EXPIRATION,
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
CLOCK
|
||||
);
|
||||
manager = new RegistrationRecoveryPasswordsManager(store);
|
||||
|
||||
manager = new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLookupAfterWrite() throws Exception {
|
||||
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
|
||||
final long initialExp = fetchTimestamp(NUMBER);
|
||||
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
|
||||
final long initialExp = fetchTimestamp(PNI);
|
||||
final long expectedExpiration = CLOCK.instant().getEpochSecond() + EXPIRATION.getSeconds();
|
||||
assertEquals(expectedExpiration, initialExp);
|
||||
|
||||
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
|
||||
assertTrue(saltedTokenHash.isPresent());
|
||||
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHash.get().salt());
|
||||
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHash.get().hash());
|
||||
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
|
||||
assertTrue(saltedTokenHashByPni.isPresent());
|
||||
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByPni.get().salt());
|
||||
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByPni.get().hash());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLookupAfterRefresh() throws Exception {
|
||||
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
|
||||
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
|
||||
|
||||
CLOCK.increment(50, TimeUnit.SECONDS);
|
||||
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
|
||||
final long updatedExp = fetchTimestamp(NUMBER);
|
||||
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
|
||||
final long updatedExp = fetchTimestamp(PNI);
|
||||
final long expectedExp = CLOCK.instant().getEpochSecond() + EXPIRATION.getSeconds();
|
||||
assertEquals(expectedExp, updatedExp);
|
||||
|
||||
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
|
||||
assertTrue(saltedTokenHash.isPresent());
|
||||
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHash.get().salt());
|
||||
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHash.get().hash());
|
||||
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
|
||||
assertTrue(saltedTokenHashByPni.isPresent());
|
||||
assertEquals(ORIGINAL_HASH.salt(), saltedTokenHashByPni.get().salt());
|
||||
assertEquals(ORIGINAL_HASH.hash(), saltedTokenHashByPni.get().hash());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplace() throws Exception {
|
||||
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
|
||||
store.addOrReplace(NUMBER, ANOTHER_HASH).get();
|
||||
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
|
||||
registrationRecoveryPasswords.addOrReplace(PNI, ANOTHER_HASH).get();
|
||||
|
||||
final Optional<SaltedTokenHash> saltedTokenHash = store.lookup(NUMBER).get();
|
||||
assertTrue(saltedTokenHash.isPresent());
|
||||
assertEquals(ANOTHER_HASH.salt(), saltedTokenHash.get().salt());
|
||||
assertEquals(ANOTHER_HASH.hash(), saltedTokenHash.get().hash());
|
||||
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
|
||||
assertTrue(saltedTokenHashByPni.isPresent());
|
||||
assertEquals(ANOTHER_HASH.salt(), saltedTokenHashByPni.get().salt());
|
||||
assertEquals(ANOTHER_HASH.hash(), saltedTokenHashByPni.get().hash());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove() throws Exception {
|
||||
store.addOrReplace(NUMBER, ORIGINAL_HASH).get();
|
||||
assertTrue(store.lookup(NUMBER).get().isPresent());
|
||||
assertDoesNotThrow(() -> registrationRecoveryPasswords.removeEntry(PNI).join());
|
||||
|
||||
store.removeEntry(NUMBER).get();
|
||||
assertTrue(store.lookup(NUMBER).get().isEmpty());
|
||||
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
|
||||
assertTrue(registrationRecoveryPasswords.lookup(PNI).get().isPresent());
|
||||
|
||||
registrationRecoveryPasswords.removeEntry(PNI).get();
|
||||
assertTrue(registrationRecoveryPasswords.lookup(PNI).get().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,31 +121,60 @@ public class RegistrationRecoveryTest {
|
||||
final byte[] wrongPassword = "qwerty123".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
// initial store
|
||||
manager.storeForCurrentNumber(NUMBER, password).get();
|
||||
assertTrue(manager.verify(NUMBER, password).get());
|
||||
assertFalse(manager.verify(NUMBER, wrongPassword).get());
|
||||
manager.store(PNI, password).get();
|
||||
assertTrue(manager.verify(PNI, password).get());
|
||||
assertFalse(manager.verify(PNI, wrongPassword).get());
|
||||
|
||||
// update
|
||||
manager.storeForCurrentNumber(NUMBER, password).get();
|
||||
assertTrue(manager.verify(NUMBER, password).get());
|
||||
assertFalse(manager.verify(NUMBER, wrongPassword).get());
|
||||
manager.store(PNI, password).get();
|
||||
assertTrue(manager.verify(PNI, password).get());
|
||||
assertFalse(manager.verify(PNI, wrongPassword).get());
|
||||
|
||||
// replace
|
||||
manager.storeForCurrentNumber(NUMBER, updatedPassword).get();
|
||||
assertTrue(manager.verify(NUMBER, updatedPassword).get());
|
||||
assertFalse(manager.verify(NUMBER, password).get());
|
||||
assertFalse(manager.verify(NUMBER, wrongPassword).get());
|
||||
manager.store(PNI, updatedPassword).get();
|
||||
assertTrue(manager.verify(PNI, updatedPassword).get());
|
||||
assertFalse(manager.verify(PNI, password).get());
|
||||
assertFalse(manager.verify(PNI, wrongPassword).get());
|
||||
|
||||
manager.removeForNumber(NUMBER).get();
|
||||
assertFalse(manager.verify(NUMBER, updatedPassword).get());
|
||||
assertFalse(manager.verify(NUMBER, password).get());
|
||||
assertFalse(manager.verify(NUMBER, wrongPassword).get());
|
||||
manager.remove(PNI).get();
|
||||
assertFalse(manager.verify(PNI, updatedPassword).get());
|
||||
assertFalse(manager.verify(PNI, password).get());
|
||||
assertFalse(manager.verify(PNI, wrongPassword).get());
|
||||
}
|
||||
|
||||
private static long fetchTimestamp(final String number) throws ExecutionException, InterruptedException {
|
||||
@Test
|
||||
void getE164AssociatedRegistrationRecoveryPasswords() {
|
||||
final String phoneNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient().putItem(PutItemRequest.builder()
|
||||
.tableName(Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName())
|
||||
.item(Map.of(
|
||||
RegistrationRecoveryPasswords.KEY_PNI, AttributeValues.fromString(PNI.toString()),
|
||||
RegistrationRecoveryPasswords.ATTR_EXP, AttributeValues.fromLong(registrationRecoveryPasswords.expirationSeconds()),
|
||||
RegistrationRecoveryPasswords.ATTR_SALT, AttributeValues.fromString(ORIGINAL_HASH.salt()),
|
||||
RegistrationRecoveryPasswords.ATTR_HASH, AttributeValues.fromString(ORIGINAL_HASH.hash())))
|
||||
.build());
|
||||
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient().putItem(PutItemRequest.builder()
|
||||
.tableName(Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName())
|
||||
.item(Map.of(
|
||||
RegistrationRecoveryPasswords.KEY_PNI, AttributeValues.fromString(phoneNumber),
|
||||
RegistrationRecoveryPasswords.ATTR_EXP, AttributeValues.fromLong(registrationRecoveryPasswords.expirationSeconds()),
|
||||
RegistrationRecoveryPasswords.ATTR_SALT, AttributeValues.fromString(ORIGINAL_HASH.salt()),
|
||||
RegistrationRecoveryPasswords.ATTR_HASH, AttributeValues.fromString(ORIGINAL_HASH.hash())))
|
||||
.build());
|
||||
|
||||
assertEquals(List.of(phoneNumber),
|
||||
registrationRecoveryPasswords.getE164sWithRegistrationRecoveryPasswords(2, 2, Schedulers.parallel())
|
||||
.collectList().block());
|
||||
}
|
||||
|
||||
private static long fetchTimestamp(final UUID phoneNumberIdentifier) throws ExecutionException, InterruptedException {
|
||||
return DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient().getItem(GetItemRequest.builder()
|
||||
.tableName(Tables.REGISTRATION_RECOVERY_PASSWORDS.tableName())
|
||||
.key(Map.of(RegistrationRecoveryPasswords.KEY_E164, AttributeValues.fromString(number)))
|
||||
.key(Map.of(RegistrationRecoveryPasswords.KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.build())
|
||||
.thenApply(getItemResponse -> {
|
||||
final Map<String, AttributeValue> item = getItemResponse.item();
|
||||
|
||||
@@ -85,6 +85,7 @@ public class AuthHelper {
|
||||
|
||||
public static final String UNDISCOVERABLE_NUMBER = "+18005551234";
|
||||
public static final UUID UNDISCOVERABLE_UUID = UUID.randomUUID();
|
||||
public static final UUID UNDISCOVERABLE_PNI = UUID.randomUUID();
|
||||
public static final String UNDISCOVERABLE_PASSWORD = "IT'S A SECRET TO EVERYBODY.";
|
||||
|
||||
public static final ECKeyPair VALID_IDENTITY_KEY_PAIR = Curve.generateKeyPair();
|
||||
@@ -169,7 +170,9 @@ public class AuthHelper {
|
||||
when(VALID_ACCOUNT_TWO.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_TWO);
|
||||
when(UNDISCOVERABLE_ACCOUNT.getNumber()).thenReturn(UNDISCOVERABLE_NUMBER);
|
||||
when(UNDISCOVERABLE_ACCOUNT.getUuid()).thenReturn(UNDISCOVERABLE_UUID);
|
||||
when(UNDISCOVERABLE_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(UNDISCOVERABLE_PNI);
|
||||
when(UNDISCOVERABLE_ACCOUNT.getIdentifier(IdentityType.ACI)).thenReturn(UNDISCOVERABLE_UUID);
|
||||
when(UNDISCOVERABLE_ACCOUNT.getIdentifier(IdentityType.PNI)).thenReturn(UNDISCOVERABLE_PNI);
|
||||
when(VALID_ACCOUNT_3.getNumber()).thenReturn(VALID_NUMBER_3);
|
||||
when(VALID_ACCOUNT_3.getUuid()).thenReturn(VALID_UUID_3);
|
||||
when(VALID_ACCOUNT_3.getPhoneNumberIdentifier()).thenReturn(VALID_PNI_3);
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NumberPrefixTest {
|
||||
|
||||
@Test
|
||||
void testPrefixes() {
|
||||
assertThat(Util.getNumberPrefix("+14151234567")).isEqualTo("+14151");
|
||||
assertThat(Util.getNumberPrefix("+22587654321")).isEqualTo("+2258765");
|
||||
assertThat(Util.getNumberPrefix("+298654321")).isEqualTo("+2986543");
|
||||
assertThat(Util.getNumberPrefix("+12")).isEqualTo("+12");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class UtilTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getAlternateForms(final String phoneNumber, final List<String> expectedAlternateForms) {
|
||||
assertEquals(expectedAlternateForms, Util.getAlternateForms(phoneNumber));
|
||||
}
|
||||
|
||||
static List<Arguments> getAlternateForms() {
|
||||
final String usE164 = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
|
||||
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
|
||||
|
||||
return List.of(
|
||||
Arguments.of(usE164, List.of(usE164)),
|
||||
Arguments.of(newFormatBeninE164, List.of(newFormatBeninE164, oldFormatBeninE164)),
|
||||
Arguments.of(oldFormatBeninE164, List.of(oldFormatBeninE164, newFormatBeninE164))
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"0, 1, false",
|
||||
"123456789, 1, true",
|
||||
"123456789, 123, true",
|
||||
"123456789, 456, false",
|
||||
})
|
||||
void startsWithDecimal(final long number, final long prefix, final boolean expectStartsWithPrefix) {
|
||||
assertEquals(expectStartsWithPrefix, Util.startsWithDecimal(number, prefix));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -99,7 +99,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7),
|
||||
sharedExecutorService);
|
||||
@@ -389,7 +389,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(timestamp)
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.setDestinationServiceId(UUID.randomUUID().toString())
|
||||
|
||||
+2
@@ -73,12 +73,14 @@ class FinishPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
pushNotificationExperimentSamples,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
//noinspection unchecked
|
||||
|
||||
+2
@@ -66,6 +66,8 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
|
||||
+2
@@ -62,12 +62,14 @@ class StartPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
pushNotificationExperimentSamples,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
Submodule spam-filter updated: bbd7628bb5...1134bee676.
Reference in new issue
Block a user