mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:46:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
beeb85cf8d | ||
|
|
ccd860207b | ||
|
|
2c835b5c51 | ||
|
|
5caa951c61 | ||
|
|
4d8c4d6693 | ||
|
|
a9d0574ea8 | ||
|
|
3954494eae | ||
|
|
ed6a2c55eb | ||
|
|
b6ee074149 | ||
|
|
f6b3500e92 | ||
|
|
a71dc48b9b | ||
|
|
bc5eed48c3 | ||
|
|
2ecf3cb303 | ||
|
|
bed33d042a | ||
|
|
d7975626be | ||
|
|
3ac7aba6b2 | ||
|
|
1dde612855 | ||
|
|
4ec97cf006 | ||
|
|
d51c6fd2f8 | ||
|
|
d868e3075c | ||
|
|
ae61ee5486 | ||
|
|
58fd9ddb27 | ||
|
|
a953cb33b7 | ||
|
|
95b90e7c5a | ||
|
|
6a3ecb2881 | ||
|
|
6cf4241283 | ||
|
|
42141e51a1 | ||
|
|
b01945ff50 | ||
|
|
a131f2116f | ||
|
|
625637b888 | ||
|
|
c873f62025 | ||
|
|
43d91e5bd6 | ||
|
|
5c4c729703 | ||
|
|
308da3343d | ||
|
|
48c7572dd5 | ||
|
|
dc5f35460b | ||
|
|
69ea9b0296 | ||
|
|
969c6884c0 | ||
|
|
fcf311aab3 | ||
|
|
888879dfb2 | ||
|
|
e003197f77 | ||
|
|
f57910cd97 |
No files matched your search
@@ -6,7 +6,9 @@
|
||||
package org.signal.event
|
||||
|
||||
import com.google.cloud.logging.Logging
|
||||
import com.google.cloud.logging.LoggingOptions
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.assertDoesNotThrow
|
||||
import org.mockito.Mockito.mock
|
||||
|
||||
class GoogleCloudAdminEventLoggerTest {
|
||||
@@ -19,4 +21,15 @@ class GoogleCloudAdminEventLoggerTest {
|
||||
val event = RemoteConfigDeleteEvent("token", "test")
|
||||
logger.logEvent(event)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetService() {
|
||||
assertDoesNotThrow {
|
||||
// This is a canary for version conflicts between the cloud logging library and protobuf-java
|
||||
LoggingOptions.newBuilder()
|
||||
.setProjectId("test")
|
||||
.build()
|
||||
.getService()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,7 @@ public class TestUser {
|
||||
}
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, "", "", true, new Device.DeviceCapabilities())
|
||||
return new AccountAttributes(true, registrationId, "", "", true, new Device.DeviceCapabilities(false, false, false, false))
|
||||
.withUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.withRecoveryPassword(registrationPassword);
|
||||
}
|
||||
|
||||
@@ -38,16 +38,16 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.19.8</aws.sdk2.version>
|
||||
<aws.sdk2.version>2.20.118</aws.sdk2.version>
|
||||
<braintree.version>3.19.0</braintree.version>
|
||||
<commons-csv.version>1.9.0</commons-csv.version>
|
||||
<commons-io.version>2.9.0</commons-io.version>
|
||||
<dropwizard.version>2.0.34</dropwizard.version>
|
||||
<dropwizard.version>2.1.7</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
|
||||
<google-cloud-libraries.version>26.1.3</google-cloud-libraries.version>
|
||||
<grpc.version>1.51.1</grpc.version> <!-- this should be kept in sync with the value from Google’s libraries-bom -->
|
||||
<google-cloud-libraries.version>26.21.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.56.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.9.0</gson.version>
|
||||
<jackson.version>2.13.4</jackson.version>
|
||||
<jackson.version>2.13.5</jackson.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<kotlin.version>1.8.0</kotlin.version>
|
||||
<kotlinx-serialization.version>1.4.1</kotlinx-serialization.version>
|
||||
@@ -57,9 +57,9 @@
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
<micrometer.version>1.10.3</micrometer.version>
|
||||
<mockito.version>4.11.0</mockito.version>
|
||||
<netty.version>4.1.82.Final</netty.version>
|
||||
<netty.version>4.1.96.Final</netty.version>
|
||||
<opentest4j.version>1.2.0</opentest4j.version>
|
||||
<protobuf.version>3.21.7</protobuf.version>
|
||||
<protobuf.version>3.23.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<pushy.version>0.15.2</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<resilience4j.version>1.7.0</resilience4j.version>
|
||||
|
||||
@@ -84,3 +84,5 @@ currentReportingKey.secret: AAAAAAAAAAA=
|
||||
currentReportingKey.salt: AAAAAAAAAAA=
|
||||
|
||||
turn.secret: AAAAAAAAAAA=
|
||||
|
||||
linkDevice.secret: AAAAAAAAAAA=
|
||||
@@ -112,10 +112,6 @@ dynamoDbTables:
|
||||
messages:
|
||||
tableName: Example_Messages
|
||||
expiration: P30D # Duration of time until rows expire
|
||||
pendingAccounts:
|
||||
tableName: Example_PendingAccounts
|
||||
pendingDevices:
|
||||
tableName: Example_PendingDevices
|
||||
phoneNumberIdentifiers:
|
||||
tableName: Example_PhoneNumberIdentifiers
|
||||
profiles:
|
||||
@@ -247,6 +243,9 @@ recaptcha:
|
||||
hCaptcha:
|
||||
apiKey: secret://hCaptcha.apiKey
|
||||
|
||||
shortCode:
|
||||
baseUrl: https://example.com/shortcodes/
|
||||
|
||||
storageService:
|
||||
uri: storage.example.com
|
||||
userAuthenticationTokenSharedSecret: secret://storageService.userAuthenticationTokenSharedSecret
|
||||
@@ -434,3 +433,9 @@ registrationService:
|
||||
|
||||
turn:
|
||||
secret: secret://turn.secret
|
||||
|
||||
commandStopListener:
|
||||
path: /example/path
|
||||
|
||||
linkDevice:
|
||||
secret: secret://linkDevice.secret
|
||||
+1
-1
@@ -436,7 +436,7 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>1.21.1</version>
|
||||
<version>1.23.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
+40
@@ -26,6 +26,7 @@ import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CommandStopListenerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientConfiguration;
|
||||
@@ -34,7 +35,9 @@ import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
|
||||
import org.whispersystems.textsecuregcm.configuration.HCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
@@ -47,6 +50,7 @@ import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ShortCodeExpanderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
@@ -199,6 +203,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private HCaptchaConfiguration hCaptcha;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ShortCodeExpanderConfiguration shortCode;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -288,6 +297,21 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private ClientReleaseConfiguration clientRelease = new ClientReleaseConfiguration(Duration.ofHours(4));
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private MessageByteLimitCardinalityEstimatorConfiguration messageByteLimitCardinalityEstimator = new MessageByteLimitCardinalityEstimatorConfiguration(Duration.ofDays(1));
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private CommandStopListenerConfiguration commandStopListener;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private LinkDeviceSecretConfiguration linkDevice;
|
||||
|
||||
public AdminEventLoggingConfiguration getAdminEventLoggingConfiguration() {
|
||||
return adminEventLoggingConfiguration;
|
||||
}
|
||||
@@ -316,6 +340,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return hCaptcha;
|
||||
}
|
||||
|
||||
public ShortCodeExpanderConfiguration getShortCodeRetrieverConfiguration() {
|
||||
return shortCode;
|
||||
}
|
||||
|
||||
public WebSocketConfiguration getWebSocketConfiguration() {
|
||||
return webSocket;
|
||||
}
|
||||
@@ -478,4 +506,16 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public ClientReleaseConfiguration getClientReleaseConfiguration() {
|
||||
return clientRelease;
|
||||
}
|
||||
|
||||
public MessageByteLimitCardinalityEstimatorConfiguration getMessageByteLimitCardinalityEstimator() {
|
||||
return messageByteLimitCardinalityEstimator;
|
||||
}
|
||||
|
||||
public CommandStopListenerConfiguration getCommandStopListener() {
|
||||
return commandStopListener;
|
||||
}
|
||||
|
||||
public LinkDeviceSecretConfiguration getLinkDeviceSecretConfiguration() {
|
||||
return linkDevice;
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
|
||||
@@ -115,14 +116,16 @@ import org.whispersystems.textsecuregcm.controllers.VerificationController;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcServerManagedWrapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.UserAgentInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcServerManagedWrapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.UserAgentInterceptor;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -188,9 +191,7 @@ import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
@@ -228,6 +229,7 @@ import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsPr
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
|
||||
public class WhisperServerService extends Application<WhisperServerConfiguration> {
|
||||
@@ -349,10 +351,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
config.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
config.getReportMessageConfiguration().getReportTtl());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
config.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
VerificationCodeStore pendingDevices = new VerificationCodeStore(dynamoDbClient,
|
||||
config.getDynamoDbTables().getPendingDevices().getTableName());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
@@ -506,8 +504,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor,
|
||||
keyspaceNotificationDispatchExecutor);
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
StoredVerificationCodeManager pendingDevicesManager = new StoredVerificationCodeManager(pendingDevices);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messagesCluster,
|
||||
keyspaceNotificationDispatchExecutor, messageDeliveryScheduler, messageDeletionAsyncExecutor, clock);
|
||||
@@ -524,7 +520,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, deletedAccounts, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client,
|
||||
secureStorageClient, secureBackupClient, secureValueRecovery2Client,
|
||||
clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, clock);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
@@ -571,6 +567,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
|
||||
config.getTurnSecretConfiguration().secret().value());
|
||||
|
||||
final CardinalityEstimator messageByteLimitCardinalityEstimator = new CardinalityEstimator(
|
||||
rateLimitersCluster,
|
||||
"message_byte_limit",
|
||||
config.getMessageByteLimitCardinalityEstimator().period());
|
||||
|
||||
RecaptchaClient recaptchaClient = new RecaptchaClient(
|
||||
config.getRecaptchaConfiguration().projectPath(),
|
||||
useSecondaryCredentialsJson
|
||||
@@ -581,7 +582,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.connectTimeout(Duration.ofSeconds(10)).build();
|
||||
HCaptchaClient hCaptchaClient = new HCaptchaClient(config.getHCaptchaConfiguration().apiKey().value(), hcaptchaHttpClient,
|
||||
dynamicConfigurationManager);
|
||||
CaptchaChecker captchaChecker = new CaptchaChecker(List.of(recaptchaClient, hCaptchaClient));
|
||||
HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(10)).build();
|
||||
ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
|
||||
CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, List.of(recaptchaClient, hCaptchaClient));
|
||||
|
||||
PushChallengeManager pushChallengeManager = new PushChallengeManager(pushNotificationManager,
|
||||
pushChallengeDynamoDb);
|
||||
@@ -616,6 +620,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.credentialsProvider(cdnCredentialsProvider)
|
||||
.region(Region.of(config.getCdnConfiguration().region()))
|
||||
.build();
|
||||
S3AsyncClient asyncCdnS3Client = S3AsyncClient.builder()
|
||||
.credentialsProvider(cdnCredentialsProvider)
|
||||
.region(Region.of(config.getCdnConfiguration().region()))
|
||||
.build();
|
||||
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
|
||||
config.getGcpAttachmentsConfiguration().domain(),
|
||||
@@ -647,7 +655,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(new MetricCollectingServerInterceptor(Metrics.globalRegistry))
|
||||
.addService(ServerInterceptors.intercept(new KeysGrpcService(accountsManager, keys, rateLimiters), basicCredentialAuthenticationInterceptor))
|
||||
.addService(new KeysAnonymousGrpcService(accountsManager, keys));
|
||||
.addService(new KeysAnonymousGrpcService(accountsManager, keys))
|
||||
.addService(ServerInterceptors.intercept(new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
config.getBadges(), asyncCdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner, config.getCdnConfiguration().bucket()), basicCredentialAuthenticationInterceptor));
|
||||
|
||||
RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
environment.servlets()
|
||||
@@ -664,7 +674,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new MetricsApplicationEventListener(TrafficSource.HTTP));
|
||||
environment.jersey().register(new MetricsApplicationEventListener(TrafficSource.HTTP, clientReleaseManager));
|
||||
environment.jersey()
|
||||
.register(new PolymorphicAuthDynamicFeature<>(ImmutableMap.of(AuthenticatedAccount.class, accountAuthFilter,
|
||||
DisabledPermittedAuthenticatedAccount.class, disabledPermittedAccountAuthFilter)));
|
||||
@@ -684,7 +694,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
|
||||
|
||||
// these should be common, but use @Auth DisabledPermittedAccount, which isn’t supported yet on websocket
|
||||
@@ -751,13 +761,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new CallLinkController(rateLimiters, genericZkSecretParams),
|
||||
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(), config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()), zkAuthOperations, genericZkSecretParams, clock),
|
||||
new ChallengeController(rateLimitChallengeManager),
|
||||
new DeviceController(pendingDevicesManager, accountsManager, messagesManager, keys, rateLimiters, config.getMaxDevices()),
|
||||
new DeviceController(config.getLinkDeviceSecretConfiguration().secret().value(), accountsManager, messagesManager, keys, rateLimiters,
|
||||
rateLimitersCluster, config.getMaxDevices(), clock),
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
ReceiptCredentialPresentation::new),
|
||||
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccounts,
|
||||
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
|
||||
messageDeliveryScheduler, reportSpamTokenProvider, clientReleaseManager, dynamicConfigurationManager),
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
|
||||
accountsManager, deletedAccounts, messagesManager, pushNotificationManager, reportMessageManager,
|
||||
multiRecipientMessageExecutor, messageDeliveryScheduler, reportSpamTokenProvider, clientReleaseManager,
|
||||
dynamicConfigurationManager),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
|
||||
@@ -796,7 +808,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), 60000);
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
|
||||
|
||||
registerCorsFilter(environment);
|
||||
|
||||
-9
@@ -32,9 +32,6 @@ public class BaseAccountAuthenticator {
|
||||
private static final String AUTHENTICATION_SUCCEEDED_TAG_NAME = "succeeded";
|
||||
private static final String AUTHENTICATION_FAILURE_REASON_TAG_NAME = "reason";
|
||||
private static final String ENABLED_TAG_NAME = "enabled";
|
||||
private static final String AUTHENTICATION_HAS_STORY_CAPABILITY = "hasStoryCapability";
|
||||
|
||||
private static final String STORY_ADOPTION_COUNTER_NAME = name(BaseAccountAuthenticator.class, "storyAdoption");
|
||||
|
||||
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(BaseAccountAuthenticator.class, "daysSinceLastSeen");
|
||||
private static final String IS_PRIMARY_DEVICE_TAG = "isPrimary";
|
||||
@@ -75,7 +72,6 @@ public class BaseAccountAuthenticator {
|
||||
public Optional<AuthenticatedAccount> authenticate(BasicCredentials basicCredentials, boolean enabledRequired) {
|
||||
boolean succeeded = false;
|
||||
String failureReason = null;
|
||||
boolean hasStoryCapability = false;
|
||||
|
||||
try {
|
||||
final UUID accountUuid;
|
||||
@@ -94,8 +90,6 @@ public class BaseAccountAuthenticator {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
hasStoryCapability = account.map(Account::isStoriesSupported).orElse(false);
|
||||
|
||||
Optional<Device> device = account.get().getDevice(deviceId);
|
||||
|
||||
if (device.isEmpty()) {
|
||||
@@ -150,9 +144,6 @@ public class BaseAccountAuthenticator {
|
||||
}
|
||||
|
||||
Metrics.counter(AUTHENTICATION_COUNTER_NAME, tags).increment();
|
||||
|
||||
Tags storyTags = Tags.of(AUTHENTICATION_HAS_STORY_CAPABILITY, String.valueOf(hasStoryCapability));
|
||||
Metrics.counter(STORY_ADOPTION_COUNTER_NAME, storyTags).increment();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public record StoredVerificationCode(@Nullable String code,
|
||||
long timestamp,
|
||||
@Nullable String pushCode,
|
||||
@Nullable byte[] sessionId) {
|
||||
|
||||
public static final Duration EXPIRATION = Duration.ofMinutes(10);
|
||||
|
||||
public boolean isValid(String theirCodeString) {
|
||||
if (Util.isEmpty(code) || Util.isEmpty(theirCodeString)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] ourCode = code.getBytes();
|
||||
byte[] theirCode = theirCodeString.getBytes();
|
||||
|
||||
return MessageDigest.isEqual(ourCode, theirCode);
|
||||
}
|
||||
}
|
||||
@@ -5,30 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TurnToken {
|
||||
|
||||
@JsonProperty
|
||||
private String username;
|
||||
|
||||
@JsonProperty
|
||||
private String password;
|
||||
|
||||
@JsonProperty
|
||||
private List<String> urls;
|
||||
|
||||
public TurnToken(String username, String password, List<String> urls) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.urls = urls;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
List<String> getUrls() {
|
||||
return urls;
|
||||
}
|
||||
public record TurnToken(String username, String password, List<String> urls) {
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class TurnTokenGenerator {
|
||||
|
||||
@@ -39,9 +40,9 @@ public class TurnTokenGenerator {
|
||||
this.turnSecret = turnSecret;
|
||||
}
|
||||
|
||||
public TurnToken generate(final String e164) {
|
||||
public TurnToken generate(final UUID aci) {
|
||||
try {
|
||||
final List<String> urls = urls(e164);
|
||||
final List<String> urls = urls(aci);
|
||||
final Mac mac = Mac.getInstance(ALGORITHM);
|
||||
final long validUntilSeconds = Instant.now().plus(Duration.ofDays(1)).getEpochSecond();
|
||||
final long user = Util.ensureNonNegativeInt(new SecureRandom().nextInt());
|
||||
@@ -56,12 +57,12 @@ public class TurnTokenGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> urls(final String e164) {
|
||||
private List<String> urls(final UUID aci) {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
|
||||
// Check if number is enrolled to test out specific turn servers
|
||||
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
|
||||
.filter(config -> config.getEnrolledNumbers().contains(e164))
|
||||
.filter(config -> config.getEnrolledAcis().contains(aci))
|
||||
.findFirst();
|
||||
|
||||
if (enrolled.isPresent()) {
|
||||
|
||||
@@ -29,9 +29,15 @@ public class CaptchaChecker {
|
||||
@VisibleForTesting
|
||||
static final String SEPARATOR = ".";
|
||||
|
||||
private static final String SHORT_SUFFIX = "-short";
|
||||
|
||||
private final ShortCodeExpander shortCodeExpander;
|
||||
private final Map<String, CaptchaClient> captchaClientMap;
|
||||
|
||||
public CaptchaChecker(final List<CaptchaClient> captchaClients) {
|
||||
public CaptchaChecker(
|
||||
final ShortCodeExpander shortCodeRetriever,
|
||||
final List<CaptchaClient> captchaClients) {
|
||||
this.shortCodeExpander = shortCodeRetriever;
|
||||
this.captchaClientMap = captchaClients.stream()
|
||||
.collect(Collectors.toMap(CaptchaClient::scheme, Function.identity()));
|
||||
}
|
||||
@@ -63,9 +69,17 @@ public class CaptchaChecker {
|
||||
final String prefix = parts[0];
|
||||
final String siteKey = parts[1].toLowerCase(Locale.ROOT).strip();
|
||||
final String action = parts[2];
|
||||
final String token = parts[3];
|
||||
String token = parts[3];
|
||||
|
||||
final CaptchaClient client = this.captchaClientMap.get(prefix);
|
||||
String provider = prefix;
|
||||
if (prefix.endsWith(SHORT_SUFFIX)) {
|
||||
// This is a "short" solution that points to the actual solution. We need to fetch the
|
||||
// full solution before proceeding
|
||||
provider = prefix.substring(0, prefix.length() - SHORT_SUFFIX.length());
|
||||
token = shortCodeExpander.retrieve(token).orElseThrow(() -> new BadRequestException("invalid shortcode"));
|
||||
}
|
||||
|
||||
final CaptchaClient client = this.captchaClientMap.get(provider);
|
||||
if (client == null) {
|
||||
throw new BadRequestException("invalid captcha scheme");
|
||||
}
|
||||
@@ -92,7 +106,7 @@ public class CaptchaChecker {
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", action,
|
||||
"score", result.getScoreString(),
|
||||
"provider", prefix)
|
||||
"provider", provider)
|
||||
.increment();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.apache.http.HttpStatus;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class ShortCodeExpander {
|
||||
private static final String EXPAND_COUNTER_NAME = name(ShortCodeExpander.class, "expand");
|
||||
|
||||
private final HttpClient client;
|
||||
private final URI shortenerHost;
|
||||
|
||||
public ShortCodeExpander(final HttpClient client, final String shortenerHost) {
|
||||
this.client = client;
|
||||
this.shortenerHost = URI.create(shortenerHost);
|
||||
}
|
||||
|
||||
public Optional<String> retrieve(final String shortCode) throws IOException {
|
||||
final URI uri = shortenerHost.resolve(shortCode);
|
||||
final HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
|
||||
|
||||
try {
|
||||
final HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
Metrics.counter(EXPAND_COUNTER_NAME, "responseCode", Integer.toString(response.statusCode())).increment();
|
||||
return switch (response.statusCode()) {
|
||||
case HttpStatus.SC_OK -> Optional.of(response.body());
|
||||
case HttpStatus.SC_NOT_FOUND -> Optional.empty();
|
||||
default -> throw new IOException("Failed to look up shortcode");
|
||||
};
|
||||
} catch (InterruptedException e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public record CommandStopListenerConfiguration(@NotNull String path) {
|
||||
|
||||
}
|
||||
-18
@@ -56,8 +56,6 @@ public class DynamoDbTables {
|
||||
private final Table kemKeys;
|
||||
private final Table kemLastResortKeys;
|
||||
private final TableWithExpiration messages;
|
||||
private final Table pendingAccounts;
|
||||
private final Table pendingDevices;
|
||||
private final Table phoneNumberIdentifiers;
|
||||
private final Table profiles;
|
||||
private final Table pushChallenge;
|
||||
@@ -79,8 +77,6 @@ public class DynamoDbTables {
|
||||
@JsonProperty("pqKeys") final Table kemKeys,
|
||||
@JsonProperty("pqLastResortKeys") final Table kemLastResortKeys,
|
||||
@JsonProperty("messages") final TableWithExpiration messages,
|
||||
@JsonProperty("pendingAccounts") final Table pendingAccounts,
|
||||
@JsonProperty("pendingDevices") final Table pendingDevices,
|
||||
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
|
||||
@JsonProperty("profiles") final Table profiles,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@@ -101,8 +97,6 @@ public class DynamoDbTables {
|
||||
this.kemKeys = kemKeys;
|
||||
this.kemLastResortKeys = kemLastResortKeys;
|
||||
this.messages = messages;
|
||||
this.pendingAccounts = pendingAccounts;
|
||||
this.pendingDevices = pendingDevices;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.profiles = profiles;
|
||||
this.pushChallenge = pushChallenge;
|
||||
@@ -174,18 +168,6 @@ public class DynamoDbTables {
|
||||
return messages;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getPendingAccounts() {
|
||||
return pendingAccounts;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getPendingDevices() {
|
||||
return pendingDevices;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getPhoneNumberIdentifiers() {
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
|
||||
public record LinkDeviceSecretConfiguration(SecretBytes secret) {
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
public record MessageByteLimitCardinalityEstimatorConfiguration(@NotNull Duration period) {}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
public record ShortCodeExpanderConfiguration(String baseUrl) {
|
||||
}
|
||||
+5
-3
@@ -6,6 +6,7 @@ import javax.validation.constraints.NotNull;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class TurnUriConfiguration {
|
||||
@JsonProperty
|
||||
@@ -22,7 +23,8 @@ public class TurnUriConfiguration {
|
||||
/**
|
||||
* Enrolled numbers will always get this uri list
|
||||
*/
|
||||
private Set<String> enrolledNumbers = Collections.emptySet();
|
||||
@JsonProperty
|
||||
private Set<UUID> enrolledAcis = Collections.emptySet();
|
||||
|
||||
public List<String> getUris() {
|
||||
return uris;
|
||||
@@ -32,7 +34,7 @@ public class TurnUriConfiguration {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public Set<String> getEnrolledNumbers() {
|
||||
return Collections.unmodifiableSet(enrolledNumbers);
|
||||
public Set<UUID> getEnrolledAcis() {
|
||||
return Collections.unmodifiableSet(enrolledAcis);
|
||||
}
|
||||
}
|
||||
+2
-19
@@ -4,7 +4,6 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -91,16 +90,14 @@ public class AccountController {
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/turn/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public TurnToken getTurnToken(@Auth AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
rateLimiters.getTurnLimiter().validate(auth.getAccount().getUuid());
|
||||
return turnTokenGenerator.generate(auth.getAccount().getNumber());
|
||||
return turnTokenGenerator.generate(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -124,7 +121,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
@ChangesDeviceEnabledState
|
||||
@@ -139,7 +135,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/apn/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -165,7 +160,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
@ChangesDeviceEnabledState
|
||||
@@ -175,6 +169,7 @@ public class AccountController {
|
||||
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
d.setApnId(null);
|
||||
d.setVoipApnId(null);
|
||||
d.setFetchesMessages(false);
|
||||
if (d.getId() == 1) {
|
||||
d.setUserAgent("OWI");
|
||||
@@ -184,7 +179,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
@@ -195,14 +189,12 @@ public class AccountController {
|
||||
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/registration_lock")
|
||||
public void removeRegistrationLock(@Auth AuthenticatedAccount auth) {
|
||||
accounts.update(auth.getAccount(), a -> a.setRegistrationLock(null, null));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/name/")
|
||||
public void setName(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth, @NotNull @Valid DeviceName deviceName) {
|
||||
@@ -211,7 +203,6 @@ public class AccountController {
|
||||
accounts.updateDevice(account, device.getId(), d -> d.setName(deviceName.getDeviceName()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/attributes/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -268,7 +259,6 @@ public class AccountController {
|
||||
auth.getAccount().isStorageSupported());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/username_hash")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -285,7 +275,6 @@ public class AccountController {
|
||||
accounts.clearUsernameHash(auth.getAccount());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/username_hash/reserve")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -325,7 +314,6 @@ public class AccountController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/username_hash/confirm")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -370,7 +358,6 @@ public class AccountController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/username_hash/{usernameHash}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -408,7 +395,6 @@ public class AccountController {
|
||||
.orElseThrow(() -> new WebApplicationException(Status.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/username_link")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -443,7 +429,6 @@ public class AccountController {
|
||||
return new UsernameLinkHandle(usernameLinkHandle);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/username_link")
|
||||
@Operation(
|
||||
@@ -462,7 +447,6 @@ public class AccountController {
|
||||
clearUsernameLink(auth.getAccount());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/username_link/{uuid}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -518,7 +502,6 @@ public class AccountController {
|
||||
return Response.status(maybeAccount.map(ignored -> Status.OK).orElse(Status.NOT_FOUND)).build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
public void deleteAccount(@Auth DisabledPermittedAuthenticatedAccount auth) throws InterruptedException {
|
||||
|
||||
-5
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -76,7 +75,6 @@ public class AccountControllerV2 {
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/number")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -155,7 +153,6 @@ public class AccountControllerV2 {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/phone_number_identity_key_distribution")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -208,7 +205,6 @@ public class AccountControllerV2 {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/phone_number_discoverability")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -221,7 +217,6 @@ public class AccountControllerV2 {
|
||||
phoneNumberDiscoverability.discoverableByPhoneNumber()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/data_report")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.UUID;
|
||||
@@ -40,7 +39,6 @@ public class ArtController {
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-2
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -48,7 +47,6 @@ public class AttachmentControllerV2 {
|
||||
this.policySigner = new PolicySigner(accessSecret, region);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
|
||||
-8
@@ -5,17 +5,13 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
@@ -25,9 +21,6 @@ import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
|
||||
import org.whispersystems.textsecuregcm.gcp.CanonicalRequest;
|
||||
import org.whispersystems.textsecuregcm.gcp.CanonicalRequestGenerator;
|
||||
import org.whispersystems.textsecuregcm.gcp.CanonicalRequestSigner;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
|
||||
@@ -51,7 +44,6 @@ public class AttachmentControllerV3 {
|
||||
this.secureRandom = new SecureRandom();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
|
||||
-4
@@ -5,13 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
@@ -20,7 +18,6 @@ import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
@@ -62,7 +59,6 @@ public class AttachmentControllerV4 {
|
||||
);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
|
||||
+9
-11
@@ -1,9 +1,17 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -12,15 +20,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateCallLinkCredential;
|
||||
import org.whispersystems.textsecuregcm.entities.GetCreateCallLinkCredentialsRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
@Path("/v1/call-link")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "CallLink")
|
||||
@@ -36,7 +35,6 @@ public class CallLinkController {
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/create-auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
+1
-6
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -20,7 +19,6 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
@@ -31,12 +29,11 @@ import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
@@ -68,7 +65,6 @@ public class CertificateController {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/delivery")
|
||||
@@ -87,7 +83,6 @@ public class CertificateController {
|
||||
certificateGenerator.createFor(auth.getAccount(), auth.getAuthenticatedDevice(), includeE164));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/auth/group")
|
||||
|
||||
-4
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -20,7 +19,6 @@ import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.Consumes;
|
||||
@@ -53,7 +51,6 @@ public class ChallengeController {
|
||||
this.rateLimitChallengeManager = rateLimitChallengeManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -110,7 +107,6 @@ public class ChallengeController {
|
||||
return Response.status(200).build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/push")
|
||||
@Operation(
|
||||
|
||||
+137
-54
@@ -4,20 +4,31 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.security.SecureRandom;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.Consumes;
|
||||
@@ -39,7 +50,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
@@ -48,13 +58,13 @@ import org.whispersystems.textsecuregcm.entities.DeviceResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.util.VerificationCode;
|
||||
@@ -65,28 +75,48 @@ public class DeviceController {
|
||||
|
||||
static final int MAX_DEVICES = 6;
|
||||
|
||||
private final StoredVerificationCodeManager pendingDevices;
|
||||
private final Key verificationTokenKey;
|
||||
private final AccountsManager accounts;
|
||||
private final MessagesManager messages;
|
||||
private final KeysManager keys;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final FaultTolerantRedisCluster usedTokenCluster;
|
||||
private final Map<String, Integer> maxDeviceConfiguration;
|
||||
|
||||
public DeviceController(StoredVerificationCodeManager pendingDevices,
|
||||
private final Clock clock;
|
||||
|
||||
private static final String VERIFICATION_TOKEN_ALGORITHM = "HmacSHA256";
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration TOKEN_EXPIRATION_DURATION = Duration.ofMinutes(10);
|
||||
|
||||
public DeviceController(byte[] linkDeviceSecret,
|
||||
AccountsManager accounts,
|
||||
MessagesManager messages,
|
||||
KeysManager keys,
|
||||
RateLimiters rateLimiters,
|
||||
Map<String, Integer> maxDeviceConfiguration) {
|
||||
this.pendingDevices = pendingDevices;
|
||||
FaultTolerantRedisCluster usedTokenCluster,
|
||||
Map<String, Integer> maxDeviceConfiguration, final Clock clock) {
|
||||
this.verificationTokenKey = new SecretKeySpec(linkDeviceSecret, VERIFICATION_TOKEN_ALGORITHM);
|
||||
this.accounts = accounts;
|
||||
this.messages = messages;
|
||||
this.keys = keys;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usedTokenCluster = usedTokenCluster;
|
||||
this.maxDeviceConfiguration = maxDeviceConfiguration;
|
||||
this.clock = clock;
|
||||
|
||||
// Fail fast: reject bad keys
|
||||
try {
|
||||
final Mac mac = Mac.getInstance(VERIFICATION_TOKEN_ALGORITHM);
|
||||
mac.init(verificationTokenKey);
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("All Java implementations must support HmacSHA256", e);
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public DeviceInfoList getDevices(@Auth AuthenticatedAccount auth) {
|
||||
@@ -100,7 +130,6 @@ public class DeviceController {
|
||||
return new DeviceInfoList(devices);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{device_id}")
|
||||
@@ -113,15 +142,14 @@ public class DeviceController {
|
||||
|
||||
final CompletableFuture<Void> deleteKeysFuture = keys.delete(account.getUuid(), deviceId);
|
||||
|
||||
messages.clear(account.getUuid(), deviceId);
|
||||
messages.clear(account.getUuid(), deviceId).join();
|
||||
account = accounts.update(account, a -> a.removeDevice(deviceId));
|
||||
// ensure any messages that came in after the first clear() are also removed
|
||||
messages.clear(account.getUuid(), deviceId);
|
||||
messages.clear(account.getUuid(), deviceId).join();
|
||||
|
||||
deleteKeysFuture.join();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/provisioning/code")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -146,20 +174,13 @@ public class DeviceController {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
VerificationCode verificationCode = generateVerificationCode();
|
||||
StoredVerificationCode storedVerificationCode =
|
||||
new StoredVerificationCode(verificationCode.getVerificationCode(), System.currentTimeMillis(), null, null);
|
||||
|
||||
pendingDevices.store(account.getNumber(), storedVerificationCode);
|
||||
|
||||
return verificationCode;
|
||||
return new VerificationCode(generateVerificationToken(account.getUuid()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated callers should use {@link #linkDevice(BasicAuthorizationHeader, LinkDeviceRequest, ContainerRequest)}
|
||||
* instead
|
||||
*/
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -172,8 +193,7 @@ public class DeviceController {
|
||||
@Context ContainerRequest containerRequest)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
final Pair<Account, Device> accountAndDevice = createDevice(authorizationHeader.getUsername(),
|
||||
authorizationHeader.getPassword(),
|
||||
final Pair<Account, Device> accountAndDevice = createDevice(authorizationHeader.getPassword(),
|
||||
verificationCode,
|
||||
accountAttributes,
|
||||
containerRequest,
|
||||
@@ -185,7 +205,6 @@ public class DeviceController {
|
||||
return new DeviceResponse(account.getUuid(), account.getPhoneNumberIdentifier(), device.getId());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -207,8 +226,7 @@ public class DeviceController {
|
||||
@Context ContainerRequest containerRequest)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
final Pair<Account, Device> accountAndDevice = createDevice(authorizationHeader.getUsername(),
|
||||
authorizationHeader.getPassword(),
|
||||
final Pair<Account, Device> accountAndDevice = createDevice(authorizationHeader.getPassword(),
|
||||
linkDeviceRequest.verificationCode(),
|
||||
linkDeviceRequest.accountAttributes(),
|
||||
containerRequest,
|
||||
@@ -220,7 +238,6 @@ public class DeviceController {
|
||||
return new DeviceResponse(account.getUuid(), account.getPhoneNumberIdentifier(), device.getId());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/unauthenticated_delivery")
|
||||
@@ -229,7 +246,6 @@ public class DeviceController {
|
||||
// Deprecated
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
@@ -239,44 +255,104 @@ public class DeviceController {
|
||||
accounts.updateDevice(auth.getAccount(), deviceId, d -> d.setCapabilities(capabilities));
|
||||
}
|
||||
|
||||
@VisibleForTesting protected VerificationCode generateVerificationCode() {
|
||||
SecureRandom random = new SecureRandom();
|
||||
int randomInt = 100000 + random.nextInt(900000);
|
||||
return new VerificationCode(randomInt);
|
||||
private Mac getInitializedMac() {
|
||||
try {
|
||||
final Mac mac = Mac.getInstance(VERIFICATION_TOKEN_ALGORITHM);
|
||||
mac.init(verificationTokenKey);
|
||||
|
||||
return mac;
|
||||
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
// All Java implementations must support HmacSHA256 and we checked the key at construction time, so this can never
|
||||
// happen
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String generateVerificationToken(final UUID aci) {
|
||||
final String claims = aci + "." + clock.instant().toEpochMilli();
|
||||
final byte[] signature = getInitializedMac().doFinal(claims.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return claims + ":" + Base64.getUrlEncoder().encodeToString(signature);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Optional<UUID> checkVerificationToken(final String verificationToken) {
|
||||
final boolean tokenUsed = usedTokenCluster.withCluster(connection ->
|
||||
connection.sync().get(getUsedTokenKey(verificationToken)) != null);
|
||||
|
||||
if (tokenUsed) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final String[] claimsAndSignature = verificationToken.split(":", 2);
|
||||
|
||||
if (claimsAndSignature.length != 2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final byte[] expectedSignature = getInitializedMac().doFinal(claimsAndSignature[0].getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] providedSignature;
|
||||
|
||||
try {
|
||||
providedSignature = Base64.getUrlDecoder().decode(claimsAndSignature[1]);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (!MessageDigest.isEqual(expectedSignature, providedSignature)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final String[] aciAndTimestamp = claimsAndSignature[0].split("\\.", 2);
|
||||
|
||||
if (aciAndTimestamp.length != 2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final UUID aci;
|
||||
|
||||
try {
|
||||
aci = UUID.fromString(aciAndTimestamp[0]);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final Instant timestamp;
|
||||
|
||||
try {
|
||||
timestamp = Instant.ofEpochMilli(Long.parseLong(aciAndTimestamp[1]));
|
||||
} catch (final NumberFormatException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final Instant tokenExpiration = timestamp.plus(TOKEN_EXPIRATION_DURATION);
|
||||
|
||||
if (tokenExpiration.isBefore(clock.instant())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.of(aci);
|
||||
}
|
||||
|
||||
static boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities) {
|
||||
boolean isDowngrade = false;
|
||||
|
||||
isDowngrade |= account.isStoriesSupported() && !capabilities.isStories();
|
||||
isDowngrade |= account.isPniSupported() && !capabilities.isPni();
|
||||
isDowngrade |= account.isChangeNumberSupported() && !capabilities.isChangeNumber();
|
||||
isDowngrade |= account.isAnnouncementGroupSupported() && !capabilities.isAnnouncementGroup();
|
||||
isDowngrade |= account.isSenderKeySupported() && !capabilities.isSenderKey();
|
||||
isDowngrade |= account.isGiftBadgesSupported() && !capabilities.isGiftBadges();
|
||||
|
||||
return isDowngrade;
|
||||
return account.isPniSupported() && !capabilities.pni();
|
||||
}
|
||||
|
||||
private Pair<Account, Device> createDevice(final String phoneNumber,
|
||||
final String password,
|
||||
private Pair<Account, Device> createDevice(final String password,
|
||||
final String verificationCode,
|
||||
final AccountAttributes accountAttributes,
|
||||
final ContainerRequest containerRequest,
|
||||
final Optional<DeviceActivationRequest> maybeDeviceActivationRequest)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
rateLimiters.getVerifyDeviceLimiter().validate(phoneNumber);
|
||||
final Optional<UUID> maybeAciFromToken = checkVerificationToken(verificationCode);
|
||||
|
||||
Optional<StoredVerificationCode> storedVerificationCode = pendingDevices.getCodeForNumber(phoneNumber);
|
||||
|
||||
if (storedVerificationCode.isEmpty() || !storedVerificationCode.get().isValid(verificationCode)) {
|
||||
throw new WebApplicationException(Response.status(403).build());
|
||||
}
|
||||
|
||||
final Account account = accounts.getByE164(phoneNumber)
|
||||
final Account account = maybeAciFromToken.flatMap(accounts::getByAccountIdentifier)
|
||||
.orElseThrow(ForbiddenException::new);
|
||||
|
||||
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
|
||||
|
||||
maybeDeviceActivationRequest.ifPresent(deviceActivationRequest -> {
|
||||
assert deviceActivationRequest.aciSignedPreKey().isPresent();
|
||||
assert deviceActivationRequest.pniSignedPreKey().isPresent();
|
||||
@@ -343,7 +419,7 @@ public class DeviceController {
|
||||
keys.delete(a.getUuid(), device.getId()),
|
||||
keys.delete(a.getPhoneNumberIdentifier(), device.getId()));
|
||||
|
||||
messages.clear(a.getUuid(), device.getId());
|
||||
messages.clear(a.getUuid(), device.getId()).join();
|
||||
|
||||
deleteKeysFuture.join();
|
||||
|
||||
@@ -361,8 +437,15 @@ public class DeviceController {
|
||||
a.addDevice(device);
|
||||
});
|
||||
|
||||
pendingDevices.remove(phoneNumber);
|
||||
if (maybeAciFromToken.isPresent()) {
|
||||
usedTokenCluster.useCluster(connection ->
|
||||
connection.sync().set(getUsedTokenKey(verificationCode), "", new SetArgs().ex(TOKEN_EXPIRATION_DURATION)));
|
||||
}
|
||||
|
||||
return new Pair<>(updatedAccount, device);
|
||||
}
|
||||
|
||||
private static String getUsedTokenKey(final String token) {
|
||||
return "usedToken::" + token;
|
||||
}
|
||||
}
|
||||
-2
@@ -4,7 +4,6 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -45,7 +44,6 @@ public class DirectoryV2Controller {
|
||||
this.directoryServiceTokenGenerator = userTokenGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-2
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.time.Clock;
|
||||
@@ -74,7 +73,6 @@ public class DonationController {
|
||||
this.receiptCredentialPresentationFactory = Objects.requireNonNull(receiptCredentialPresentationFactory);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/redeem-receipt")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-3
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -40,7 +39,6 @@ public class KeepAliveController {
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
public Response getKeepAlive(@Auth Optional<AuthenticatedAccount> maybeAuth,
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
@@ -63,7 +61,6 @@ public class KeepAliveController {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/provisioning")
|
||||
public Response getProvisioningKeepAlive() {
|
||||
|
||||
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -107,7 +106,6 @@ public class KeysController {
|
||||
return new PreKeyCount(ecCountFuture.join(), pqCountFuture.join());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -192,7 +190,6 @@ public class KeysController {
|
||||
.join();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/{identifier}/{device_id}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -277,7 +274,6 @@ public class KeysController {
|
||||
return new PreKeyResponse(identityKey, responseItems);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/signed")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
+5
@@ -85,6 +85,7 @@ import org.whispersystems.textsecuregcm.entities.SpamReport;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
@@ -118,6 +119,7 @@ public class MessageController {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private final CardinalityEstimator messageByteLimitEstimator;
|
||||
private final MessageSender messageSender;
|
||||
private final ReceiptSender receiptSender;
|
||||
private final AccountsManager accountsManager;
|
||||
@@ -153,6 +155,7 @@ public class MessageController {
|
||||
|
||||
public MessageController(
|
||||
RateLimiters rateLimiters,
|
||||
CardinalityEstimator messageByteLimitEstimator,
|
||||
MessageSender messageSender,
|
||||
ReceiptSender receiptSender,
|
||||
AccountsManager accountsManager,
|
||||
@@ -166,6 +169,7 @@ public class MessageController {
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.messageByteLimitEstimator = messageByteLimitEstimator;
|
||||
this.messageSender = messageSender;
|
||||
this.receiptSender = receiptSender;
|
||||
this.accountsManager = accountsManager;
|
||||
@@ -237,6 +241,7 @@ public class MessageController {
|
||||
rateLimiters.getInboundMessageBytes().validate(destinationIdentifier.uuid(), totalContentLength);
|
||||
} catch (final RateLimitExceededException e) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getInboundMessageByteLimitConfiguration().enforceInboundLimit()) {
|
||||
messageByteLimitEstimator.add(destinationIdentifier.uuid().toString());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
-3
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import javax.ws.rs.GET;
|
||||
@@ -40,7 +39,6 @@ public class PaymentsController {
|
||||
this.paymentsServiceCredentialsGenerator = paymentsServiceCredentialsGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -48,7 +46,6 @@ public class PaymentsController {
|
||||
return paymentsServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/conversions")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
+4
-76
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Preconditions;
|
||||
import io.dropwizard.auth.Auth;
|
||||
@@ -18,24 +17,18 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.vavr.Tuple;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -88,9 +81,9 @@ import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.UserCapabilities;
|
||||
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -104,7 +97,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
@@ -171,7 +163,6 @@ public class ProfileController {
|
||||
this.batchIdentityCheckExecutor = Preconditions.checkNotNull(batchIdentityCheckExecutor);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -199,7 +190,7 @@ public class ProfileController {
|
||||
final String avatar = switch (request.getAvatarChange()) {
|
||||
case UNCHANGED -> currentAvatar.orElse(null);
|
||||
case CLEAR -> null;
|
||||
case UPDATE -> generateAvatarObjectName();
|
||||
case UPDATE -> ProfileHelper.generateAvatarObjectName();
|
||||
};
|
||||
|
||||
profilesManager.set(auth.getAccount().getUuid(),
|
||||
@@ -220,7 +211,7 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
final List<AccountBadge> updatedBadges = request.getBadges()
|
||||
.map(badges -> mergeBadgeIdsWithExistingAccountBadges(badges, auth.getAccount().getBadges()))
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, auth.getAccount().getBadges()))
|
||||
.orElseGet(() -> auth.getAccount().getBadges());
|
||||
|
||||
accountsManager.update(auth.getAccount(), a -> {
|
||||
@@ -229,13 +220,12 @@ public class ProfileController {
|
||||
});
|
||||
|
||||
if (request.getAvatarChange() == CreateProfileRequest.AvatarChange.UPDATE) {
|
||||
return Response.ok(generateAvatarUploadForm(avatar)).build();
|
||||
return Response.ok(ProfileHelper.generateAvatarUploadForm(policyGenerator, policySigner, avatar)).build();
|
||||
} else {
|
||||
return Response.ok().build();
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}")
|
||||
@@ -256,7 +246,6 @@ public class ProfileController {
|
||||
containerRequestContext);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}/{credentialRequest}")
|
||||
@@ -288,7 +277,6 @@ public class ProfileController {
|
||||
|
||||
// Although clients should generally be using versioned profiles wherever possible, there are still a few lingering
|
||||
// use cases for getting profiles without a version (e.g. getting a contact's unidentified access key checksum).
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}")
|
||||
@@ -331,7 +319,6 @@ public class ProfileController {
|
||||
};
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -477,23 +464,6 @@ public class ProfileController {
|
||||
}
|
||||
}
|
||||
|
||||
private ProfileAvatarUploadAttributes generateAvatarUploadForm(String objectName) {
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
Pair<String, String> policy = policyGenerator.createFor(now, objectName, 10 * 1024 * 1024);
|
||||
String signature = policySigner.getSignature(now, policy.second());
|
||||
|
||||
return new ProfileAvatarUploadAttributes(objectName, policy.first(), "private", "AWS4-HMAC-SHA256",
|
||||
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
|
||||
|
||||
}
|
||||
|
||||
private String generateAvatarObjectName() {
|
||||
byte[] object = new byte[16];
|
||||
new SecureRandom().nextBytes(object);
|
||||
|
||||
return "profiles/" + Base64.getUrlEncoder().encodeToString(object);
|
||||
}
|
||||
|
||||
private List<Locale> getAcceptableLanguagesForRequest(ContainerRequestContext containerRequestContext) {
|
||||
try {
|
||||
return containerRequestContext.getAcceptableLanguages();
|
||||
@@ -509,48 +479,6 @@ public class ProfileController {
|
||||
}
|
||||
}
|
||||
|
||||
private List<AccountBadge> mergeBadgeIdsWithExistingAccountBadges(
|
||||
final List<String> badgeIds,
|
||||
final List<AccountBadge> accountBadges) {
|
||||
LinkedHashMap<String, AccountBadge> existingBadges = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final AccountBadge accountBadge : accountBadges) {
|
||||
existingBadges.putIfAbsent(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
|
||||
LinkedHashMap<String, AccountBadge> result = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final String badgeId : badgeIds) {
|
||||
|
||||
// duplicate in the list, ignore it
|
||||
if (result.containsKey(badgeId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// This is for testing badges and allows them to be added to an account at any time with an expiration of 1 day
|
||||
// in the future.
|
||||
BadgeConfiguration badgeConfiguration = badgeConfigurationMap.get(badgeId);
|
||||
if (badgeConfiguration != null && badgeConfiguration.isTestBadge()) {
|
||||
result.put(badgeId, new AccountBadge(badgeId, clock.instant().plus(Duration.ofDays(1)), true));
|
||||
continue;
|
||||
}
|
||||
|
||||
// reordering or making visible existing badges
|
||||
if (existingBadges.containsKey(badgeId)) {
|
||||
AccountBadge accountBadge = existingBadges.get(badgeId).withVisibility(true);
|
||||
result.put(badgeId, accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
// take any remaining account badges and make them invisible
|
||||
for (final Entry<String, AccountBadge> entry : existingBadges.entrySet()) {
|
||||
if (!result.containsKey(entry.getKey())) {
|
||||
AccountBadge accountBadge = entry.getValue().withVisibility(false);
|
||||
result.put(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayList<>(result.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that the requester has permission to view the profile of the account identified by the given ACI.
|
||||
*
|
||||
|
||||
-2
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.Base64;
|
||||
@@ -37,7 +36,6 @@ public class ProvisioningController {
|
||||
this.provisioningManager = provisioningManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@Path("/{destination}")
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-6
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -34,8 +33,6 @@ import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
@@ -57,8 +54,6 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Registration")
|
||||
public class RegistrationController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
|
||||
|
||||
private static final DistributionSummary REREGISTRATION_IDLE_DAYS_DISTRIBUTION = DistributionSummary
|
||||
.builder(name(RegistrationController.class, "reregistrationIdleDays"))
|
||||
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
|
||||
@@ -90,7 +85,6 @@ public class RegistrationController {
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-4
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
@@ -76,7 +75,6 @@ public class RemoteConfigController {
|
||||
this.googleIdTokenVerifier = googleIdTokenVerifierBuilder.setAudience(audience).build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public UserRemoteConfigList getAll(@Auth AuthenticatedAccount auth) {
|
||||
@@ -98,7 +96,6 @@ public class RemoteConfigController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -123,7 +120,6 @@ public class RemoteConfigController {
|
||||
remoteConfigsManager.set(config);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/{name}")
|
||||
public void delete(@HeaderParam("Config-Token") String configToken, @PathParam("name") String name) {
|
||||
|
||||
-3
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
@@ -69,7 +68,6 @@ public class SecureBackupController {
|
||||
this.accountsManager = requireNonNull(accountsManager);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -86,7 +84,6 @@ public class SecureBackupController {
|
||||
return credentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/auth/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-2
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import javax.ws.rs.GET;
|
||||
@@ -34,7 +33,6 @@ public class SecureStorageController {
|
||||
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-3
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
@@ -66,7 +65,6 @@ public class SecureValueRecovery2Controller {
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -84,7 +82,6 @@ public class SecureValueRecovery2Controller {
|
||||
}
|
||||
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/auth/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-19
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
@@ -220,7 +219,6 @@ public class SubscriptionController {
|
||||
return new GetSubscriptionConfigurationResponse(currencyConfiguration, levels);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/{subscriberId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -242,7 +240,6 @@ public class SubscriptionController {
|
||||
.thenApply(unused -> Response.ok().build());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/{subscriberId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -277,7 +274,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/create_payment_method")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -332,7 +328,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/create_payment_method/paypal")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -396,7 +391,6 @@ public class SubscriptionController {
|
||||
};
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/default_payment_method/{paymentMethodId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -414,7 +408,6 @@ public class SubscriptionController {
|
||||
.thenApply(customer -> Response.ok().build());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/default_payment_method/{processor}/{paymentMethodToken}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -497,7 +490,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/{subscriberId}/level/{level}/{currency}/{idempotencyKey}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -655,7 +647,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/configuration")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -666,7 +657,6 @@ public class SubscriptionController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/levels")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -714,7 +704,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/badges")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -737,7 +726,6 @@ public class SubscriptionController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/amounts")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -749,7 +737,6 @@ public class SubscriptionController {
|
||||
.build());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/amounts/gift")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -801,7 +788,6 @@ public class SubscriptionController {
|
||||
/**
|
||||
* Creates a Stripe PaymentIntent with the requested amount and currency
|
||||
*/
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -855,7 +841,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/paypal/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -898,7 +883,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/paypal/confirm")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -945,7 +929,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -1158,7 +1141,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/{subscriberId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -1236,7 +1218,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
+1
-7
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
@@ -78,8 +77,8 @@ import org.whispersystems.textsecuregcm.registration.TransportNotAllowedExceptio
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.spam.Extract;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThreshold;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
@@ -137,7 +136,6 @@ public class VerificationController {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/session")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -188,7 +186,6 @@ public class VerificationController {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@FilterSpam
|
||||
@PATCH
|
||||
@Path("/session/{sessionId}")
|
||||
@@ -411,7 +408,6 @@ public class VerificationController {
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/session/{sessionId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -423,7 +419,6 @@ public class VerificationController {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -518,7 +513,6 @@ public class VerificationController {
|
||||
return buildResponse(resultSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
public enum AvatarChange {
|
||||
AVATAR_CHANGE_UNCHANGED,
|
||||
AVATAR_CHANGE_CLEAR,
|
||||
AVATAR_CHANGE_UPDATE
|
||||
}
|
||||
+18
-6
@@ -9,11 +9,23 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public record UserCapabilities(
|
||||
@JsonProperty("gv1-migration") boolean gv1Migration,
|
||||
@Deprecated(forRemoval = true)
|
||||
@JsonProperty("gv1-migration")
|
||||
boolean gv1Migration,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean senderKey,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean announcementGroup,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean changeNumber,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean stories,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean giftBadges,
|
||||
boolean paymentActivation,
|
||||
boolean pni) {
|
||||
@@ -21,11 +33,11 @@ public record UserCapabilities(
|
||||
public static UserCapabilities createForAccount(Account account) {
|
||||
return new UserCapabilities(
|
||||
true,
|
||||
account.isSenderKeySupported(),
|
||||
account.isAnnouncementGroupSupported(),
|
||||
account.isChangeNumberSupported(),
|
||||
account.isStoriesSupported(),
|
||||
account.isGiftBadgesSupported(),
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
|
||||
// Hardcode payment activation flag to false until all clients support the flow
|
||||
false,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Status;
|
||||
import org.whispersystems.textsecuregcm.entities.AvatarChange;
|
||||
|
||||
public class AvatarChangeUtil {
|
||||
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileRequest.AvatarChange avatarChangeType) {
|
||||
return switch (avatarChangeType) {
|
||||
case AVATAR_CHANGE_UNCHANGED -> AvatarChange.AVATAR_CHANGE_UNCHANGED;
|
||||
case AVATAR_CHANGE_CLEAR -> AvatarChange.AVATAR_CHANGE_CLEAR;
|
||||
case AVATAR_CHANGE_UPDATE -> AvatarChange.AVATAR_CHANGE_UPDATE;
|
||||
case UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Invalid avatar change value").asRuntimeException();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.signal.chat.calling.GetTurnCredentialsRequest;
|
||||
import org.signal.chat.calling.GetTurnCredentialsResponse;
|
||||
import org.signal.chat.calling.ReactorCallingGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class CallingGrpcService extends ReactorCallingGrpc.CallingImplBase {
|
||||
|
||||
private final TurnTokenGenerator turnTokenGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public CallingGrpcService(final TurnTokenGenerator turnTokenGenerator, final RateLimiters rateLimiters) {
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Throwable onErrorMap(final Throwable throwable) {
|
||||
return RateLimitUtil.mapRateLimitExceededException(throwable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetTurnCredentialsResponse> getTurnCredentials(final GetTurnCredentialsRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
return rateLimiters.getTurnLimiter().validateReactive(authenticatedDevice.accountIdentifier())
|
||||
.then(Mono.fromSupplier(() -> turnTokenGenerator.generate(authenticatedDevice.accountIdentifier())))
|
||||
.map(turnToken -> GetTurnCredentialsResponse.newBuilder()
|
||||
.setUsername(turnToken.username())
|
||||
.setPassword(turnToken.password())
|
||||
.addAllUrls(turnToken.urls())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
|
||||
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
|
||||
import org.signal.chat.profile.ReactorProfileGrpc;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
|
||||
private final Clock clock;
|
||||
|
||||
private final ProfilesManager profilesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
|
||||
private final PolicySigner policySigner;
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
|
||||
private final S3AsyncClient asyncS3client;
|
||||
private final String bucket;
|
||||
|
||||
private record AvatarData(Optional<String> currentAvatar,
|
||||
Optional<String> finalAvatar,
|
||||
Optional<ProfileAvatarUploadAttributes> uploadAttributes) {}
|
||||
|
||||
public ProfileGrpcService(
|
||||
Clock clock,
|
||||
AccountsManager accountsManager,
|
||||
ProfilesManager profilesManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
BadgesConfiguration badgesConfiguration,
|
||||
S3AsyncClient asyncS3client,
|
||||
PostPolicyGenerator policyGenerator,
|
||||
PolicySigner policySigner,
|
||||
String bucket) {
|
||||
this.clock = clock;
|
||||
this.accountsManager = accountsManager;
|
||||
this.profilesManager = profilesManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
|
||||
BadgeConfiguration::getId, Function.identity()));
|
||||
this.bucket = bucket;
|
||||
this.asyncS3client = asyncS3client;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.policySigner = policySigner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<SetProfileResponse> setProfile(SetProfileRequest request) {
|
||||
validateRequest(request);
|
||||
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
|
||||
.flatMap(authenticatedDevice -> Mono.zip(
|
||||
Mono.fromFuture(accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)),
|
||||
Mono.fromFuture(profilesManager.getAsync(authenticatedDevice.accountIdentifier(), request.getVersion()))
|
||||
))
|
||||
.doOnNext(accountAndMaybeProfile -> {
|
||||
if (!request.getPaymentAddress().isEmpty()) {
|
||||
final boolean hasDisallowedPrefix =
|
||||
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
|
||||
.anyMatch(prefix -> accountAndMaybeProfile.getT1().getNumber().startsWith(prefix));
|
||||
if (hasDisallowedPrefix && accountAndMaybeProfile.getT2().map(VersionedProfile::getPaymentAddress).isEmpty()) {
|
||||
throw Status.PERMISSION_DENIED.asRuntimeException();
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatMap(accountAndMaybeProfile -> {
|
||||
final Account account = accountAndMaybeProfile.getT1();
|
||||
final Optional<String> currentAvatar = accountAndMaybeProfile.getT2().map(VersionedProfile::getAvatar)
|
||||
.filter(avatar -> avatar.startsWith("profiles/"));
|
||||
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
|
||||
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
|
||||
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
|
||||
case AVATAR_CHANGE_UPDATE -> {
|
||||
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
|
||||
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
|
||||
Optional.of(ProfileHelper.generateAvatarUploadFormGrpc(policyGenerator, policySigner, updateAvatarObjectName)));
|
||||
}
|
||||
};
|
||||
|
||||
final Mono<Void> profileSetMono = Mono.fromFuture(profilesManager.setAsync(account.getUuid(),
|
||||
new VersionedProfile(
|
||||
request.getVersion(),
|
||||
encodeToBase64(request.getName().toByteArray()),
|
||||
avatarData.finalAvatar().orElse(null),
|
||||
encodeToBase64(request.getAboutEmoji().toByteArray()),
|
||||
encodeToBase64(request.getAbout().toByteArray()),
|
||||
encodeToBase64(request.getPaymentAddress().toByteArray()),
|
||||
request.getCommitment().toByteArray())));
|
||||
|
||||
final List<Mono<?>> updates = new ArrayList<>(2);
|
||||
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, account.getBadges()))
|
||||
.orElseGet(account::getBadges);
|
||||
|
||||
updates.add(Mono.fromFuture(accountsManager.updateAsync(account, a -> {
|
||||
a.setBadges(clock, updatedBadges);
|
||||
a.setCurrentProfileVersion(request.getVersion());
|
||||
})));
|
||||
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
|
||||
updates.add(Mono.fromFuture(asyncS3client.deleteObject(DeleteObjectRequest.builder()
|
||||
.bucket(bucket)
|
||||
.key(avatarData.currentAvatar().get())
|
||||
.build())));
|
||||
}
|
||||
return profileSetMono.thenMany(Flux.merge(updates)).then(Mono.just(avatarData));
|
||||
})
|
||||
.map(avatarData -> avatarData.uploadAttributes()
|
||||
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
|
||||
.orElse(SetProfileResponse.newBuilder().build())
|
||||
);
|
||||
}
|
||||
|
||||
private void validateRequest(SetProfileRequest request) {
|
||||
if (request.getVersion().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asRuntimeException();
|
||||
}
|
||||
|
||||
if (request.getCommitment().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asRuntimeException();
|
||||
}
|
||||
|
||||
checkByteStringLength(request.getName(), "Invalid name length", List.of(81, 285));
|
||||
checkByteStringLength(request.getAboutEmoji(), "Invalid about emoji length", List.of(0, 60));
|
||||
checkByteStringLength(request.getAbout(), "Invalid about length", List.of(0, 156, 282, 540));
|
||||
checkByteStringLength(request.getPaymentAddress(), "Invalid mobile coin address length", List.of(0, 582));
|
||||
}
|
||||
|
||||
private static void checkByteStringLength(final ByteString byteString, final String errorMessage, final List<Integer> allowedLengths) {
|
||||
final int byteStringLength = byteString.toByteArray().length;
|
||||
|
||||
for (int allowedLength : allowedLengths) {
|
||||
if (byteStringLength == allowedLength) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asRuntimeException();
|
||||
}
|
||||
|
||||
private static String encodeToBase64(byte[] input) {
|
||||
return Base64.getEncoder().encodeToString(input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
public class ProfileHelper {
|
||||
public static List<AccountBadge> mergeBadgeIdsWithExistingAccountBadges(
|
||||
final Clock clock,
|
||||
final Map<String, BadgeConfiguration> badgeConfigurationMap,
|
||||
final List<String> badgeIds,
|
||||
final List<AccountBadge> accountBadges) {
|
||||
LinkedHashMap<String, AccountBadge> existingBadges = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final AccountBadge accountBadge : accountBadges) {
|
||||
existingBadges.putIfAbsent(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
|
||||
LinkedHashMap<String, AccountBadge> result = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final String badgeId : badgeIds) {
|
||||
|
||||
// duplicate in the list, ignore it
|
||||
if (result.containsKey(badgeId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// This is for testing badges and allows them to be added to an account at any time with an expiration of 1 day
|
||||
// in the future.
|
||||
BadgeConfiguration badgeConfiguration = badgeConfigurationMap.get(badgeId);
|
||||
if (badgeConfiguration != null && badgeConfiguration.isTestBadge()) {
|
||||
result.put(badgeId, new AccountBadge(badgeId, clock.instant().plus(Duration.ofDays(1)), true));
|
||||
continue;
|
||||
}
|
||||
|
||||
// reordering or making visible existing badges
|
||||
if (existingBadges.containsKey(badgeId)) {
|
||||
AccountBadge accountBadge = existingBadges.get(badgeId).withVisibility(true);
|
||||
result.put(badgeId, accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
// take any remaining account badges and make them invisible
|
||||
for (final Map.Entry<String, AccountBadge> entry : existingBadges.entrySet()) {
|
||||
if (!result.containsKey(entry.getKey())) {
|
||||
AccountBadge accountBadge = entry.getValue().withVisibility(false);
|
||||
result.put(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayList<>(result.values());
|
||||
}
|
||||
|
||||
public static String generateAvatarObjectName() {
|
||||
byte[] object = new byte[16];
|
||||
new SecureRandom().nextBytes(object);
|
||||
|
||||
return "profiles/" + Base64.getUrlEncoder().encodeToString(object);
|
||||
}
|
||||
|
||||
public static org.signal.chat.profile.ProfileAvatarUploadAttributes generateAvatarUploadFormGrpc(
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final PolicySigner policySigner,
|
||||
final String objectName) {
|
||||
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
final Pair<String, String> policy = policyGenerator.createFor(now, objectName, 10 * 1024 * 1024);
|
||||
final String signature = policySigner.getSignature(now, policy.second());
|
||||
|
||||
return org.signal.chat.profile.ProfileAvatarUploadAttributes.newBuilder()
|
||||
.setPath(objectName)
|
||||
.setCredential(policy.first())
|
||||
.setAcl("private")
|
||||
.setAlgorithm("AWS4-HMAC-SHA256")
|
||||
.setDate(now.format(PostPolicyGenerator.AWS_DATE_TIME))
|
||||
.setPolicy(policy.second())
|
||||
.setSignature(ByteString.copyFrom(signature.getBytes()))
|
||||
.build();
|
||||
}
|
||||
|
||||
public static org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes generateAvatarUploadForm(
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final PolicySigner policySigner,
|
||||
final String objectName) {
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
Pair<String, String> policy = policyGenerator.createFor(now, objectName, 10 * 1024 * 1024);
|
||||
String signature = policySigner.getSignature(now, policy.second());
|
||||
|
||||
return new org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes(objectName, policy.first(), "private", "AWS4-HMAC-SHA256",
|
||||
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
|
||||
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* Estimate the number of unique items seen over a configurable period and update a metric
|
||||
*/
|
||||
public class CardinalityEstimator {
|
||||
|
||||
private volatile double uniqueElementCount;
|
||||
private final FaultTolerantRedisCluster redisCluster;
|
||||
private final String hllName;
|
||||
private final Duration period;
|
||||
|
||||
public CardinalityEstimator(final FaultTolerantRedisCluster redisCluster, final String name, final Duration period) {
|
||||
this.redisCluster = redisCluster;
|
||||
this.hllName = "cardinality_estimator::" + name;
|
||||
this.period = period;
|
||||
Metrics.gauge(
|
||||
MetricsUtil.name(getClass(), "unique"),
|
||||
Tags.of("name", name),
|
||||
this,
|
||||
obj -> obj.uniqueElementCount);
|
||||
}
|
||||
|
||||
public void add(String element) {
|
||||
addAsync(element).toCompletableFuture().join();
|
||||
}
|
||||
|
||||
public CompletionStage<Void> addAsync(String element) {
|
||||
return redisCluster.withCluster(connection -> connection.async()
|
||||
.pfadd(hllName, element)
|
||||
.thenCompose(modCount -> {
|
||||
if (modCount == 0) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
|
||||
// The hll changed - update our local view of the cardinality, and
|
||||
// initialize the TTL if required
|
||||
return connection.async()
|
||||
.pfcount(hllName)
|
||||
.thenCompose(count -> {
|
||||
uniqueElementCount = count;
|
||||
// check if this is a new hll with no TTL set
|
||||
return connection.async().ttl(hllName).thenApply(ttl -> ttl == -1);
|
||||
});
|
||||
})
|
||||
.thenCompose(isNewHll -> {
|
||||
if (!isNewHll) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
// If this is a new hll, we need to set the TTL. This could be
|
||||
// a single atomic op in redis 7.x with EXPIRE NX
|
||||
return connection.async().expire(hllName, period).thenRun(Util.NOOP);
|
||||
}));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
long estimate() {
|
||||
return (long) this.uniqueElementCount;
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,10 @@ public interface RateLimiter {
|
||||
return Mono.fromFuture(validateAsync(key).toCompletableFuture());
|
||||
}
|
||||
|
||||
default Mono<Void> validateReactive(final UUID accountUuid) {
|
||||
return validateReactive(accountUuid.toString());
|
||||
}
|
||||
|
||||
default boolean hasAvailablePermits(final UUID accountUuid, final int permits) {
|
||||
return hasAvailablePermits(accountUuid.toString(), permits);
|
||||
}
|
||||
|
||||
+3
-2
@@ -9,6 +9,7 @@ import org.glassfish.jersey.server.monitoring.ApplicationEvent;
|
||||
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
|
||||
/**
|
||||
* Delegates request events to a listener that captures and reports request-level metrics.
|
||||
@@ -17,8 +18,8 @@ public class MetricsApplicationEventListener implements ApplicationEventListener
|
||||
|
||||
private final MetricsRequestEventListener metricsRequestEventListener;
|
||||
|
||||
public MetricsApplicationEventListener(final TrafficSource trafficSource) {
|
||||
this.metricsRequestEventListener = new MetricsRequestEventListener(trafficSource);
|
||||
public MetricsApplicationEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
this.metricsRequestEventListener = new MetricsRequestEventListener(trafficSource, clientReleaseManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+17
-3
@@ -11,8 +11,10 @@ import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -24,7 +26,10 @@ import java.util.List;
|
||||
*/
|
||||
public class MetricsRequestEventListener implements RequestEventListener {
|
||||
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
public static final String REQUEST_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "request");
|
||||
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "requestByVersion");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PATH_TAG = "path";
|
||||
@@ -41,14 +46,18 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
private final TrafficSource trafficSource;
|
||||
private final MeterRegistry meterRegistry;
|
||||
|
||||
public MetricsRequestEventListener(final TrafficSource trafficSource) {
|
||||
this(trafficSource, Metrics.globalRegistry);
|
||||
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MetricsRequestEventListener(final TrafficSource trafficSource, final MeterRegistry meterRegistry) {
|
||||
MetricsRequestEventListener(final TrafficSource trafficSource,
|
||||
final MeterRegistry meterRegistry,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
|
||||
this.trafficSource = trafficSource;
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -70,6 +79,11 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
|
||||
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
|
||||
.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
|
||||
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
@@ -42,42 +44,17 @@ public class MetricsUtil {
|
||||
public static void configureRegistries(final WhisperServerConfiguration config, final Environment environment) {
|
||||
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
|
||||
|
||||
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
|
||||
.percentiles(.75, .95, .99, .999)
|
||||
.build();
|
||||
|
||||
{
|
||||
final DatadogMeterRegistry datadogMeterRegistry = new DatadogMeterRegistry(
|
||||
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
datadogMeterRegistry.config().commonTags(
|
||||
Tags.of(
|
||||
"service", "chat",
|
||||
"host", HostnameUtil.getLocalHostname(),
|
||||
"version", WhisperServerVersion.getServerVersion(),
|
||||
"env", config.getDatadogConfiguration().getEnvironment()))
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
});
|
||||
|
||||
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
|
||||
datadogMeterRegistry.config().meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public Meter.Id map(final Meter.Id id) {
|
||||
if (id.getName().startsWith("lettuce")) {
|
||||
return id.withName(PREFIX + "." + id.getName())
|
||||
.replaceTags(id.getTags().stream()
|
||||
.filter(tag -> !"command".equals(tag.getKey()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
return MeterFilter.super.map(id);
|
||||
}
|
||||
});
|
||||
|
||||
Tags.of(
|
||||
"service", "chat",
|
||||
"host", HostnameUtil.getLocalHostname(),
|
||||
"version", WhisperServerVersion.getServerVersion(),
|
||||
"env", config.getDatadogConfiguration().getEnvironment()));
|
||||
configureMeterFilters(datadogMeterRegistry.config());
|
||||
Metrics.addRegistry(datadogMeterRegistry);
|
||||
}
|
||||
|
||||
@@ -85,6 +62,40 @@ public class MetricsUtil {
|
||||
environment.lifecycle().manage(new ApplicationShutdownMonitor(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static MeterRegistry.Config configureMeterFilters(MeterRegistry.Config config) {
|
||||
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
|
||||
.percentiles(.75, .95, .99, .999)
|
||||
.build();
|
||||
|
||||
return config
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
})
|
||||
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public Meter.Id map(final Meter.Id id) {
|
||||
if (id.getName().startsWith("lettuce")) {
|
||||
return id.withName(PREFIX + "." + id.getName())
|
||||
.replaceTags(id.getTags().stream()
|
||||
.filter(tag -> !"command".equals(tag.getKey()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
return MeterFilter.super.map(id);
|
||||
}
|
||||
})
|
||||
// Deny lettuce metrics, but leave command.completions.max. Note that regardless of configured order, accept
|
||||
// filters are applied after map filters.
|
||||
.meterFilter(MeterFilter.deny(id ->
|
||||
id.getName().startsWith(PREFIX + ".lettuce") && !id.getName().contains("command.completion.max")
|
||||
));
|
||||
}
|
||||
|
||||
public static void registerSystemResourceMetrics(final Environment environment) {
|
||||
environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge(3, TimeUnit.SECONDS));
|
||||
environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
|
||||
|
||||
@@ -247,45 +247,21 @@ public class Account {
|
||||
public boolean isStorageSupported() {
|
||||
requireNotStale();
|
||||
|
||||
return devices.stream().anyMatch(device -> device.getCapabilities() != null && device.getCapabilities().isStorage());
|
||||
return devices.stream().anyMatch(device -> device.getCapabilities() != null && device.getCapabilities().storage());
|
||||
}
|
||||
|
||||
public boolean isTransferSupported() {
|
||||
requireNotStale();
|
||||
|
||||
return getMasterDevice().map(Device::getCapabilities).map(Device.DeviceCapabilities::isTransfer).orElse(false);
|
||||
}
|
||||
|
||||
public boolean isSenderKeySupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isSenderKey);
|
||||
}
|
||||
|
||||
public boolean isAnnouncementGroupSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isAnnouncementGroup);
|
||||
}
|
||||
|
||||
public boolean isChangeNumberSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isChangeNumber);
|
||||
return getMasterDevice().map(Device::getCapabilities).map(Device.DeviceCapabilities::transfer).orElse(false);
|
||||
}
|
||||
|
||||
public boolean isPniSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isPni);
|
||||
}
|
||||
|
||||
public boolean isStoriesSupported() {
|
||||
requireNotStale();
|
||||
|
||||
return devices.stream()
|
||||
.filter(Device::isEnabled)
|
||||
.allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isStories());
|
||||
}
|
||||
|
||||
public boolean isGiftBadgesSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isGiftBadges);
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::pni);
|
||||
}
|
||||
|
||||
public boolean isPaymentActivationSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isPaymentActivation);
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::paymentActivation);
|
||||
}
|
||||
|
||||
private boolean allEnabledDevicesHaveCapability(final Predicate<DeviceCapabilities> predicate) {
|
||||
|
||||
@@ -104,7 +104,6 @@ public class AccountsManager {
|
||||
private final KeysManager keysManager;
|
||||
private final MessagesManager messagesManager;
|
||||
private final ProfilesManager profilesManager;
|
||||
private final StoredVerificationCodeManager pendingAccounts;
|
||||
private final SecureStorageClient secureStorageClient;
|
||||
private final SecureBackupClient secureBackupClient;
|
||||
private final SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
@@ -151,7 +150,6 @@ public class AccountsManager {
|
||||
final KeysManager keysManager,
|
||||
final MessagesManager messagesManager,
|
||||
final ProfilesManager profilesManager,
|
||||
final StoredVerificationCodeManager pendingAccounts,
|
||||
final SecureStorageClient secureStorageClient,
|
||||
final SecureBackupClient secureBackupClient,
|
||||
final SecureValueRecovery2Client secureValueRecovery2Client,
|
||||
@@ -167,7 +165,6 @@ public class AccountsManager {
|
||||
this.keysManager = keysManager;
|
||||
this.messagesManager = messagesManager;
|
||||
this.profilesManager = profilesManager;
|
||||
this.pendingAccounts = pendingAccounts;
|
||||
this.secureStorageClient = secureStorageClient;
|
||||
this.secureBackupClient = secureBackupClient;
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
@@ -221,8 +218,6 @@ public class AccountsManager {
|
||||
|
||||
redisSet(account);
|
||||
|
||||
pendingAccounts.remove(number);
|
||||
|
||||
// In terms of previously-existing accounts, there are three possible cases:
|
||||
//
|
||||
// 1. This is a completely new account; there was no pre-existing account and no recently-deleted account
|
||||
@@ -240,7 +235,7 @@ public class AccountsManager {
|
||||
keysManager.delete(actualUuid),
|
||||
keysManager.delete(account.getPhoneNumberIdentifier()));
|
||||
|
||||
messagesManager.clear(actualUuid);
|
||||
messagesManager.clear(actualUuid).join();
|
||||
profilesManager.deleteAll(actualUuid);
|
||||
|
||||
deleteKeysFuture.join();
|
||||
@@ -882,12 +877,15 @@ public class AccountsManager {
|
||||
keysManager.delete(account.getUuid()),
|
||||
keysManager.delete(account.getPhoneNumberIdentifier()));
|
||||
|
||||
final CompletableFuture<Void> deleteMessagesFuture = CompletableFuture.allOf(
|
||||
messagesManager.clear(account.getUuid()),
|
||||
messagesManager.clear(account.getPhoneNumberIdentifier()));
|
||||
|
||||
profilesManager.deleteAll(account.getUuid());
|
||||
messagesManager.clear(account.getUuid());
|
||||
messagesManager.clear(account.getPhoneNumberIdentifier());
|
||||
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber());
|
||||
|
||||
deleteKeysFuture.join();
|
||||
deleteMessagesFuture.join();
|
||||
deleteStorageServiceDataFuture.join();
|
||||
deleteBackupServiceDataFuture.join();
|
||||
deleteSecureValueRecoveryServiceDataFuture.join();
|
||||
|
||||
@@ -274,85 +274,6 @@ public class Device {
|
||||
return this.userAgent;
|
||||
}
|
||||
|
||||
public static class DeviceCapabilities {
|
||||
@JsonProperty
|
||||
private boolean storage;
|
||||
|
||||
@JsonProperty
|
||||
private boolean transfer;
|
||||
|
||||
@JsonProperty
|
||||
private boolean senderKey;
|
||||
|
||||
@JsonProperty
|
||||
private boolean announcementGroup;
|
||||
|
||||
@JsonProperty
|
||||
private boolean changeNumber;
|
||||
|
||||
@JsonProperty
|
||||
private boolean pni;
|
||||
|
||||
@JsonProperty
|
||||
private boolean stories;
|
||||
|
||||
@JsonProperty
|
||||
private boolean giftBadges;
|
||||
|
||||
@JsonProperty
|
||||
private boolean paymentActivation;
|
||||
|
||||
public DeviceCapabilities() {
|
||||
}
|
||||
|
||||
public DeviceCapabilities(boolean storage, boolean transfer,
|
||||
final boolean senderKey, final boolean announcementGroup, final boolean changeNumber,
|
||||
final boolean pni, final boolean stories, final boolean giftBadges, final boolean paymentActivation) {
|
||||
this.storage = storage;
|
||||
this.transfer = transfer;
|
||||
this.senderKey = senderKey;
|
||||
this.announcementGroup = announcementGroup;
|
||||
this.changeNumber = changeNumber;
|
||||
this.pni = pni;
|
||||
this.stories = stories;
|
||||
this.giftBadges = giftBadges;
|
||||
this.paymentActivation = paymentActivation;
|
||||
}
|
||||
|
||||
public boolean isStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
public boolean isTransfer() {
|
||||
return transfer;
|
||||
}
|
||||
|
||||
public boolean isSenderKey() {
|
||||
return senderKey;
|
||||
}
|
||||
|
||||
public boolean isAnnouncementGroup() {
|
||||
return announcementGroup;
|
||||
}
|
||||
|
||||
public boolean isChangeNumber() {
|
||||
return changeNumber;
|
||||
}
|
||||
|
||||
public boolean isPni() {
|
||||
return pni;
|
||||
}
|
||||
|
||||
public boolean isStories() {
|
||||
return stories;
|
||||
}
|
||||
|
||||
public boolean isGiftBadges() {
|
||||
return giftBadges;
|
||||
}
|
||||
|
||||
public boolean isPaymentActivation() {
|
||||
return paymentActivation;
|
||||
}
|
||||
public record DeviceCapabilities(boolean storage, boolean transfer, boolean pni, boolean paymentActivation) {
|
||||
}
|
||||
}
|
||||
@@ -329,21 +329,24 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
});
|
||||
}
|
||||
|
||||
public void clear(final UUID destinationUuid) {
|
||||
// TODO Remove null check in a fully UUID-based world
|
||||
if (destinationUuid != null) {
|
||||
for (int i = 1; i < Device.MAXIMUM_DEVICE_ID; i++) {
|
||||
clear(destinationUuid, i);
|
||||
}
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
final CompletableFuture<?>[] clearFutures = new CompletableFuture[Device.MAXIMUM_DEVICE_ID];
|
||||
|
||||
for (int deviceId = 0; deviceId < Device.MAXIMUM_DEVICE_ID; deviceId++) {
|
||||
clearFutures[deviceId] = clear(destinationUuid, deviceId);
|
||||
}
|
||||
|
||||
return CompletableFuture.allOf(clearFutures);
|
||||
}
|
||||
|
||||
public void clear(final UUID destinationUuid, final long deviceId) {
|
||||
clearQueueTimer.record(() ->
|
||||
removeQueueScript.executeBinary(List.of(getMessageQueueKey(destinationUuid, deviceId),
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid, final long deviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return removeQueueScript.executeBinaryAsync(List.of(getMessageQueueKey(destinationUuid, deviceId),
|
||||
getMessageQueueMetadataKey(destinationUuid, deviceId),
|
||||
getQueueIndexKey(destinationUuid, deviceId)),
|
||||
Collections.emptyList()));
|
||||
Collections.emptyList())
|
||||
.thenRun(() -> sample.stop(clearQueueTimer));
|
||||
}
|
||||
|
||||
int getNextSlotToPersist() {
|
||||
|
||||
+49
-46
@@ -37,7 +37,6 @@ 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.DeleteRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
@@ -215,38 +214,57 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}, messageDeletionExecutor);
|
||||
}
|
||||
|
||||
public void deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
|
||||
deleteByAccount.record(() -> {
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey))
|
||||
.build();
|
||||
deleteRowsMatchingQuery(partitionKey, queryRequest);
|
||||
});
|
||||
public CompletableFuture<Void> deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
|
||||
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey))
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> Mono.fromFuture(dbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT)))
|
||||
.build())))
|
||||
.doOnComplete(() -> sample.stop(deleteByAccount))
|
||||
.then()
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
public void deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
deleteByDevice.record(() -> {
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.build();
|
||||
deleteRowsMatchingQuery(partitionKey, queryRequest);
|
||||
});
|
||||
public CompletableFuture<Void> deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
|
||||
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> Mono.fromFuture(dbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT)))
|
||||
.build())))
|
||||
.doOnComplete(() -> sample.stop(deleteByDevice))
|
||||
.then()
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -256,21 +274,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
return MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray());
|
||||
}
|
||||
|
||||
private void deleteRowsMatchingQuery(AttributeValue partitionKey, QueryRequest querySpec) {
|
||||
writeInBatches(db().queryPaginator(querySpec).items(), itemBatch -> deleteItems(partitionKey, itemBatch));
|
||||
}
|
||||
|
||||
private void deleteItems(AttributeValue partitionKey, List<Map<String, AttributeValue>> items) {
|
||||
List<WriteRequest> deletes = items.stream()
|
||||
.map(item -> WriteRequest.builder()
|
||||
.deleteRequest(DeleteRequest.builder().key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT))).build())
|
||||
.build())
|
||||
.toList();
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, deletes));
|
||||
}
|
||||
|
||||
private long getTtlForMessage(MessageProtos.Envelope message) {
|
||||
return message.getServerTimestamp() / 1000 + timeToLive.getSeconds();
|
||||
}
|
||||
|
||||
@@ -102,14 +102,16 @@ public class MessagesManager {
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public void clear(UUID destinationUuid) {
|
||||
messagesCache.clear(destinationUuid);
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid);
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid) {
|
||||
return CompletableFuture.allOf(
|
||||
messagesCache.clear(destinationUuid),
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid));
|
||||
}
|
||||
|
||||
public void clear(UUID destinationUuid, long deviceId) {
|
||||
messagesCache.clear(destinationUuid, deviceId);
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId);
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid, long deviceId) {
|
||||
return CompletableFuture.allOf(
|
||||
messagesCache.clear(destinationUuid, deviceId),
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, long destinationDeviceId, UUID guid,
|
||||
|
||||
@@ -11,6 +11,7 @@ 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.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -75,6 +76,7 @@ public class Profiles {
|
||||
private static final Timer SET_PROFILES_TIMER = Metrics.timer(name(Profiles.class, "set"));
|
||||
private static final Timer GET_PROFILE_TIMER = Metrics.timer(name(Profiles.class, "get"));
|
||||
private static final Timer DELETE_PROFILES_TIMER = Metrics.timer(name(Profiles.class, "delete"));
|
||||
private static final String PARSE_BYTE_ARRAY_COUNTER_NAME = name(Profiles.class, "parseByteArray");
|
||||
|
||||
public Profiles(final DynamoDbClient dynamoDbClient,
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
@@ -226,14 +228,23 @@ public class Profiles {
|
||||
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
|
||||
return new VersionedProfile(
|
||||
AttributeValues.getString(item, ATTR_VERSION, null),
|
||||
AttributeValues.getString(item, ATTR_NAME, null),
|
||||
getBase64EncodedBytes(item, ATTR_NAME, PARSE_BYTE_ARRAY_COUNTER_NAME),
|
||||
AttributeValues.getString(item, ATTR_AVATAR, null),
|
||||
AttributeValues.getString(item, ATTR_EMOJI, null),
|
||||
AttributeValues.getString(item, ATTR_ABOUT, null),
|
||||
AttributeValues.getString(item, ATTR_PAYMENT_ADDRESS, null),
|
||||
getBase64EncodedBytes(item, ATTR_EMOJI, PARSE_BYTE_ARRAY_COUNTER_NAME),
|
||||
getBase64EncodedBytes(item, ATTR_ABOUT, PARSE_BYTE_ARRAY_COUNTER_NAME),
|
||||
getBase64EncodedBytes(item, ATTR_PAYMENT_ADDRESS, PARSE_BYTE_ARRAY_COUNTER_NAME),
|
||||
AttributeValues.getByteArray(item, ATTR_COMMITMENT, null));
|
||||
}
|
||||
|
||||
private static String getBase64EncodedBytes(final Map<String, AttributeValue> item, final String attributeName, final String counterName) {
|
||||
final AttributeValue attributeValue = item.get(attributeName);
|
||||
|
||||
if (attributeValue == null) {
|
||||
return null;
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(AttributeValues.extractByteArray(attributeValue, counterName));
|
||||
}
|
||||
|
||||
public void deleteAll(final UUID uuid) {
|
||||
DELETE_PROFILES_TIMER.record(() -> {
|
||||
final AttributeValue uuidAttributeValue = AttributeValues.fromUUID(uuid);
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
private static final String ATTR_SERIALIZED_VALUE = "V";
|
||||
private static final String ATTR_TTL = "E";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(VerificationCodeStore.class);
|
||||
private final Logger log = LoggerFactory.getLogger(getClass());
|
||||
|
||||
public SerializedExpireableJsonDynamoStore(final DynamoDbAsyncClient dynamoDbClient, final String tableName,
|
||||
final Clock clock) {
|
||||
|
||||
+4
-1
@@ -14,7 +14,10 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class SingleUseECPreKeyStore extends SingleUsePreKeyStore<ECPreKey> {
|
||||
private static final String PARSE_BYTE_ARRAY_COUNTER_NAME = name(SingleUseECPreKeyStore.class, "parseByteArray");
|
||||
|
||||
protected SingleUseECPreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
|
||||
super(dynamoDbAsyncClient, tableName);
|
||||
@@ -31,7 +34,7 @@ public class SingleUseECPreKeyStore extends SingleUsePreKeyStore<ECPreKey> {
|
||||
@Override
|
||||
protected ECPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
|
||||
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
|
||||
final byte[] publicKey = extractByteArray(item.get(ATTR_PUBLIC_KEY));
|
||||
final byte[] publicKey = AttributeValues.extractByteArray(item.get(ATTR_PUBLIC_KEY), PARSE_BYTE_ARRAY_COUNTER_NAME);
|
||||
|
||||
try {
|
||||
return new ECPreKey(keyId, new ECPublicKey(publicKey));
|
||||
|
||||
-23
@@ -73,9 +73,6 @@ public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
|
||||
private final String takeKeyTimerName = name(getClass(), "takeKey");
|
||||
private static final String KEY_PRESENT_TAG_NAME = "keyPresent";
|
||||
|
||||
private final Counter parseBytesFromStringCounter = Metrics.counter(name(getClass(), "parseByteArray"), "format", "string");
|
||||
private final Counter readBytesFromByteArrayCounter = Metrics.counter(name(getClass(), "parseByteArray"), "format", "bytes");
|
||||
|
||||
static final String KEY_ACCOUNT_UUID = "U";
|
||||
static final String KEY_DEVICE_ID_KEY_ID = "DK";
|
||||
static final String ATTR_PUBLIC_KEY = "P";
|
||||
@@ -289,24 +286,4 @@ public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
|
||||
final K preKey);
|
||||
|
||||
protected abstract K getPreKeyFromItem(final Map<String, AttributeValue> item);
|
||||
|
||||
/**
|
||||
* Extracts a byte array from an {@link AttributeValue} that may be either a byte array or a base64-encoded string.
|
||||
*
|
||||
* @param attributeValue the {@code AttributeValue} from which to extract a byte array
|
||||
*
|
||||
* @return the byte array represented by the given {@code AttributeValue}
|
||||
*/
|
||||
@VisibleForTesting
|
||||
byte[] extractByteArray(final AttributeValue attributeValue) {
|
||||
if (attributeValue.b() != null) {
|
||||
readBytesFromByteArrayCounter.increment();
|
||||
return attributeValue.b().asByteArray();
|
||||
} else if (StringUtils.isNotBlank(attributeValue.s())) {
|
||||
parseBytesFromStringCounter.increment();
|
||||
return Base64.getDecoder().decode(attributeValue.s());
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Attribute value has neither a byte array nor a string value");
|
||||
}
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
|
||||
public class StoredVerificationCodeManager {
|
||||
|
||||
private final VerificationCodeStore verificationCodeStore;
|
||||
|
||||
public StoredVerificationCodeManager(final VerificationCodeStore verificationCodeStore) {
|
||||
this.verificationCodeStore = verificationCodeStore;
|
||||
}
|
||||
|
||||
public void store(String number, StoredVerificationCode code) {
|
||||
verificationCodeStore.insert(number, code);
|
||||
}
|
||||
|
||||
public void remove(String number) {
|
||||
verificationCodeStore.remove(number);
|
||||
}
|
||||
|
||||
public Optional<StoredVerificationCode> getCodeForNumber(String number) {
|
||||
return verificationCodeStore.findForNumber(number);
|
||||
}
|
||||
}
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
|
||||
public class VerificationCodeStore {
|
||||
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final String tableName;
|
||||
|
||||
private final Timer insertTimer;
|
||||
private final Timer getTimer;
|
||||
private final Timer removeTimer;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String KEY_E164 = "P";
|
||||
|
||||
private static final String ATTR_STORED_CODE = "C";
|
||||
private static final String ATTR_TTL = "E";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(VerificationCodeStore.class);
|
||||
|
||||
public VerificationCodeStore(final DynamoDbClient dynamoDbClient, final String tableName) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.tableName = tableName;
|
||||
|
||||
this.insertTimer = Metrics.timer(name(getClass(), "insert"), "table", tableName);
|
||||
this.getTimer = Metrics.timer(name(getClass(), "get"), "table", tableName);
|
||||
this.removeTimer = Metrics.timer(name(getClass(), "remove"), "table", tableName);
|
||||
}
|
||||
|
||||
public void insert(final String number, final StoredVerificationCode verificationCode) {
|
||||
insertTimer.record(() -> {
|
||||
try {
|
||||
dynamoDbClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_E164, AttributeValues.fromString(number),
|
||||
ATTR_STORED_CODE, AttributeValues.fromString(SystemMapper.jsonMapper().writeValueAsString(verificationCode)),
|
||||
ATTR_TTL, AttributeValues.fromLong(getExpirationTimestamp(verificationCode))))
|
||||
.build());
|
||||
} catch (final JsonProcessingException e) {
|
||||
// This should never happen when writing directly to a string except in cases of serious misconfiguration, which
|
||||
// would be caught by tests.
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private long getExpirationTimestamp(final StoredVerificationCode storedVerificationCode) {
|
||||
return Instant.ofEpochMilli(storedVerificationCode.timestamp()).plus(StoredVerificationCode.EXPIRATION).getEpochSecond();
|
||||
}
|
||||
|
||||
public Optional<StoredVerificationCode> findForNumber(final String number) {
|
||||
return getTimer.record(() -> {
|
||||
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
|
||||
.build());
|
||||
|
||||
try {
|
||||
return response.hasItem()
|
||||
? filterMaybeExpiredCode(
|
||||
SystemMapper.jsonMapper().readValue(response.item().get(ATTR_STORED_CODE).s(), StoredVerificationCode.class))
|
||||
: Optional.empty();
|
||||
} catch (final JsonProcessingException e) {
|
||||
log.error("Failed to parse stored verification code", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Optional<StoredVerificationCode> filterMaybeExpiredCode(StoredVerificationCode storedVerificationCode) {
|
||||
// It's possible for DynamoDB to return items after their expiration time (although it is very unlikely for small
|
||||
// tables)
|
||||
if (getExpirationTimestamp(storedVerificationCode) < Instant.now().getEpochSecond()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.of(storedVerificationCode);
|
||||
}
|
||||
|
||||
public void remove(final String number) {
|
||||
removeTimer.record(() -> {
|
||||
dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_E164, AttributeValues.fromString(number)))
|
||||
.build());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,13 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
|
||||
@@ -124,4 +128,24 @@ public class AttributeValues {
|
||||
public static UUID getUUID(Map<String, AttributeValue> item, String key, UUID defaultValue) {
|
||||
return AttributeValues.get(item, key).filter(av -> av.b() != null).map(AttributeValues::toUUID).orElse(defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a byte array from an {@link AttributeValue} that may be either a byte array or a base64-encoded string.
|
||||
*
|
||||
* @param attributeValue the {@code AttributeValue} from which to extract a byte array
|
||||
*
|
||||
* @return the byte array represented by the given {@code AttributeValue}
|
||||
*/
|
||||
@VisibleForTesting
|
||||
public static byte[] extractByteArray(final AttributeValue attributeValue, final String counterName) {
|
||||
if (attributeValue.b() != null) {
|
||||
Metrics.counter(counterName, "format", "bytes").increment();
|
||||
return attributeValue.b().asByteArray();
|
||||
} else if (StringUtils.isNotBlank(attributeValue.s())) {
|
||||
Metrics.counter(counterName, "format", "string").increment();
|
||||
return Base64.getDecoder().decode(attributeValue.s());
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Attribute value has neither a byte array nor a string value");
|
||||
}
|
||||
}
|
||||
@@ -4,61 +4,5 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
public class VerificationCode {
|
||||
|
||||
@JsonProperty
|
||||
private String verificationCode;
|
||||
@JsonIgnore
|
||||
private String verificationCodeDisplay;
|
||||
@JsonIgnore
|
||||
private String verificationCodeSpeech;
|
||||
|
||||
@VisibleForTesting VerificationCode() {}
|
||||
|
||||
public VerificationCode(int verificationCode) {
|
||||
this(verificationCode + "");
|
||||
}
|
||||
|
||||
public VerificationCode(String verificationCode) {
|
||||
this.verificationCode = verificationCode;
|
||||
this.verificationCodeDisplay = this.verificationCode.substring(0, 3) + "-" + this.verificationCode.substring(3, 6);
|
||||
this.verificationCodeSpeech = delimit(verificationCode + "");
|
||||
}
|
||||
|
||||
public String getVerificationCode() {
|
||||
return verificationCode;
|
||||
}
|
||||
|
||||
public String getVerificationCodeDisplay() {
|
||||
return verificationCodeDisplay;
|
||||
}
|
||||
|
||||
public String getVerificationCodeSpeech() {
|
||||
return verificationCodeSpeech;
|
||||
}
|
||||
|
||||
private String delimit(String code) {
|
||||
String delimited = "";
|
||||
|
||||
for (int i=0;i<code.length();i++) {
|
||||
delimited += code.charAt(i);
|
||||
|
||||
if (i != code.length() - 1)
|
||||
delimited += ',';
|
||||
}
|
||||
|
||||
return delimited;
|
||||
}
|
||||
|
||||
@VisibleForTesting public boolean equals(Object o) {
|
||||
return o instanceof VerificationCode && verificationCode.equals(((VerificationCode) o).verificationCode);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return Integer.parseInt(verificationCode);
|
||||
}
|
||||
public record VerificationCode(String verificationCode) {
|
||||
}
|
||||
+9
-3
@@ -9,6 +9,7 @@ import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.Cli;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import java.util.Objects;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
@@ -17,10 +18,8 @@ import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.ParallelFlux;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import java.util.Objects;
|
||||
|
||||
public abstract class AbstractSinglePassCrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfiguration> {
|
||||
|
||||
@@ -69,7 +68,14 @@ public abstract class AbstractSinglePassCrawlAccountsCommand extends Environment
|
||||
segments,
|
||||
Runtime.getRuntime().availableProcessors());
|
||||
|
||||
crawlAccounts(commandDependencies.accountsManager().streamAllFromDynamo(segments, Schedulers.parallel()));
|
||||
final CommandStopListener commandStopListener = new CommandStopListener(configuration.getCommandStopListener());
|
||||
try {
|
||||
commandStopListener.start();
|
||||
crawlAccounts(commandDependencies.accountsManager().streamAllFromDynamo(segments, Schedulers.parallel()));
|
||||
} finally {
|
||||
commandStopListener.stop();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-6
@@ -51,10 +51,8 @@ import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
@@ -145,8 +143,6 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
@@ -209,10 +205,9 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, deletedAccounts, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
secureStorageClient, secureBackupClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, Clock.systemUTC());
|
||||
|
||||
final String usernameHash = namespace.getString("usernameHash");
|
||||
|
||||
+1
-8
@@ -44,8 +44,6 @@ import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
|
||||
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
@@ -61,7 +59,6 @@ record CommandDependencies(
|
||||
ReportMessageManager reportMessageManager,
|
||||
MessagesCache messagesCache,
|
||||
MessagesManager messagesManager,
|
||||
StoredVerificationCodeManager pendingAccountsManager,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
KeysManager keysManager,
|
||||
FaultTolerantRedisCluster cacheCluster,
|
||||
@@ -122,8 +119,6 @@ record CommandDependencies(
|
||||
|
||||
DeletedAccounts deletedAccounts = new DeletedAccounts(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccounts().getTableName());
|
||||
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
@@ -188,10 +183,9 @@ record CommandDependencies(
|
||||
reportMessageManager, messageDeletionExecutor);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
StoredVerificationCodeManager pendingAccountsManager = new StoredVerificationCodeManager(pendingAccounts);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
accountLockManager, deletedAccounts, keys, messagesManager, profilesManager,
|
||||
pendingAccountsManager, secureStorageClient, secureBackupClient, secureValueRecovery2Client,
|
||||
secureStorageClient, secureBackupClient, secureValueRecovery2Client,
|
||||
clientPresenceManager,
|
||||
experimentEnrollmentManager, registrationRecoveryPasswordsManager, clock);
|
||||
|
||||
@@ -204,7 +198,6 @@ record CommandDependencies(
|
||||
reportMessageManager,
|
||||
messagesCache,
|
||||
messagesManager,
|
||||
pendingAccountsManager,
|
||||
clientPresenceManager,
|
||||
keys,
|
||||
cacheCluster,
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CommandStopListenerConfiguration;
|
||||
|
||||
/**
|
||||
* When {@link Managed#stop()} is called, writes to a configured file path
|
||||
* <p>
|
||||
* Useful for coordinating process termination via a shared file-system, such as a Kubernetes volume mount.
|
||||
*/
|
||||
public class CommandStopListener implements Managed {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CommandStopListener.class);
|
||||
|
||||
private final String path;
|
||||
|
||||
CommandStopListener(CommandStopListenerConfiguration config) {
|
||||
this.path = config.path();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
try {
|
||||
try (FileWriter writer = new FileWriter(path)) {
|
||||
writer.write("stopped");
|
||||
}
|
||||
} catch (final IOException e) {
|
||||
logger.error("Failed to open file {}", path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -142,6 +142,8 @@ public class CrawlAccountsCommand extends EnvironmentCommand<WhisperServerConfig
|
||||
}
|
||||
};
|
||||
|
||||
environment.lifecycle().manage(new CommandStopListener(configuration.getCommandStopListener()));
|
||||
|
||||
environment.lifecycle().getManagedObjects().forEach(managedObject -> {
|
||||
try {
|
||||
managedObject.start();
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ public class UnlinkDeviceCommand extends EnvironmentCommand<WhisperServerConfigu
|
||||
deps.keysManager().delete(account.getUuid(), deviceId).join();
|
||||
|
||||
System.out.format("Clearing additional messages for %s::%d\n", aci, deviceId);
|
||||
deps.messagesManager().clear(account.getUuid(), deviceId);
|
||||
deps.messagesManager().clear(account.getUuid(), deviceId).join();
|
||||
|
||||
System.out.format("Clearing presence state for %s::%d\n", aci, deviceId);
|
||||
deps.clientPresenceManager().disconnectPresence(aci, deviceId);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling;
|
||||
|
||||
/**
|
||||
* Provides methods for getting credentials for one-on-one and group calls.
|
||||
*/
|
||||
service Calling {
|
||||
|
||||
/**
|
||||
* Generates and returns TURN credentials for the caller.
|
||||
*
|
||||
* This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
* generating TURN credentials has been exceeded, in which case a
|
||||
* `retry-after` header containing an ISO 8601 duration string will be present
|
||||
* in the response trailers.
|
||||
*/
|
||||
rpc GetTurnCredentials(GetTurnCredentialsRequest) returns (GetTurnCredentialsResponse) {}
|
||||
}
|
||||
|
||||
message GetTurnCredentialsRequest {}
|
||||
|
||||
message GetTurnCredentialsResponse {
|
||||
/**
|
||||
* A username that can be presented to authenticate with a TURN server.
|
||||
*/
|
||||
string username = 1;
|
||||
|
||||
/**
|
||||
* A password that can be presented to authenticate with a TURN server.
|
||||
*/
|
||||
string password = 2;
|
||||
|
||||
/**
|
||||
* A list of TURN (or TURNS or STUN) servers where the provided credentials
|
||||
* may be used.
|
||||
*/
|
||||
repeated string urls = 3;
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.profile;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
|
||||
/**
|
||||
* Provides methods for working with profiles and profile-related data.
|
||||
*/
|
||||
service Profile {
|
||||
/**
|
||||
* Sets profile data and if needed, returns S3 credentials used by clients to upload an avatar.
|
||||
*
|
||||
* This RPC may fail with `PERMISSION_DENIED` if it attempts to set the MobileCoin wallet ID
|
||||
* on an account whose profile does not currently have a MobileCoin wallet ID and
|
||||
* whose phone number contains a disallowed country prefix.
|
||||
*/
|
||||
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves versioned profile data. Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
rpc GetVersionedProfile(GetVersionedProfileRequest) returns (GetVersionedProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves unversioned profile data. Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves a profile key credential.
|
||||
* Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers. It may also fail with an
|
||||
* `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
*/
|
||||
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides methods for working with profiles and profile-related data using "unidentified access"
|
||||
* credentials. Callers must not submit any self-identifying credentials
|
||||
* when calling methods in this service and must instead present the targeted account's
|
||||
* unidentified access key as an anonymous authentication mechanism. Callers
|
||||
* without an unidentified access key should use the equivalent, authenticated
|
||||
* methods in `Profile` instead.
|
||||
*/
|
||||
service ProfileAnonymous {
|
||||
/**
|
||||
* Retrieves versioned profile data.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key.
|
||||
*/
|
||||
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileResponse) {}
|
||||
/**
|
||||
* Retrieves unversioned profile data.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key.
|
||||
*/
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileResponse) {}
|
||||
/**
|
||||
* Retrieves a profile key credential.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key, or an `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
*/
|
||||
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
|
||||
|
||||
/**
|
||||
* Checks identity key fingerprints of the target accounts.
|
||||
*
|
||||
* Returns a stream of elements, each one representing an account that had a mismatched
|
||||
* identity key fingerprint with the server and the corresponding identity key stored by the server.
|
||||
*/
|
||||
rpc CheckIdentityKeys(stream CheckIdentityKeysRequest) returns (stream CheckIdentityKeysResponse) {}
|
||||
}
|
||||
|
||||
message SetProfileRequest {
|
||||
enum AvatarChange {
|
||||
AVATAR_CHANGE_UNCHANGED = 0;
|
||||
AVATAR_CHANGE_CLEAR = 1;
|
||||
AVATAR_CHANGE_UPDATE = 2;
|
||||
}
|
||||
/**
|
||||
* The profile version. Must be set.
|
||||
*/
|
||||
string version = 1;
|
||||
/**
|
||||
* The ciphertext of a name that users must set on the profile.
|
||||
*/
|
||||
bytes name = 2;
|
||||
/**
|
||||
* An enum to indicate what change, if any, is made to the avatar with this request.
|
||||
*/
|
||||
AvatarChange avatarChange = 3;
|
||||
/**
|
||||
* The ciphertext of an emoji that users can set on their profile.
|
||||
*/
|
||||
bytes about_emoji = 4;
|
||||
/**
|
||||
* The ciphertext of a description that users can set on their profile.
|
||||
*/
|
||||
bytes about = 5;
|
||||
/**
|
||||
* The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
*/
|
||||
bytes payment_address = 6;
|
||||
/**
|
||||
* A list of badge IDs associated with the profile.
|
||||
*/
|
||||
repeated string badge_ids = 7;
|
||||
/**
|
||||
* The profile key commitment. Used to issue a profile key credential response.
|
||||
* Must be set on the request.
|
||||
*/
|
||||
bytes commitment = 9;
|
||||
}
|
||||
|
||||
message SetProfileResponse {
|
||||
/**
|
||||
* The policy and credential used by clients to upload an avatar to S3.
|
||||
*/
|
||||
ProfileAvatarUploadAttributes attributes = 1;
|
||||
}
|
||||
|
||||
message GetVersionedProfileRequest {
|
||||
/**
|
||||
* The ACI of the account for which to get profile data.
|
||||
*/
|
||||
common.ServiceIdentifier accountIdentifier = 1;
|
||||
/**
|
||||
* The profile version to retrieve.
|
||||
*/
|
||||
bytes version = 2;
|
||||
}
|
||||
|
||||
message GetVersionedProfileAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request a versioned profile.
|
||||
*/
|
||||
GetVersionedProfileRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetVersionedProfileResponse {
|
||||
/**
|
||||
* The ciphertext of the name on the profile.
|
||||
*/
|
||||
bytes name = 1;
|
||||
/**
|
||||
* The ciphertext of the description on the profile.
|
||||
*/
|
||||
bytes about = 2;
|
||||
/**
|
||||
* The ciphertext of the emoji on the profile.
|
||||
*/
|
||||
bytes about_emoji = 3;
|
||||
/**
|
||||
* The S3 path of the avatar on the profile.
|
||||
*/
|
||||
string avatar = 4;
|
||||
/**
|
||||
* The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
*/
|
||||
bytes payment_address = 5;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileRequest {
|
||||
/**
|
||||
* The service identifier of the account for which to get profile data.
|
||||
*/
|
||||
common.ServiceIdentifier serviceIdentifier = 1;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request an unversioned profile.
|
||||
*/
|
||||
GetUnversionedProfileRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileResponse {
|
||||
/**
|
||||
* The identity key of the targeted account/identity type.
|
||||
*/
|
||||
bytes identity_key = 1;
|
||||
/**
|
||||
* A checksum of the unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access = 2;
|
||||
/**
|
||||
* Whether the account has enabled sealed sender from anyone.
|
||||
*/
|
||||
bool unrestricted_unidentified_access = 3;
|
||||
/**
|
||||
* A list of capabilities enabled on the account.
|
||||
*/
|
||||
UserCapabilities capabilities = 4;
|
||||
/**
|
||||
* A list of badges associated with the account.
|
||||
*/
|
||||
repeated Badge badges = 5;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialRequest {
|
||||
/**
|
||||
* The ACI of the account for which to get a profile key credential.
|
||||
*/
|
||||
common.ServiceIdentifier accountIdentifier = 1;
|
||||
/**
|
||||
* A zkgroup request for a profile key credential.
|
||||
*/
|
||||
bytes credential_request = 2;
|
||||
/**
|
||||
* The type of credential being requested.
|
||||
*/
|
||||
CredentialType credential_type = 3;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request an expiring profile key credential.
|
||||
*/
|
||||
GetExpiringProfileKeyCredentialRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialResponse {
|
||||
/**
|
||||
* A zkgroup credential used by a client to prove that it has the profile key
|
||||
* of a targeted account.
|
||||
*/
|
||||
bytes profileKeyCredential = 2;
|
||||
}
|
||||
|
||||
message CheckIdentityKeysRequest {
|
||||
/**
|
||||
* The service identifier of the account for which we want to check the associated identity key fingerprint.
|
||||
*/
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
/**
|
||||
* The most significant 4 bytes of the SHA-256 hash of the identity key associated with the target account/identity type.
|
||||
*/
|
||||
bytes fingerprint = 2;
|
||||
}
|
||||
|
||||
message CheckIdentityKeysResponse {
|
||||
/**
|
||||
* The service identifier of the account for which there is a mismatch between the client and server identity key fingerprints.
|
||||
*/
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
/**
|
||||
* The identity key that is stored by the server for the target account/identity type.
|
||||
*/
|
||||
bytes identity_key = 2;
|
||||
}
|
||||
|
||||
message ProfileAvatarUploadAttributes {
|
||||
/**
|
||||
* The S3 upload path for the profile's avatar.
|
||||
*/
|
||||
string path = 1;
|
||||
/**
|
||||
* A scoped credential. Includes the AWS access key, date, region targeted, and AWS service.
|
||||
*/
|
||||
string credential = 2;
|
||||
/**
|
||||
* The type of access control for the avatar object.
|
||||
*/
|
||||
string acl = 3;
|
||||
/**
|
||||
* The algorithm used to calculate a signature on the S3 policy.
|
||||
*/
|
||||
string algorithm = 4;
|
||||
/**
|
||||
* The timestamp at which the S3 policy and signature were generated.
|
||||
*/
|
||||
string date = 5;
|
||||
/**
|
||||
* The S3 policy used to upload the avatar object.
|
||||
*/
|
||||
string policy = 6;
|
||||
/**
|
||||
* A digital signature on the S3 policy.
|
||||
*/
|
||||
bytes signature = 7;
|
||||
}
|
||||
|
||||
message UserCapabilities {
|
||||
/**
|
||||
* Whether all devices linked to the account support the groups v1 migration.
|
||||
*/
|
||||
bool gv1_migration = 1;
|
||||
/**
|
||||
* Whether all devices linked to the account support sender keys.
|
||||
*/
|
||||
bool sender_key = 2;
|
||||
/**
|
||||
* Whether all devices linked to the account support announcement groups
|
||||
* (groups where only the admin can send messages or start calls).
|
||||
*/
|
||||
bool announcement_group = 3;
|
||||
/**
|
||||
* Whether all devices linked to the account support changing phone number.
|
||||
*/
|
||||
bool change_number = 4;
|
||||
/**
|
||||
* Whether all devices linked to the account support stories.
|
||||
*/
|
||||
bool stories = 5;
|
||||
/**
|
||||
* Whether all devices linked to the account support gift badges.
|
||||
*/
|
||||
bool gift_badges = 6;
|
||||
/**
|
||||
* Whether all devices linked to the account support MobileCoin payments.
|
||||
*/
|
||||
bool payment_activation = 7;
|
||||
/**
|
||||
* Whether all devices linked to the account support phone number privacy.
|
||||
*/
|
||||
bool pni = 8;
|
||||
}
|
||||
|
||||
message Badge {
|
||||
/**
|
||||
* An ID that uniquely identifies the badge.
|
||||
*/
|
||||
string id = 1;
|
||||
/**
|
||||
* The category the badge falls in ("donor" or "other").
|
||||
*/
|
||||
string category = 2;
|
||||
/**
|
||||
* The badge name.
|
||||
*/
|
||||
string name = 3;
|
||||
/**
|
||||
* The badge description.
|
||||
*/
|
||||
string description = 4;
|
||||
/**
|
||||
* Different size badge SVG files.
|
||||
*/
|
||||
repeated string sprites6 = 5;
|
||||
/**
|
||||
* File name of the scalable vector graphic representing this badge.
|
||||
*/
|
||||
string svg = 6;
|
||||
/**
|
||||
* Pairs of light/dark SVG files designed for display at different sizes.
|
||||
*/
|
||||
repeated BadgeSvg svgs = 7;
|
||||
}
|
||||
|
||||
message BadgeSvg {
|
||||
/**
|
||||
* File name of the scalable vector graphic for light mode.
|
||||
*/
|
||||
string light = 1;
|
||||
/**
|
||||
* File name of the scalable vector graphic for dark mode.
|
||||
*/
|
||||
string dark = 2;
|
||||
}
|
||||
|
||||
enum CredentialType {
|
||||
CREDENTIAL_TYPE_UNSPECIFIED = 0;
|
||||
CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY = 1;
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class StoredVerificationCodeTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isValid(final StoredVerificationCode storedVerificationCode, final String code, final boolean expectValid) {
|
||||
assertEquals(expectValid, storedVerificationCode.isValid(code));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> isValid() {
|
||||
return Stream.of(
|
||||
Arguments.of(new StoredVerificationCode("code", System.currentTimeMillis(), null, null), "code", true),
|
||||
Arguments.of(new StoredVerificationCode("code", System.currentTimeMillis(), null, null), "incorrect", false),
|
||||
Arguments.of(new StoredVerificationCode("", System.currentTimeMillis(), null, null), "", false)
|
||||
);
|
||||
}
|
||||
}
|
||||
+11
-10
@@ -7,6 +7,7 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -46,9 +47,9 @@ public class TurnTokenGeneratorTest {
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(""))
|
||||
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.getUrls().stream())
|
||||
.flatMap(token -> token.urls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always1.org")).isEqualTo(COUNT);
|
||||
@@ -87,9 +88,9 @@ public class TurnTokenGeneratorTest {
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(""))
|
||||
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.getUrls().stream())
|
||||
.flatMap(token -> token.urls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always.org")).isEqualTo(COUNT);
|
||||
@@ -108,8 +109,8 @@ public class TurnTokenGeneratorTest {
|
||||
- uris:
|
||||
- enrolled.org
|
||||
weight: 0
|
||||
enrolledNumbers:
|
||||
- +15555555555
|
||||
enrolledAcis:
|
||||
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
|
||||
- uris:
|
||||
- unenrolled.org
|
||||
weight: 1
|
||||
@@ -127,10 +128,10 @@ public class TurnTokenGeneratorTest {
|
||||
final TurnTokenGenerator turnTokenGenerator =
|
||||
new TurnTokenGenerator(mockDynamicConfigManager, "bloop".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
TurnToken token = turnTokenGenerator.generate("+15555555555");
|
||||
assertThat(token.getUrls().get(0)).isEqualTo("enrolled.org");
|
||||
token = turnTokenGenerator.generate("+15555555556");
|
||||
assertThat(token.getUrls().get(0)).isEqualTo("unenrolled.org");
|
||||
TurnToken token = turnTokenGenerator.generate(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
|
||||
assertThat(token.urls().get(0)).isEqualTo("enrolled.org");
|
||||
token = turnTokenGenerator.generate(UUID.randomUUID());
|
||||
assertThat(token.urls().get(0)).isEqualTo("unenrolled.org");
|
||||
|
||||
}
|
||||
|
||||
|
||||
+16
-4
@@ -18,6 +18,7 @@ import static org.whispersystems.textsecuregcm.captcha.CaptchaChecker.SEPARATOR;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -77,7 +78,7 @@ public class CaptchaCheckerTest {
|
||||
final String siteKey,
|
||||
final Action expectedAction) throws IOException {
|
||||
final CaptchaClient captchaClient = mockClient(PREFIX);
|
||||
new CaptchaChecker(List.of(captchaClient)).verify(expectedAction, input, null);
|
||||
new CaptchaChecker(null, List.of(captchaClient)).verify(expectedAction, input, null);
|
||||
verify(captchaClient, times(1)).verify(eq(siteKey), eq(expectedAction), eq(expectedToken), any());
|
||||
}
|
||||
|
||||
@@ -105,10 +106,10 @@ public class CaptchaCheckerTest {
|
||||
final CaptchaClient a = mockClient(PREFIX_A);
|
||||
final CaptchaClient b = mockClient(PREFIX_B);
|
||||
|
||||
new CaptchaChecker(List.of(a, b)).verify(Action.CHALLENGE, ainput, null);
|
||||
new CaptchaChecker(null, List.of(a, b)).verify(Action.CHALLENGE, ainput, null);
|
||||
verify(a, times(1)).verify(any(), any(), any(), any());
|
||||
|
||||
new CaptchaChecker(List.of(a, b)).verify(Action.CHALLENGE, binput, null);
|
||||
new CaptchaChecker(null, List.of(a, b)).verify(Action.CHALLENGE, binput, null);
|
||||
verify(b, times(1)).verify(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@@ -130,7 +131,18 @@ public class CaptchaCheckerTest {
|
||||
public void badArgs(final String input) throws IOException {
|
||||
final CaptchaClient cc = mockClient(PREFIX);
|
||||
assertThrows(BadRequestException.class,
|
||||
() -> new CaptchaChecker(List.of(cc)).verify(Action.CHALLENGE, input, null));
|
||||
() -> new CaptchaChecker(null, List.of(cc)).verify(Action.CHALLENGE, input, null));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testShortened() throws IOException {
|
||||
final CaptchaClient captchaClient = mockClient(PREFIX);
|
||||
final ShortCodeExpander retriever = mock(ShortCodeExpander.class);
|
||||
when(retriever.retrieve("abc")).thenReturn(Optional.of(TOKEN));
|
||||
final String input = String.join(SEPARATOR, PREFIX + "-short", REG_SITE_KEY, "registration", "abc");
|
||||
new CaptchaChecker(retriever, List.of(captchaClient)).verify(Action.REGISTRATION, input, null);
|
||||
verify(captchaClient, times(1)).verify(eq(REG_SITE_KEY), eq(Action.REGISTRATION), eq(TOKEN), any());
|
||||
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import com.google.api.Http;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ShortCodeExpanderTest {
|
||||
|
||||
@Test
|
||||
public void testUriResolution() throws IOException, InterruptedException {
|
||||
final HttpClient httpClient = mock(HttpClient.class);
|
||||
final ShortCodeExpander expander = new ShortCodeExpander(httpClient, "https://www.example.org/shortener/");
|
||||
when(httpClient
|
||||
.send(argThat(req -> req.uri().toString().equals("https://www.example.org/shortener/shorturl")), any()))
|
||||
.thenReturn(new FakeResponse(200, "longurl"));
|
||||
assertThat(expander.retrieve("shorturl").get()).isEqualTo("longurl");
|
||||
}
|
||||
|
||||
private record FakeResponse(int statusCode, String body) implements HttpResponse<Object> {
|
||||
|
||||
@Override
|
||||
public HttpRequest request() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<HttpResponse<Object>> previousResponse() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders headers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SSLSession> sslSession() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public URI uri() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpClient.Version version() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+4
-3
@@ -336,8 +336,8 @@ class DynamicConfigurationTest {
|
||||
- uris:
|
||||
- turn:test2.org
|
||||
weight: 2
|
||||
enrolledNumbers:
|
||||
- +15555555555
|
||||
enrolledAcis:
|
||||
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
|
||||
""");
|
||||
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
|
||||
.parseConfiguration(config, DynamicConfiguration.class)
|
||||
@@ -347,7 +347,8 @@ class DynamicConfigurationTest {
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getUris()).hasSize(1);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(0).getWeight()).isEqualTo(1);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getWeight()).isEqualTo(2);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getEnrolledNumbers()).containsExactly("+15555555555");
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getEnrolledAcis())
|
||||
.containsExactly(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
-22
@@ -57,7 +57,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
@@ -83,7 +82,6 @@ import org.whispersystems.textsecuregcm.spam.ScoreThresholdProvider;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
@@ -124,7 +122,6 @@ class AccountControllerTest {
|
||||
private static final String NICE_HOST = "127.0.0.1";
|
||||
private static final String RATE_LIMITED_IP_HOST = "10.0.0.1";
|
||||
|
||||
private static StoredVerificationCodeManager pendingAccountsManager = mock(StoredVerificationCodeManager.class);
|
||||
private static AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private static RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
@@ -204,24 +201,6 @@ class AccountControllerTest {
|
||||
when(senderTransfer.getUuid()).thenReturn(SENDER_TRANSFER_UUID);
|
||||
when(senderTransfer.getNumber()).thenReturn(SENDER_TRANSFER);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OLD)).thenReturn(Optional.empty());
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "validchallenge", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
|
||||
when(accountsManager.getByE164(eq(SENDER_PIN))).thenReturn(Optional.of(senderPinAccount));
|
||||
when(accountsManager.getByE164(eq(SENDER_REG_LOCK))).thenReturn(Optional.of(senderRegLockAccount));
|
||||
when(accountsManager.getByE164(eq(SENDER_OVER_PIN))).thenReturn(Optional.of(senderPinAccount));
|
||||
@@ -244,7 +223,6 @@ class AccountControllerTest {
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
reset(
|
||||
pendingAccountsManager,
|
||||
accountsManager,
|
||||
rateLimiters,
|
||||
rateLimiter,
|
||||
|
||||
+198
-250
@@ -4,36 +4,12 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -49,65 +25,65 @@ import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.WebsocketRefreshApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.*;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.*;
|
||||
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.VerificationCode;
|
||||
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class DeviceControllerTest {
|
||||
|
||||
@Path("/v1/devices")
|
||||
static class DumbVerificationDeviceController extends DeviceController {
|
||||
|
||||
public DumbVerificationDeviceController(StoredVerificationCodeManager pendingDevices,
|
||||
AccountsManager accounts,
|
||||
MessagesManager messages,
|
||||
KeysManager keys,
|
||||
RateLimiters rateLimiters,
|
||||
Map<String, Integer> deviceConfiguration) {
|
||||
super(pendingDevices, accounts, messages, keys, rateLimiters, deviceConfiguration);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected VerificationCode generateVerificationCode() {
|
||||
return new VerificationCode(5678901);
|
||||
}
|
||||
}
|
||||
|
||||
private static StoredVerificationCodeManager pendingDevicesManager = mock(StoredVerificationCodeManager.class);
|
||||
private static AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private static MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
private static KeysManager keysManager = mock(KeysManager.class);
|
||||
private static RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
private static RedisAdvancedClusterCommands<String, String> commands = mock(RedisAdvancedClusterCommands.class);
|
||||
private static Account account = mock(Account.class);
|
||||
private static Account maxedAccount = mock(Account.class);
|
||||
private static Device masterDevice = mock(Device.class);
|
||||
private static ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
|
||||
private static Map<String, Integer> deviceConfiguration = new HashMap<>();
|
||||
private static TestClock testClock = TestClock.now();
|
||||
|
||||
private static DeviceController deviceController = new DeviceController(
|
||||
generateLinkDeviceSecret(),
|
||||
accountsManager,
|
||||
messagesManager,
|
||||
keysManager,
|
||||
rateLimiters,
|
||||
RedisClusterHelper.builder().stringCommands(commands).build(),
|
||||
deviceConfiguration,
|
||||
testClock);
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
@@ -116,14 +92,15 @@ class DeviceControllerTest {
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addProvider(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager))
|
||||
.addProvider(new DeviceLimitExceededExceptionMapper())
|
||||
.addResource(new DumbVerificationDeviceController(pendingDevicesManager,
|
||||
accountsManager,
|
||||
messagesManager,
|
||||
keysManager,
|
||||
rateLimiters,
|
||||
deviceConfiguration))
|
||||
.addResource(deviceController)
|
||||
.build();
|
||||
|
||||
private static byte[] generateLinkDeviceSecret() {
|
||||
final byte[] linkDeviceSecret = new byte[32];
|
||||
new SecureRandom().nextBytes(linkDeviceSecret);
|
||||
|
||||
return linkDeviceSecret;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
@@ -140,17 +117,10 @@ class DeviceControllerTest {
|
||||
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
|
||||
when(account.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI);
|
||||
when(account.isEnabled()).thenReturn(false);
|
||||
when(account.isSenderKeySupported()).thenReturn(true);
|
||||
when(account.isAnnouncementGroupSupported()).thenReturn(true);
|
||||
when(account.isChangeNumberSupported()).thenReturn(true);
|
||||
when(account.isPniSupported()).thenReturn(true);
|
||||
when(account.isStoriesSupported()).thenReturn(true);
|
||||
when(account.isGiftBadgesSupported()).thenReturn(true);
|
||||
when(account.isPaymentActivationSupported()).thenReturn(false);
|
||||
|
||||
when(pendingDevicesManager.getCodeForNumber(AuthHelper.VALID_NUMBER)).thenReturn(
|
||||
Optional.of(new StoredVerificationCode("5678901", System.currentTimeMillis(), null, null)));
|
||||
when(pendingDevicesManager.getCodeForNumber(AuthHelper.VALID_NUMBER_TWO)).thenReturn(Optional.empty());
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByE164(AuthHelper.VALID_NUMBER)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByE164(AuthHelper.VALID_NUMBER_TWO)).thenReturn(Optional.of(maxedAccount));
|
||||
|
||||
@@ -158,30 +128,33 @@ class DeviceControllerTest {
|
||||
|
||||
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(keysManager.delete(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(messagesManager.clear(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
reset(
|
||||
pendingDevicesManager,
|
||||
accountsManager,
|
||||
messagesManager,
|
||||
keysManager,
|
||||
rateLimiters,
|
||||
rateLimiter,
|
||||
commands,
|
||||
account,
|
||||
maxedAccount,
|
||||
masterDevice,
|
||||
clientPresenceManager
|
||||
);
|
||||
|
||||
testClock.unpin();
|
||||
}
|
||||
|
||||
@Test
|
||||
void validDeviceRegisterTest() {
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.MASTER_ID);
|
||||
when(existingDevice.isEnabled()).thenReturn(true);
|
||||
when(AuthHelper.VALID_ACCOUNT.getDevices()).thenReturn(List.of(existingDevice));
|
||||
|
||||
VerificationCode deviceCode = resources.getJerseyTest()
|
||||
@@ -190,10 +163,8 @@ class DeviceControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VerificationCode.class);
|
||||
|
||||
assertThat(deviceCode).isEqualTo(new VerificationCode(5678901));
|
||||
|
||||
DeviceResponse response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.target("/v1/devices/" + deviceCode.verificationCode())
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 1234, null,
|
||||
@@ -203,9 +174,31 @@ class DeviceControllerTest {
|
||||
|
||||
assertThat(response.getDeviceId()).isEqualTo(42L);
|
||||
|
||||
verify(pendingDevicesManager).remove(AuthHelper.VALID_NUMBER);
|
||||
verify(messagesManager).clear(eq(AuthHelper.VALID_UUID), eq(42L));
|
||||
verify(clientPresenceManager).disconnectPresence(AuthHelper.VALID_UUID, Device.MASTER_ID);
|
||||
verify(commands).set(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validDeviceRegisterTestSignedTokenUsed() {
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.MASTER_ID);
|
||||
when(AuthHelper.VALID_ACCOUNT.getDevices()).thenReturn(List.of(existingDevice));
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
when(commands.get(anyString())).thenReturn("");
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 1234, null,
|
||||
null, true, null),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -222,10 +215,8 @@ class DeviceControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VerificationCode.class);
|
||||
|
||||
assertThat(deviceCode).isEqualTo(new VerificationCode(5678901));
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.target("/v1/devices/" + deviceCode.verificationCode())
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.json(""));
|
||||
@@ -235,8 +226,10 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void verifyDeviceTokenBadCredentials() {
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", "This is not a valid authorization header")
|
||||
.put(Entity.entity(new AccountAttributes(false, 1234, null,
|
||||
@@ -256,8 +249,6 @@ class DeviceControllerTest {
|
||||
final Optional<String> expectedApnsVoipToken,
|
||||
final Optional<String> expectedGcmToken) {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.MASTER_ID);
|
||||
when(AuthHelper.VALID_ACCOUNT.getDevices()).thenReturn(List.of(existingDevice));
|
||||
@@ -268,8 +259,6 @@ class DeviceControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VerificationCode.class);
|
||||
|
||||
assertThat(deviceCode).isEqualTo(new VerificationCode(5678901));
|
||||
|
||||
final Optional<ECSignedPreKey> aciSignedPreKey;
|
||||
final Optional<ECSignedPreKey> pniSignedPreKey;
|
||||
final Optional<KEMSignedPreKey> aciPqLastResortPreKey;
|
||||
@@ -289,7 +278,7 @@ class DeviceControllerTest {
|
||||
when(keysManager.storeEcSignedPreKeys(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest("5678901",
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
|
||||
new AccountAttributes(fetchesMessages, 1234, null, null, true, null),
|
||||
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId));
|
||||
|
||||
@@ -319,15 +308,15 @@ class DeviceControllerTest {
|
||||
expectedGcmToken.ifPresentOrElse(expectedToken -> assertEquals(expectedToken, device.getGcmId()),
|
||||
() -> assertNull(device.getGcmId()));
|
||||
|
||||
verify(pendingDevicesManager).remove(AuthHelper.VALID_NUMBER);
|
||||
verify(messagesManager).clear(eq(AuthHelper.VALID_UUID), eq(42L));
|
||||
verify(clientPresenceManager).disconnectPresence(AuthHelper.VALID_UUID, Device.MASTER_ID);
|
||||
verify(keysManager).storeEcSignedPreKeys(AuthHelper.VALID_UUID, Map.of(response.getDeviceId(), aciSignedPreKey.get()));
|
||||
verify(keysManager).storeEcSignedPreKeys(AuthHelper.VALID_PNI, Map.of(response.getDeviceId(), pniSignedPreKey.get()));
|
||||
verify(keysManager).storePqLastResort(AuthHelper.VALID_UUID, Map.of(response.getDeviceId(), aciPqLastResortPreKey.get()));
|
||||
verify(keysManager).storePqLastResort(AuthHelper.VALID_PNI, Map.of(response.getDeviceId(), pniPqLastResortPreKey.get()));
|
||||
verify(commands).set(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
|
||||
private static Stream<Arguments> linkDeviceAtomic() {
|
||||
final String apnsToken = "apns-token";
|
||||
final String apnsVoipToken = "apns-voip-token";
|
||||
@@ -341,6 +330,50 @@ class DeviceControllerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkDeviceAtomicWithVerificationTokenUsed() {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.MASTER_ID);
|
||||
when(AuthHelper.VALID_ACCOUNT.getDevices()).thenReturn(List.of(existingDevice));
|
||||
|
||||
final Optional<ECSignedPreKey> aciSignedPreKey;
|
||||
final Optional<ECSignedPreKey> pniSignedPreKey;
|
||||
final Optional<KEMSignedPreKey> aciPqLastResortPreKey;
|
||||
final Optional<KEMSignedPreKey> pniPqLastResortPreKey;
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = Curve.generateKeyPair();
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
|
||||
aciSignedPreKey = Optional.of(KeysHelper.signedECPreKey(1, aciIdentityKeyPair));
|
||||
pniSignedPreKey = Optional.of(KeysHelper.signedECPreKey(2, pniIdentityKeyPair));
|
||||
aciPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair));
|
||||
pniPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair));
|
||||
|
||||
when(account.getIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
when(account.getPhoneNumberIdentityKey()).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
|
||||
|
||||
when(keysManager.storeEcSignedPreKeys(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(commands.get(anyString())).thenReturn("");
|
||||
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest(deviceController.generateVerificationToken(AuthHelper.VALID_UUID),
|
||||
new AccountAttributes(false, 1234, null, null, true, null),
|
||||
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/link")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@@ -359,8 +392,6 @@ class DeviceControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VerificationCode.class);
|
||||
|
||||
assertThat(deviceCode).isEqualTo(new VerificationCode(5678901));
|
||||
|
||||
final Optional<ECSignedPreKey> aciSignedPreKey;
|
||||
final Optional<ECSignedPreKey> pniSignedPreKey;
|
||||
final Optional<KEMSignedPreKey> aciPqLastResortPreKey;
|
||||
@@ -377,7 +408,7 @@ class DeviceControllerTest {
|
||||
when(account.getIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
when(account.getPhoneNumberIdentityKey()).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
|
||||
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest("5678901",
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
|
||||
new AccountAttributes(fetchesMessages, 1234, null, null, true, null),
|
||||
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId));
|
||||
|
||||
@@ -422,12 +453,10 @@ class DeviceControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VerificationCode.class);
|
||||
|
||||
assertThat(deviceCode).isEqualTo(new VerificationCode(5678901));
|
||||
|
||||
when(account.getIdentityKey()).thenReturn(aciIdentityKey);
|
||||
when(account.getPhoneNumberIdentityKey()).thenReturn(pniIdentityKey);
|
||||
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest("5678901",
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
|
||||
new AccountAttributes(true, 1234, null, null, true, null),
|
||||
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty()));
|
||||
|
||||
@@ -482,12 +511,10 @@ class DeviceControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VerificationCode.class);
|
||||
|
||||
assertThat(deviceCode).isEqualTo(new VerificationCode(5678901));
|
||||
|
||||
when(account.getIdentityKey()).thenReturn(aciIdentityKey);
|
||||
when(account.getPhoneNumberIdentityKey()).thenReturn(pniIdentityKey);
|
||||
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest("5678901",
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
|
||||
new AccountAttributes(true, 1234, null, null, true, null),
|
||||
new DeviceActivationRequest(Optional.of(aciSignedPreKey), Optional.of(pniSignedPreKey), Optional.of(aciPqLastResortPreKey), Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty()));
|
||||
|
||||
@@ -552,10 +579,8 @@ class DeviceControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VerificationCode.class);
|
||||
|
||||
assertThat(deviceCode).isEqualTo(new VerificationCode(5678901));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678902")
|
||||
.target("/v1/devices/" + deviceCode.verificationCode() + "-incorrect")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 1234, null, null, true, null),
|
||||
@@ -595,8 +620,10 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void longNameTest() {
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 1234,
|
||||
@@ -608,164 +635,29 @@ class DeviceControllerTest {
|
||||
verifyNoMoreInteractions(messagesManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeSenderKeyTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, false, true,
|
||||
true, true, true, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeAnnouncementGroupTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, false,
|
||||
true, true, true, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeChangeNumberTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true,
|
||||
false, true, true, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradePniTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true,
|
||||
false, true, true, true);
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true,
|
||||
false, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeStoriesTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true,
|
||||
true, false, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeGiftBadgesTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, false, true);
|
||||
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
@@ -776,7 +668,7 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void putCapabilitiesSuccessTest() {
|
||||
final DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
final DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true);
|
||||
final Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/capabilities")
|
||||
@@ -804,11 +696,14 @@ class DeviceControllerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void deviceDowngradePaymentActivationTest(boolean paymentActivation) {
|
||||
// Update when we start returning true value of capability & restricting downgrades
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, paymentActivation);
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, paymentActivation);
|
||||
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/5678901")
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
@@ -841,4 +736,57 @@ class DeviceControllerTest {
|
||||
verify(keysManager).delete(AuthHelper.VALID_UUID, deviceId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkVerificationToken() {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
|
||||
assertEquals(Optional.of(uuid),
|
||||
deviceController.checkVerificationToken(deviceController.generateVerificationToken(uuid)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void checkVerificationTokenBadToken(final String token, final Instant currentTime) {
|
||||
testClock.pin(currentTime);
|
||||
|
||||
assertEquals(Optional.empty(),
|
||||
deviceController.checkVerificationToken(token));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> checkVerificationTokenBadToken() {
|
||||
final Instant tokenTimestamp = testClock.instant();
|
||||
|
||||
return Stream.of(
|
||||
// Expired token
|
||||
Arguments.of(deviceController.generateVerificationToken(UUID.randomUUID()),
|
||||
tokenTimestamp.plus(DeviceController.TOKEN_EXPIRATION_DURATION).plusSeconds(1)),
|
||||
|
||||
// Bad UUID
|
||||
Arguments.of("not-a-valid-uuid.1691096565171:0CKWF7q3E9fi4sB2or4q1A0Up2z_73EQlMAy7Dpel9c=", tokenTimestamp),
|
||||
|
||||
// No UUID
|
||||
Arguments.of(".1691096565171:0CKWF7q3E9fi4sB2or4q1A0Up2z_73EQlMAy7Dpel9c=", tokenTimestamp),
|
||||
|
||||
// Bad timestamp
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4.not-a-valid-timestamp:0CKWF7q3E9fi4sB2or4q1A0Up2z_73EQlMAy7Dpel9c=", tokenTimestamp),
|
||||
|
||||
// No timestamp
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4:0CKWF7q3E9fi4sB2or4q1A0Up2z_73EQlMAy7Dpel9c=", tokenTimestamp),
|
||||
|
||||
// Blank timestamp
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4.:0CKWF7q3E9fi4sB2or4q1A0Up2z_73EQlMAy7Dpel9c=", tokenTimestamp),
|
||||
|
||||
// No signature
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4.1691096565171", tokenTimestamp),
|
||||
|
||||
// Blank signature
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4.1691096565171:", tokenTimestamp),
|
||||
|
||||
// Incorrect signature
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4.1691096565171:0CKWF7q3E9fi4sB2or4q1A0Up2z_73EQlMAy7Dpel9c=", tokenTimestamp),
|
||||
|
||||
// Invalid signature
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4.1691096565171:This is not valid base64", tokenTimestamp)
|
||||
);
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -100,6 +100,7 @@ import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
@@ -161,6 +162,7 @@ class MessageControllerTest {
|
||||
private static final DeletedAccounts deletedAccounts = mock(DeletedAccounts.class);
|
||||
private static final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final CardinalityEstimator cardinalityEstimator = mock(CardinalityEstimator.class);
|
||||
private static final RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
private static final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
|
||||
@@ -177,7 +179,7 @@ class MessageControllerTest {
|
||||
.addProvider(MultiRecipientMessageProvider.class)
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccounts,
|
||||
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager, deletedAccounts,
|
||||
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
|
||||
messageDeliveryScheduler, ReportSpamTokenProvider.noop(), mock(ClientReleaseManager.class), dynamicConfigurationManager))
|
||||
.build();
|
||||
@@ -247,6 +249,7 @@ class MessageControllerTest {
|
||||
messagesManager,
|
||||
rateLimiters,
|
||||
rateLimiter,
|
||||
cardinalityEstimator,
|
||||
pushNotificationManager,
|
||||
reportMessageManager,
|
||||
multiRecipientMessageExecutor
|
||||
|
||||
+8
-28
@@ -200,9 +200,6 @@ class ProfileControllerTest {
|
||||
when(profileAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID_TWO);
|
||||
when(profileAccount.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI_TWO);
|
||||
when(profileAccount.isEnabled()).thenReturn(true);
|
||||
when(profileAccount.isSenderKeySupported()).thenReturn(false);
|
||||
when(profileAccount.isAnnouncementGroupSupported()).thenReturn(false);
|
||||
when(profileAccount.isChangeNumberSupported()).thenReturn(false);
|
||||
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.empty());
|
||||
when(profileAccount.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH));
|
||||
when(profileAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of("1337".getBytes()));
|
||||
@@ -215,9 +212,6 @@ class ProfileControllerTest {
|
||||
when(capabilitiesAccount.getPhoneNumberIdentityKey()).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
|
||||
when(capabilitiesAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
|
||||
when(capabilitiesAccount.isEnabled()).thenReturn(true);
|
||||
when(capabilitiesAccount.isSenderKeySupported()).thenReturn(true);
|
||||
when(capabilitiesAccount.isAnnouncementGroupSupported()).thenReturn(true);
|
||||
when(capabilitiesAccount.isChangeNumberSupported()).thenReturn(true);
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
|
||||
|
||||
@@ -401,29 +395,15 @@ class ProfileControllerTest {
|
||||
|
||||
@Test
|
||||
void testProfileCapabilities() {
|
||||
{
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(BaseProfileResponse.class);
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(BaseProfileResponse.class);
|
||||
|
||||
assertThat(profile.getCapabilities().gv1Migration()).isTrue();
|
||||
assertThat(profile.getCapabilities().senderKey()).isTrue();
|
||||
assertThat(profile.getCapabilities().announcementGroup()).isTrue();
|
||||
}
|
||||
|
||||
{
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.get(BaseProfileResponse.class);
|
||||
|
||||
assertThat(profile.getCapabilities().gv1Migration()).isTrue();
|
||||
assertThat(profile.getCapabilities().senderKey()).isFalse();
|
||||
assertThat(profile.getCapabilities().announcementGroup()).isFalse();
|
||||
}
|
||||
assertThat(profile.getCapabilities().gv1Migration()).isTrue();
|
||||
assertThat(profile.getCapabilities().senderKey()).isTrue();
|
||||
assertThat(profile.getCapabilities().announcementGroup()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-6
@@ -437,10 +437,10 @@ class RegistrationControllerTest {
|
||||
}
|
||||
|
||||
final AccountAttributes fetchesMessagesAccountAttributes =
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
final AccountAttributes pushAccountAttributes =
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
return Stream.of(
|
||||
// "Fetches messages" is true, but an APNs token is provided
|
||||
@@ -529,7 +529,7 @@ class RegistrationControllerTest {
|
||||
}
|
||||
|
||||
final AccountAttributes accountAttributes =
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
return Stream.of(
|
||||
// Signed PNI EC pre-key is missing
|
||||
@@ -720,7 +720,7 @@ class RegistrationControllerTest {
|
||||
|
||||
RegistrationRequest reg = new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities()),
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false)),
|
||||
true,
|
||||
requireAtomic,
|
||||
Optional.empty(),
|
||||
@@ -758,10 +758,10 @@ class RegistrationControllerTest {
|
||||
}
|
||||
|
||||
final AccountAttributes fetchesMessagesAccountAttributes =
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
final AccountAttributes pushAccountAttributes =
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
final String apnsToken = "apns-token";
|
||||
final String apnsVoipToken = "apns-voip-token";
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.grpc.ServerInterceptors;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.signal.chat.calling.CallingGrpc;
|
||||
import org.signal.chat.calling.GetTurnCredentialsRequest;
|
||||
import org.signal.chat.calling.GetTurnCredentialsResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
class CallingGrpcServiceTest {
|
||||
|
||||
private TurnTokenGenerator turnTokenGenerator;
|
||||
private RateLimiter turnCredentialRateLimiter;
|
||||
|
||||
private CallingGrpc.CallingBlockingStub callingStub;
|
||||
|
||||
private static final UUID AUTHENTICATED_ACI = UUID.randomUUID();
|
||||
private static final long AUTHENTICATED_DEVICE_ID = Device.MASTER_ID;
|
||||
|
||||
@RegisterExtension
|
||||
static final GrpcServerExtension GRPC_SERVER_EXTENSION = new GrpcServerExtension();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
turnTokenGenerator = mock(TurnTokenGenerator.class);
|
||||
turnCredentialRateLimiter = mock(RateLimiter.class);
|
||||
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
when(rateLimiters.getTurnLimiter()).thenReturn(turnCredentialRateLimiter);
|
||||
|
||||
final CallingGrpcService callingGrpcService = new CallingGrpcService(turnTokenGenerator, rateLimiters);
|
||||
|
||||
final MockAuthenticationInterceptor mockAuthenticationInterceptor = new MockAuthenticationInterceptor();
|
||||
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, AUTHENTICATED_DEVICE_ID);
|
||||
|
||||
GRPC_SERVER_EXTENSION.getServiceRegistry()
|
||||
.addService(ServerInterceptors.intercept(callingGrpcService, mockAuthenticationInterceptor));
|
||||
|
||||
callingStub = CallingGrpc.newBlockingStub(GRPC_SERVER_EXTENSION.getChannel());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTurnCredentials() {
|
||||
final String username = "test-username";
|
||||
final String password = "test-password";
|
||||
final List<String> urls = List.of("first", "second");
|
||||
|
||||
when(turnCredentialRateLimiter.validateReactive(AUTHENTICATED_ACI)).thenReturn(Mono.empty());
|
||||
when(turnTokenGenerator.generate(any())).thenReturn(new TurnToken(username, password, urls));
|
||||
|
||||
final GetTurnCredentialsResponse response = callingStub.getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build());
|
||||
|
||||
final GetTurnCredentialsResponse expectedResponse = GetTurnCredentialsResponse.newBuilder()
|
||||
.setUsername(username)
|
||||
.setPassword(password)
|
||||
.addAllUrls(urls)
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTurnCredentialsRateLimited() {
|
||||
final Duration retryAfter = Duration.ofMinutes(19);
|
||||
|
||||
when(turnCredentialRateLimiter.validateReactive(AUTHENTICATED_ACI))
|
||||
.thenReturn(Mono.error(new RateLimitExceededException(retryAfter, false)));
|
||||
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> callingStub.getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build()));
|
||||
|
||||
verify(turnTokenGenerator, never()).generate(any());
|
||||
|
||||
assertEquals(Status.Code.RESOURCE_EXHAUSTED, exception.getStatus().getCode());
|
||||
assertNotNull(exception.getTrailers());
|
||||
assertEquals(retryAfter, exception.getTrailers().get(RateLimitUtil.RETRY_AFTER_DURATION_KEY));
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -152,7 +152,7 @@ class KeysAnonymousGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(identifier)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException statusRuntimeException =
|
||||
final StatusRuntimeException statusRuntimeException =
|
||||
assertThrows(StatusRuntimeException.class,
|
||||
() -> keysAnonymousStub.getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setRequest(GetPreKeysRequest.newBuilder()
|
||||
@@ -172,7 +172,7 @@ class KeysAnonymousGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class,
|
||||
() -> keysAnonymousStub.getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
@@ -205,7 +205,7 @@ class KeysAnonymousGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(accountIdentifier)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class,
|
||||
() -> keysAnonymousStub.getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
|
||||
+81
-81
@@ -188,34 +188,37 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setOneTimeEcPreKeysWithError(final SetOneTimeEcPreKeysRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setOneTimeEcPreKeys(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setOneTimeEcPreKeysWithError() {
|
||||
final SetOneTimeEcPreKeysRequest prototypeRequest = SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(EcPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing identity type
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.addPreKeys(EcPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
|
||||
.build())
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Invalid public key
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(EcPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.empty())
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.setPreKeys(0, EcPreKey.newBuilder(prototypeRequest.getPreKeys(0))
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// No keys
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearPreKeys()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -261,7 +264,7 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setOneTimeKemSignedPreKeysWithError(final SetOneTimeKemSignedPreKeysRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setOneTimeKemSignedPreKeys(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
@@ -270,39 +273,38 @@ class KeysGrpcServiceTest {
|
||||
private static Stream<Arguments> setOneTimeKemSignedPreKeysWithError() {
|
||||
final KEMSignedPreKey signedPreKey = KeysHelper.signedKEMPreKey(1, ACI_IDENTITY_KEY_PAIR);
|
||||
|
||||
final SetOneTimeKemSignedPreKeysRequest prototypeRequest = SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing identity type
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Invalid public key
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.empty())
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.setPreKeys(0, KemSignedPreKey.newBuilder(prototypeRequest.getPreKeys(0))
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Invalid signature
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.empty())
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.setPreKeys(0, KemSignedPreKey.newBuilder(prototypeRequest.getPreKeys(0))
|
||||
.clearSignature()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// No keys
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearPreKeys()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -355,7 +357,7 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setSignedPreKeyWithError(final SetEcSignedPreKeyRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setEcSignedPreKey(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
@@ -364,39 +366,38 @@ class KeysGrpcServiceTest {
|
||||
private static Stream<Arguments> setSignedPreKeyWithError() {
|
||||
final ECSignedPreKey signedPreKey = KeysHelper.signedECPreKey(17, ACI_IDENTITY_KEY_PAIR);
|
||||
|
||||
final SetEcSignedPreKeyRequest prototypeRequest = SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing identity type
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Invalid public key
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.empty())
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Invalid signature
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.empty())
|
||||
.build())
|
||||
.build()),
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearSignature()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Missing key
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearSignedPreKey()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -435,7 +436,7 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setLastResortPreKeyWithError(final SetKemLastResortPreKeyRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setKemLastResortPreKey(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
@@ -444,39 +445,38 @@ class KeysGrpcServiceTest {
|
||||
private static Stream<Arguments> setLastResortPreKeyWithError() {
|
||||
final KEMSignedPreKey lastResortPreKey = KeysHelper.signedKEMPreKey(17, ACI_IDENTITY_KEY_PAIR);
|
||||
|
||||
final SetKemLastResortPreKeyRequest prototypeRequest = SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(lastResortPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(lastResortPreKey.signature()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// No identity type
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(lastResortPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(lastResortPreKey.signature()))
|
||||
.build())
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Bad public key
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.empty())
|
||||
.setSignature(ByteString.copyFrom(lastResortPreKey.signature()))
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Bad signature
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(lastResortPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.empty())
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearSignature()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Missing key
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearSignedPreKey()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -605,7 +605,7 @@ class KeysGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
@@ -630,7 +630,7 @@ class KeysGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(accountIdentifier)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
@@ -658,7 +658,7 @@ class KeysGrpcServiceTest {
|
||||
when(preKeysRateLimiter.validateReactive(anyString()))
|
||||
.thenReturn(Mono.error(new RateLimitExceededException(retryAfterDuration, false)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.ServerInterceptors;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
|
||||
import org.signal.chat.profile.ProfileGrpc;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPaymentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
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.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ProfileGrpcServiceTest {
|
||||
private static final UUID AUTHENTICATED_ACI = UUID.randomUUID();
|
||||
private static final long AUTHENTICATED_DEVICE_ID = Device.MASTER_ID;
|
||||
private static final String S3_BUCKET = "profileBucket";
|
||||
private static final String VERSION = "someVersion";
|
||||
private static final byte[] VALID_NAME = new byte[81];
|
||||
private ProfilesManager profilesManager;
|
||||
private DynamicPaymentsConfiguration dynamicPaymentsConfiguration;
|
||||
private S3AsyncClient asyncS3client;
|
||||
private VersionedProfile profile;
|
||||
private Account account;
|
||||
private ProfileGrpc.ProfileBlockingStub profileBlockingStub;
|
||||
|
||||
@RegisterExtension
|
||||
static final GrpcServerExtension GRPC_SERVER_EXTENSION = new GrpcServerExtension();
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
profilesManager = mock(ProfilesManager.class);
|
||||
dynamicPaymentsConfiguration = mock(DynamicPaymentsConfiguration.class);
|
||||
asyncS3client = mock(S3AsyncClient.class);
|
||||
profile = mock(VersionedProfile.class);
|
||||
account = mock(Account.class);
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final PolicySigner policySigner = new PolicySigner("accessSecret", "us-west-1");
|
||||
final PostPolicyGenerator policyGenerator = new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey");
|
||||
final BadgesConfiguration badgesConfiguration = new BadgesConfiguration(
|
||||
List.of(new BadgeConfiguration(
|
||||
"TEST",
|
||||
"other",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"),
|
||||
"SVG",
|
||||
List.of(
|
||||
new BadgeSvg("sl", "sd"),
|
||||
new BadgeSvg("ml", "md"),
|
||||
new BadgeSvg("ll", "ld")
|
||||
)
|
||||
)),
|
||||
List.of("TEST1"),
|
||||
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")
|
||||
);
|
||||
final String phoneNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
profileBlockingStub = ProfileGrpc.newBlockingStub(GRPC_SERVER_EXTENSION.getChannel());
|
||||
|
||||
final ProfileGrpcService profileGrpcService = new ProfileGrpcService(
|
||||
Clock.systemUTC(),
|
||||
accountsManager,
|
||||
profilesManager,
|
||||
dynamicConfigurationManager,
|
||||
badgesConfiguration,
|
||||
asyncS3client,
|
||||
policyGenerator,
|
||||
policySigner,
|
||||
S3_BUCKET
|
||||
);
|
||||
|
||||
final MockAuthenticationInterceptor mockAuthenticationInterceptor = new MockAuthenticationInterceptor();
|
||||
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, AUTHENTICATED_DEVICE_ID);
|
||||
|
||||
GRPC_SERVER_EXTENSION.getServiceRegistry()
|
||||
.addService(ServerInterceptors.intercept(profileGrpcService, mockAuthenticationInterceptor));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
|
||||
|
||||
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(account.getNumber()).thenReturn(phoneNumber);
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
|
||||
when(profile.getPaymentAddress()).thenReturn(null);
|
||||
when(profile.getAvatar()).thenReturn("");
|
||||
|
||||
when(accountsManager.getByAccountIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(profilesManager.getAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
|
||||
when(profilesManager.setAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
|
||||
when(dynamicPaymentsConfiguration.getDisallowedPrefixes()).thenReturn(Collections.emptyList());
|
||||
|
||||
when(asyncS3client.deleteObject(any(DeleteObjectRequest.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfile() throws InvalidInputException {
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
final byte[] validAboutEmoji = new byte[60];
|
||||
final byte[] validAbout = new byte[540];
|
||||
final byte[] validPaymentAddress = new byte[582];
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setAboutEmoji(ByteString.copyFrom(validAboutEmoji))
|
||||
.setAbout(ByteString.copyFrom(validAbout))
|
||||
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
profileBlockingStub.setProfile(request);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
verify(profilesManager).setAsync(eq(account.getUuid()), profileArgumentCaptor.capture());
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
|
||||
assertThat(profile.getCommitment()).isEqualTo(commitment);
|
||||
assertThat(profile.getAvatar()).isNull();
|
||||
assertThat(profile.getVersion()).isEqualTo(VERSION);
|
||||
assertThat(profile.getName()).isEqualTo(encodeToBase64(VALID_NAME));
|
||||
assertThat(profile.getAboutEmoji()).isEqualTo(encodeToBase64(validAboutEmoji));
|
||||
assertThat(profile.getAbout()).isEqualTo(encodeToBase64(validAbout));
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo(encodeToBase64(validPaymentAddress));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setProfileUpload(AvatarChange avatarChange, boolean hasPreviousProfile,
|
||||
boolean expectHasS3UploadPath, boolean expectDeleteS3Object) throws InvalidInputException {
|
||||
final String currentAvatar = "profiles/currentAvatar";
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(avatarChange)
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
|
||||
when(profile.getAvatar()).thenReturn(currentAvatar);
|
||||
|
||||
when(profilesManager.getAsync(any(), anyString())).thenReturn(CompletableFuture.completedFuture(
|
||||
hasPreviousProfile ? Optional.of(profile) : Optional.empty()));
|
||||
when(profilesManager.setAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
SetProfileResponse response = profileBlockingStub.setProfile(request);
|
||||
|
||||
if (expectHasS3UploadPath) {
|
||||
assertTrue(response.getAttributes().getPath().startsWith("profiles/"));
|
||||
} else {
|
||||
assertEquals(response.getAttributes().getPath(), "");
|
||||
}
|
||||
|
||||
if (expectDeleteS3Object) {
|
||||
verify(asyncS3client).deleteObject(DeleteObjectRequest.builder()
|
||||
.bucket(S3_BUCKET)
|
||||
.key(currentAvatar)
|
||||
.build());
|
||||
} else {
|
||||
verifyNoInteractions(asyncS3client);
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setProfileUpload() {
|
||||
return Stream.of(
|
||||
// Upload new avatar, no previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UPDATE, false, true, false),
|
||||
// Upload new avatar, has previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UPDATE, true, true, true),
|
||||
// Clear avatar on profile, no previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_CLEAR, false, false, false),
|
||||
// Clear avatar on profile, has previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_CLEAR, true, false, true),
|
||||
// Set same avatar, no previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UNCHANGED, false, false, false),
|
||||
// Set same avatar, has previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UNCHANGED, true, false, false)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setProfileInvalidRequestData(SetProfileRequest request) {
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> profileBlockingStub.setProfile(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setProfileInvalidRequestData() throws InvalidInputException{
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO)).serialize();
|
||||
final byte[] invalidValue = new byte[42];
|
||||
|
||||
final SetProfileRequest prototypeRequest = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing version
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearVersion()
|
||||
.build()),
|
||||
// Missing name
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearName()
|
||||
.build()),
|
||||
// Invalid name length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setName(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid about emoji length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setAboutEmoji(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid about length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setAbout(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid payment address
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setPaymentAddress(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Missing profile commitment
|
||||
Arguments.of(SetProfileRequest.newBuilder()
|
||||
.clearCommitment()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void setPaymentAddressDisallowedCountry(boolean hasExistingPaymentAddress) throws InvalidInputException {
|
||||
final Phonenumber.PhoneNumber disallowedPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("CU");
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
final byte[] validPaymentAddress = new byte[582];
|
||||
if (hasExistingPaymentAddress) {
|
||||
when(profile.getPaymentAddress()).thenReturn(encodeToBase64(validPaymentAddress));
|
||||
}
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
final String disallowedCountryCode = String.format("+%d", disallowedPhoneNumber.getCountryCode());
|
||||
when(dynamicPaymentsConfiguration.getDisallowedPrefixes()).thenReturn(List.of(disallowedCountryCode));
|
||||
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
|
||||
disallowedPhoneNumber,
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164));
|
||||
when(profilesManager.getAsync(any(), anyString())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
|
||||
|
||||
if (hasExistingPaymentAddress) {
|
||||
assertDoesNotThrow(() -> profileBlockingStub.setProfile(request),
|
||||
"Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address");
|
||||
} else {
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> profileBlockingStub.setProfile(request));
|
||||
assertEquals(Status.PERMISSION_DENIED.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
}
|
||||
|
||||
private static String encodeToBase64(byte[] input) {
|
||||
return Base64.getEncoder().encodeToString(input);
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import java.time.Duration;
|
||||
|
||||
public class CardinalityEstimatorTest {
|
||||
|
||||
@RegisterExtension
|
||||
private static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
@Test
|
||||
public void testAdd() throws Exception {
|
||||
final FaultTolerantRedisCluster redisCluster = REDIS_CLUSTER_EXTENSION.getRedisCluster();
|
||||
final CardinalityEstimator estimator = new CardinalityEstimator(redisCluster, "test", Duration.ofSeconds(1));
|
||||
|
||||
estimator.add("1");
|
||||
|
||||
long count = redisCluster.withCluster(conn -> conn.sync().pfcount("cardinality_estimator::test"));
|
||||
assertThat(count).isEqualTo(1).isEqualTo(estimator.estimate());
|
||||
|
||||
estimator.add("2");
|
||||
count = redisCluster.withCluster(conn -> conn.sync().pfcount("cardinality_estimator::test"));
|
||||
assertThat(count).isEqualTo(2).isEqualTo(estimator.estimate());
|
||||
|
||||
estimator.add("1");
|
||||
count = redisCluster.withCluster(conn -> conn.sync().pfcount("cardinality_estimator::test"));
|
||||
assertThat(count).isEqualTo(2).isEqualTo(estimator.estimate());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(5)
|
||||
public void testEventuallyExpires() throws InterruptedException {
|
||||
final FaultTolerantRedisCluster redisCluster = REDIS_CLUSTER_EXTENSION.getRedisCluster();
|
||||
final CardinalityEstimator estimator = new CardinalityEstimator(redisCluster, "test", Duration.ofMillis(100));
|
||||
estimator.add("1");
|
||||
long count;
|
||||
do {
|
||||
count = redisCluster.withCluster(conn -> conn.sync().pfcount("cardinality_estimator::test"));
|
||||
Thread.sleep(1);
|
||||
} while (count != 0);
|
||||
}
|
||||
|
||||
}
|
||||
+6
-1
@@ -46,6 +46,7 @@ import org.glassfish.jersey.uri.UriTemplate;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.websocket.WebSocketResourceProvider;
|
||||
import org.whispersystems.websocket.auth.WebsocketAuthValueFactoryProvider;
|
||||
import org.whispersystems.websocket.logging.WebsocketRequestLog;
|
||||
@@ -65,7 +66,11 @@ class MetricsRequestEventListenerTest {
|
||||
void setup() {
|
||||
meterRegistry = mock(MeterRegistry.class);
|
||||
counter = mock(Counter.class);
|
||||
listener = new MetricsRequestEventListener(TRAFFIC_SOURCE, meterRegistry);
|
||||
|
||||
final ClientReleaseManager clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
when(clientReleaseManager.isVersionActive(any(), any())).thenReturn(false);
|
||||
|
||||
listener = new MetricsRequestEventListener(TRAFFIC_SOURCE, meterRegistry, clientReleaseManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -5,8 +5,13 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
||||
@@ -19,4 +24,25 @@ class MetricsUtilTest {
|
||||
assertEquals("chat.MetricsUtilTest.namespace.metric",
|
||||
MetricsUtil.name(MetricsUtilTest.class, "namespace", "metric"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lettuceRejection() {
|
||||
MeterRegistry registry = new SimpleMeterRegistry();
|
||||
MetricsUtil.configureMeterFilters(registry.config());
|
||||
|
||||
registry.counter("lettuce.command.completion.count").increment();
|
||||
registry.counter("lettuce.command.firstresponse.max").increment();
|
||||
registry.counter("lettuce.test").increment();
|
||||
assertThat(registry.getMeters()).isEmpty();
|
||||
|
||||
// this lettuce statistic is allow-listed
|
||||
registry.counter("lettuce.command.completion.max", "command", "hello", "remote", "world").increment();
|
||||
final List<Meter> meters = registry.getMeters();
|
||||
assertThat(meters).hasSize(1);
|
||||
|
||||
Meter meter = meters.get(0);
|
||||
assertThat(meter.getId().getName()).isEqualTo("chat.lettuce.command.completion.max");
|
||||
assertThat(meter.getId().getTag("command")).isNull();
|
||||
assertThat(meter.getId().getTag("remote")).isNotNull();
|
||||
}
|
||||
}
|
||||
@@ -92,86 +92,86 @@ class AccountTest {
|
||||
when(oldSecondaryDevice.getId()).thenReturn(2L);
|
||||
|
||||
when(senderKeyCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(senderKeyCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(senderKeyIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, false, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(senderKeyIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(senderKeyIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, false, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(senderKeyIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(announcementGroupCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(announcementGroupCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(announcementGroupIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(announcementGroupIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(announcementGroupIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(announcementGroupIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(changeNumberCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, true, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(changeNumberCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(changeNumberIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(changeNumberIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(changeNumberIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(changeNumberIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(pniCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, true, false, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(pniCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(pniIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(pniIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(pniIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(pniIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(storiesCapableDevice.getId()).thenReturn(1L);
|
||||
when(storiesCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, true, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(storiesCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(storiesCapableDevice.getId()).thenReturn(2L);
|
||||
when(storiesIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(storiesIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(storiesCapableDevice.getId()).thenReturn(3L);
|
||||
when(storiesIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(storiesIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(giftBadgesCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, true, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(giftBadgesCapableDevice.isEnabled()).thenReturn(true);
|
||||
when(giftBadgesIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(giftBadgesIncapableDevice.isEnabled()).thenReturn(true);
|
||||
when(giftBadgesIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(giftBadgesIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(paymentActivationCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, true, true));
|
||||
new DeviceCapabilities(true, true, true, true));
|
||||
when(paymentActivationCapableDevice.isEnabled()).thenReturn(true);
|
||||
when(paymentActivationIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(paymentActivationIncapableDevice.isEnabled()).thenReturn(true);
|
||||
when(paymentActivationIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(paymentActivationIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
}
|
||||
@@ -222,8 +222,8 @@ class AccountTest {
|
||||
when(transferCapableLinkedDevice.isMaster()).thenReturn(false);
|
||||
when(transferCapableLinkedDevice.getCapabilities()).thenReturn(transferCapabilities);
|
||||
|
||||
when(transferCapabilities.isTransfer()).thenReturn(true);
|
||||
when(nonTransferCapabilities.isTransfer()).thenReturn(false);
|
||||
when(transferCapabilities.transfer()).thenReturn(true);
|
||||
when(nonTransferCapabilities.transfer()).thenReturn(false);
|
||||
|
||||
{
|
||||
final Account transferableMasterAccount =
|
||||
@@ -261,44 +261,6 @@ class AccountTest {
|
||||
assertTrue(account.isDiscoverableByPhoneNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isSenderKeySupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), List.of(senderKeyCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isSenderKeySupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(senderKeyCapableDevice, senderKeyIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isSenderKeySupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(senderKeyCapableDevice, senderKeyIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isSenderKeySupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAnnouncementGroupSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(announcementGroupCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(announcementGroupCapableDevice, announcementGroupIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(announcementGroupCapableDevice, announcementGroupIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isChangeNumberSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(changeNumberCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isChangeNumberSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(changeNumberCapableDevice, changeNumberIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isChangeNumberSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(changeNumberCapableDevice, changeNumberIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isChangeNumberSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isPniSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
@@ -312,32 +274,6 @@ class AccountTest {
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isPniSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStoriesSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(storiesCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(storiesCapableDevice, storiesIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(storiesCapableDevice, storiesIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isGiftBadgesSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(giftBadgesCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isGiftBadgesSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(giftBadgesCapableDevice, giftBadgesIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isGiftBadgesSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(giftBadgesCapableDevice, giftBadgesIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isGiftBadgesSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isPaymentActivationSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
|
||||
+5
-3
@@ -103,6 +103,9 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final KeysManager keysManager = mock(KeysManager.class);
|
||||
when(keysManager.delete(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -110,9 +113,8 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
accountLockManager,
|
||||
deletedAccounts,
|
||||
keysManager,
|
||||
mock(MessagesManager.class),
|
||||
messagesManager,
|
||||
mock(ProfilesManager.class),
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
secureStorageClient,
|
||||
secureBackupClient,
|
||||
svr2Client,
|
||||
@@ -154,7 +156,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
final ECSignedPreKey rotatedSignedPreKey = KeysHelper.signedECPreKey(1L, pniIdentityKeyPair);
|
||||
|
||||
final AccountAttributes accountAttributes = new AccountAttributes(true, rotatedPniRegistrationId + 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
final AccountAttributes accountAttributes = new AccountAttributes(true, rotatedPniRegistrationId + 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
final Account account = accountsManager.create(originalNumber, "password", null, accountAttributes, new ArrayList<>());
|
||||
account.getMasterDevice().orElseThrow().setSignedPreKey(KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
|
||||
|
||||
|
||||
-1
@@ -118,7 +118,6 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(KeysManager.class),
|
||||
mock(MessagesManager.class),
|
||||
mock(ProfilesManager.class),
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureBackupClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
|
||||
+2
-2
@@ -188,6 +188,7 @@ class AccountsManagerTest {
|
||||
}).when(accountLockManager).withLock(any(), any());
|
||||
|
||||
when(keysManager.delete(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
@@ -201,7 +202,6 @@ class AccountsManagerTest {
|
||||
keysManager,
|
||||
messagesManager,
|
||||
profilesManager,
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
storageClient,
|
||||
backupClient,
|
||||
svr2Client,
|
||||
@@ -977,7 +977,7 @@ class AccountsManagerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testCreateWithStorageCapability(final boolean hasStorage) throws InterruptedException {
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 0, null, null, true,
|
||||
new DeviceCapabilities(hasStorage, false, false, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(hasStorage, false, false, false));
|
||||
|
||||
final Account account = accountsManager.create("+18005550123", "password", null, attributes, new ArrayList<>());
|
||||
|
||||
|
||||
-1
@@ -123,7 +123,6 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
mock(KeysManager.class),
|
||||
mock(MessagesManager.class),
|
||||
mock(ProfilesManager.class),
|
||||
mock(StoredVerificationCodeManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureBackupClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user