Compare commits

...
Author SHA1 Message Date
Jon Chambers d225ba3618 Align FoundationDB default page size with mirroring page size 2026-06-30 17:14:06 -04:00
Jon Chambers 8790514b8a Establish presence when fetching messages from FoundationDB 2026-06-30 11:36:22 -04:00
Jon Chambers fa4d3c7ca9 Avoid automatic, unbounded requests on subscription 2026-06-30 11:36:22 -04:00
Jon Chambers 1f0b2ad92d Reapply "Mirror message reads/acknowledgements via FoundationDbMessageStream"
This reverts commit 28aefe0ebe.
2026-06-30 11:36:22 -04:00
Chris Eager feb00c6ba6 Add avatars to profiles gRPC 2026-06-29 13:15:07 -05:00
Ravi Khadiwala f588390bdb Handle ACCOUNT_NOT_FOUND errors in AppleAppStoreClient 2026-06-29 13:11:00 -05:00
Jon Chambers 355b320c92 Don't attempt to send empty message bundles when changing numbers 2026-06-26 15:51:28 -04:00
Jon Chambers 40fb9c4cee Fix a bogus assertion for "change number" message-sending 2026-06-26 15:51:28 -04:00
Ravi Khadiwala aa5ac70ad3 Select lifecycle-manager based on environment variable (like in FoundationDbClusterExtension) 2026-06-25 17:42:04 -04:00
Jon Chambers 2abf55e395 Don't trigger state transitions inside retryable transactions 2026-06-25 17:41:33 -04:00
Jon Chambers 808bb16103 Add basic read/acknowledgement counters to RedisDynamoDbMessageStream 2026-06-25 17:41:11 -04:00
Ameya Lokare 4743abcfbd Port OneTimeDonationController to gRPC 2026-06-25 17:40:49 -04:00
Katherine 1b09529ece Use V2 key transparency query RPCs 2026-06-24 15:02:34 -07:00
Chris Eager 0c3c390a0b Update Donation-Permit header parameter documentation 2026-06-24 14:51:46 -07:00
Chris Eager ca4ee141d8 Disable a flaky test 2026-06-24 13:18:07 -05:00
Jonathan Klabunde TomerandJon Chambers 671a6e1d7c address review comments
Co-authored-by: Jon Chambers <63609320+jon-signal@users.noreply.github.com>
2026-06-24 12:14:52 -05:00
Jonathan Klabunde Tomer f4e16676c9 add FoundationDbMessageStore api to clear messages before a given time 2026-06-24 12:14:52 -05:00
Chris Eager 78b3147491 Implement donation permit spending 2026-06-24 12:13:21 -05:00
Ravi Khadiwala 8b617b64f8 Add metric for requested attachment upload size 2026-06-24 12:11:57 -05:00
Jon Chambers 28aefe0ebe Revert "Mirror message reads/acknowledgements via FoundationDbMessageStream"
This reverts commit 4e52317e26.
2026-06-24 13:01:13 -04:00
Jon Chambers 4e52317e26 Mirror message reads/acknowledgements via FoundationDbMessageStream 2026-06-24 10:18:15 -04:00
Ravi Khadiwala 99465c1f41 Update to the latest version of the spam filter 2026-06-23 13:13:49 -05:00
Chris Eager 041c29bfa8 Update foundationdb to 7.3.68 2026-06-23 13:11:05 -05:00
Chris Eager 8e5ad7f52e Remove unused mocking in CredentialsGrpcServiceTest 2026-06-23 13:11:05 -05:00
Jon Chambers ca5d203f1c Make RegistrationServiceClient blocking 2026-06-23 13:09:12 -05:00
ravi-signal 9a9b15ee0a Add per-element constraint validation 2026-06-23 13:08:39 -05:00
ravi-signal 503941ec6a Add a load-shedding GOAWAY 2026-06-23 13:07:49 -05:00
116 changed files with 5486 additions and 1739 deletions

No files matched your search

+6 -6
View File
@@ -14,14 +14,14 @@ jobs:
services:
foundationdb0:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
# bump it purely to match the CLIENT version
image: foundationdb/foundationdb:7.3.68
options: --name foundationdb0
foundationdb1:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
# bump it purely to match the CLIENT version
image: foundationdb/foundationdb:7.3.68
options: --name foundationdb1
steps:
+5 -6
View File
@@ -50,13 +50,12 @@
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.21.0</commons-io.version>
<dropwizard.version>5.0.1</dropwizard.version>
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
with even-numbered patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDB
used by GitHub Actions. -->
<foundationdb.version>7.3.62</foundationdb.version>
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
Actions. -->
<foundationdb.version>7.3.68</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.13.2</gson.version>
+1
View File
@@ -82,6 +82,7 @@ zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcd
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
profileAvatarsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
paymentsService.fixerApiKey: unset
+8
View File
@@ -100,6 +100,9 @@ dynamoDbTables:
tableName: Example_DeletedAccounts
deletedAccountsLock:
tableName: Example_DeletedAccountsLock
donationPermits:
tableName: Example_DonationPermits
expiration: P7D # Duration of time until rows expire
issuedReceipts:
tableName: Example_IssuedReceipts
expiration: P30D # Duration of time until rows expire
@@ -125,6 +128,8 @@ dynamoDbTables:
expiration: P90D
phoneNumberIdentifiers:
tableName: Example_PhoneNumberIdentifiers
profileAvatars:
tableName: Example_ProfileAvatars
profiles:
tableName: Example_Profiles
profilesV2:
@@ -323,6 +328,9 @@ callingZkConfig:
backupsZkConfig:
serverSecret: secret://backupsZkConfig.serverSecret
profileAvatarsZkConfig:
serverSecret: secret://profileAvatarsZkConfig.serverSecret
dynamicConfig:
s3Region: a-region
s3Bucket: a-bucket
@@ -235,6 +235,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GenericZkConfig backupsZkConfig;
@Valid
@NotNull
@JsonProperty
private GenericZkConfig profileAvatarsZkConfig;
@Valid
@NotNull
@JsonProperty
@@ -499,6 +504,10 @@ public class WhisperServerConfiguration extends Configuration {
return backupsZkConfig;
}
public GenericZkConfig getProfileAvatarsZkConfig() {
return profileAvatarsZkConfig;
}
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
return remoteConfig;
}
@@ -176,6 +176,7 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
@@ -251,6 +252,8 @@ import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriodManager
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.ClientReleases;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.FoundationDbVersion;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
@@ -262,6 +265,7 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
@@ -535,6 +539,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
config.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
@@ -615,6 +621,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.threads(16).build();
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
final ScheduledExecutorService presenceRenewalExecutor =
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
ExecutorServiceBuilder.of(environment, "messageDelivery")
@@ -633,10 +641,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.workQueue(receiptSenderQueue)
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
.build();
ExecutorService registrationCallbackExecutor = ExecutorServiceBuilder.of(environment, "registration")
.maxThreads(2)
.minThreads(2)
.build();
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
.minThreads(8)
.maxThreads(8)
@@ -718,7 +722,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
retryExecutor);
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
.build(environment, registrationCallbackExecutor, registrationIdentityTokenRefreshExecutor);
.build(environment, registrationIdentityTokenRefreshExecutor);
KeyTransparencyServiceClient keyTransparencyServiceClient = new KeyTransparencyServiceClient(
config.getKeyTransparencyServiceConfiguration().host(),
config.getKeyTransparencyServiceConfiguration().port(),
@@ -741,7 +745,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
disconnectionRequestListenerExecutor, retryExecutor);
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock);
@@ -749,6 +753,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getFoundationDbMessagesConfiguration().activeEpoch(),
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
presenceRenewalExecutor,
Clock.systemUTC());
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
@@ -789,6 +794,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbClient);
DonationPermits donationPermits = new DonationPermits(
config.getDynamoDbTables().getDonationPermits().getTableName(), config.getDynamoDbTables().getDonationPermits().getExpiration(), dynamoDbClient);
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
dynamoDbClient,
@@ -910,6 +917,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().value());
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
GenericServerSecretParams backupsGenericZkSecretParams = new GenericServerSecretParams(config.getBackupsZkConfig().serverSecret().value());
GenericServerSecretParams profileAvatarsGenericZkSecretParams = new GenericServerSecretParams(config.getProfileAvatarsZkConfig().serverSecret().value());
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(zkSecretParams);
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(zkSecretParams);
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
@@ -953,6 +961,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAppleDeviceCheck().teamId(),
config.getAppleDeviceCheck().bundleId());
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, zkSecretParams,
clock);
final SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
zkReceiptOperations, issuedReceiptsManager);
@@ -1060,7 +1071,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileBadgeConverter, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
@@ -1069,7 +1080,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAttachments().maxAttachmentUploadSizeInBytes(), Clock.systemUTC()),
new PaymentsGrpcService(currencyManager),
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new))
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -1086,13 +1097,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, zkSecretParams, rateLimiters, clock),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
new SubscriptionsGrpcService(clock, config.getSubscription(), config.getOneTimeDonations(), subscriptionManager,
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, profileBadgeConverter,
bankMandateTranslator, dynamicConfigurationManager))
donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager),
new OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, oneTimeDonationsManager, issuedReceiptsManager,
zkReceiptOperations, clock, rateLimiters, donationPermitsManager))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -1133,6 +1147,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
omnibusNioEventLoopGroup.getEventLoopGroup(),
omnibusLocalEventLoopGroup.getEventLoopGroup(),
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
config.getGrpc().idleTimeout());
environment.lifecycle().manage(omnibusLocalEventLoopGroup);
@@ -1222,7 +1237,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeviceCheck().backupRedemptionDuration()),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new, zkSecretParams, rateLimiters),
ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
@@ -1244,9 +1259,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
dynamicConfigurationManager, experimentEnrollmentManager, clock),
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager),
profileBadgeConverter, bankMandateTranslator, donationPermitsManager, dynamicConfigurationManager),
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager)
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
donationPermitsManager)
);
for (Object controller : commonControllers) {
@@ -1362,7 +1378,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
}
}
public static void main(String[] args) throws Exception {
static void main(String[] args) throws Exception {
new WhisperServerService().run(args);
}
}
@@ -0,0 +1,24 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import java.util.Base64;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
public record DonationPermitHeader(DonationPermit permit) {
public static DonationPermitHeader valueOf(String header) {
try {
return new DonationPermitHeader(new DonationPermit(Base64.getDecoder().decode(header)));
} catch (InvalidInputException | IllegalArgumentException e) {
// Base64 throws IllegalArgumentException; DonationPermit ctor throws InvalidInputException
throw new WebApplicationException(e, Response.Status.UNAUTHORIZED);
}
}
}
@@ -16,10 +16,10 @@ import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
@@ -28,7 +28,6 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import javax.annotation.Nullable;
public class PhoneVerificationTokenManager {
@@ -90,11 +89,10 @@ public class PhoneVerificationTokenManager {
return verificationType;
}
private void verifyBySessionId(final String number, final byte[] sessionId) throws InterruptedException {
private void verifyBySessionId(final String number, final byte[] sessionId) {
try {
final RegistrationServiceSession session = registrationServiceClient
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
@@ -103,19 +101,11 @@ public class PhoneVerificationTokenManager {
if (!session.verified()) {
throw new NotAuthorizedException("session not verified");
}
} catch (final ExecutionException e) {
if (e.getCause() instanceof StatusRuntimeException grpcRuntimeException) {
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
} catch (final StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
} catch (final CancellationException | TimeoutException e) {
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
}
@@ -55,6 +55,7 @@ public class DynamoDbTables {
private final Table clientReleases;
private final Table deletedAccounts;
private final Table deletedAccountsLock;
private final TableWithExpiration donationPermits;
private final IssuedReceiptsTableConfiguration issuedReceipts;
private final Table ecKeys;
private final Table ecSignedPreKeys;
@@ -63,6 +64,7 @@ public class DynamoDbTables {
private final TableWithExpiration messages;
private final TableWithExpiration onetimeDonations;
private final Table phoneNumberIdentifiers;
private final Table profileAvatars;
private final Table profiles;
private final Table profilesV2;
private final Table pushChallenge;
@@ -84,6 +86,7 @@ public class DynamoDbTables {
@JsonProperty("clientReleases") final Table clientReleases,
@JsonProperty("deletedAccounts") final Table deletedAccounts,
@JsonProperty("deletedAccountsLock") final Table deletedAccountsLock,
@JsonProperty("donationPermits") final TableWithExpiration donationPermits,
@JsonProperty("issuedReceipts") final IssuedReceiptsTableConfiguration issuedReceipts,
@JsonProperty("ecKeys") final Table ecKeys,
@JsonProperty("ecSignedPreKeys") final Table ecSignedPreKeys,
@@ -92,6 +95,7 @@ public class DynamoDbTables {
@JsonProperty("messages") final TableWithExpiration messages,
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@JsonProperty("profileAvatars") final Table profileAvatars,
@JsonProperty("profiles") final Table profiles,
@JsonProperty("profilesV2") final Table profilesV2,
@JsonProperty("pushChallenge") final Table pushChallenge,
@@ -112,6 +116,7 @@ public class DynamoDbTables {
this.clientReleases = clientReleases;
this.deletedAccounts = deletedAccounts;
this.deletedAccountsLock = deletedAccountsLock;
this.donationPermits = donationPermits;
this.issuedReceipts = issuedReceipts;
this.ecKeys = ecKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
@@ -120,6 +125,7 @@ public class DynamoDbTables {
this.messages = messages;
this.onetimeDonations = onetimeDonations;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profileAvatars = profileAvatars;
this.profiles = profiles;
this.profilesV2 = profilesV2;
this.pushChallenge = pushChallenge;
@@ -181,6 +187,12 @@ public class DynamoDbTables {
return deletedAccountsLock;
}
@NotNull
@Valid
public TableWithExpiration getDonationPermits() {
return donationPermits;
}
@NotNull
@Valid
public IssuedReceiptsTableConfiguration getIssuedReceipts() {
@@ -229,6 +241,12 @@ public class DynamoDbTables {
return phoneNumberIdentifiers;
}
@NotNull
@Valid
public Table getProfileAvatars() {
return profileAvatars;
}
@NotNull
@Valid
public Table getProfilesV1() {
@@ -15,6 +15,5 @@ import java.util.concurrent.ScheduledExecutorService;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RegistrationServiceConfiguration.class)
public interface RegistrationServiceClientFactory extends Discoverable {
RegistrationServiceClient build(Environment environment, Executor callbackExecutor,
ScheduledExecutorService identityRefreshExecutor);
RegistrationServiceClient build(Environment environment, ScheduledExecutorService identityRefreshExecutor);
}
@@ -5,7 +5,6 @@ import io.dropwizard.core.setup.Environment;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.registration.IdentityTokenCallCredentials;
@@ -21,16 +20,16 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
RegistrationServiceClientFactory {
@Override
public RegistrationServiceClient build(final Environment environment, final Executor callbackExecutor,
public RegistrationServiceClient build(final Environment environment,
final ScheduledExecutorService identityRefreshExecutor) {
try {
final IdentityTokenCallCredentials callCredentials = IdentityTokenCallCredentials.fromCredentialConfig(
credentialConfigurationJson, identityTokenAudience, identityRefreshExecutor);
environment.lifecycle().manage(callCredentials);
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value(),
identityRefreshExecutor);
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value());
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -80,6 +81,10 @@ public class DynamicConfiguration {
@Valid
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@JsonProperty
@Valid
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
@JsonProperty
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
@@ -150,6 +155,10 @@ public class DynamicConfiguration {
return grpcAllowList;
}
public DynamicOmnibusConfiguration getOmnibus() {
return omnibus;
}
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
@@ -0,0 +1,13 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import java.math.BigDecimal;
/// @param rejectConnectionRatio The proportion of connection attempts that should be immediately closed with a GOAWAY
public record DynamicOmnibusConfiguration(@DecimalMin("0.0") @DecimalMax("1.0") BigDecimal rejectConnectionRatio) {
}
@@ -5,16 +5,21 @@
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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 jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
@@ -24,6 +29,7 @@ import java.security.SecureRandom;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
@@ -33,6 +39,8 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
/**
@@ -40,7 +48,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
* (message attachments) to a remote storage location. The location may be selected by the server at runtime.
*/
@Path("/v4/attachments")
@Tag(name = "Attachments")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Attachments")
public class AttachmentControllerV4 {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
@@ -50,6 +58,9 @@ public class AttachmentControllerV4 {
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private static final String ATTACHMENT_SIZE_NAME =
MetricsUtil.name(AttachmentControllerV4.class, "attachmentSize");
@Nonnull
private final SecureRandom secureRandom;
@@ -91,7 +102,8 @@ public class AttachmentControllerV4 {
public AttachmentDescriptorV3 getAttachmentUploadForm(
@Auth AuthenticatedDevice auth,
@Parameter(description = "The size of the attachment to upload in bytes")
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength)
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent)
throws RateLimitExceededException {
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
@@ -111,6 +123,12 @@ public class AttachmentControllerV4 {
}
}
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("uploadLengthSupplied", Boolean.toString(maybeUploadLength.isPresent()))))
.register(Metrics.globalRegistry)
.record(uploadLength);
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), AttachmentUtil.CDN3_EXPERIMENT_NAME);
int cdn = useCdn3 ? 3 : 2;
@@ -24,9 +24,7 @@ import java.time.Instant;
import java.util.Objects;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermitDerivedKeyPair;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
@@ -40,6 +38,7 @@ import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
@@ -53,7 +52,7 @@ public class DonationController {
private final AccountsManager accountsManager;
private final BadgesConfiguration badgesConfiguration;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private final ServerSecretParams serverSecretParams;
private final DonationPermitsManager donationPermitsManager;
private final RateLimiters rateLimiters;
public DonationController(
@@ -63,7 +62,7 @@ public class DonationController {
final AccountsManager accountsManager,
final BadgesConfiguration badgesConfiguration,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
final ServerSecretParams serverSecretParams,
final DonationPermitsManager donationPermitsManager,
final RateLimiters rateLimiters) {
this.clock = Objects.requireNonNull(clock);
this.serverZkReceiptOperations = Objects.requireNonNull(serverZkReceiptOperations);
@@ -71,7 +70,7 @@ public class DonationController {
this.accountsManager = Objects.requireNonNull(accountsManager);
this.badgesConfiguration = Objects.requireNonNull(badgesConfiguration);
this.receiptCredentialPresentationFactory = Objects.requireNonNull(receiptCredentialPresentationFactory);
this.serverSecretParams = Objects.requireNonNull(serverSecretParams);
this.donationPermitsManager = Objects.requireNonNull(donationPermitsManager);
this.rateLimiters = Objects.requireNonNull(rateLimiters);
}
@@ -169,10 +168,7 @@ public class DonationController {
rateLimiters.getCreateDonationPermitLimiter().validate(auth.accountIdentifier(), permitRequest.getPermitCount());
final DonationPermitDerivedKeyPair derivedKeyPair = DonationPermitDerivedKeyPair.forExpiration(
DonationPermitResponse.defaultExpiration(clock.instant()), serverSecretParams);
final DonationPermitResponse permitResponse = permitRequest.issue(derivedKeyPair);
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
return new CreateDonationPermitResponse(permitResponse.serialize());
}
@@ -33,6 +33,8 @@ import org.glassfish.jersey.server.ManagedAsync;
import org.signal.keytransparency.client.AciMonitorRequest;
import org.signal.keytransparency.client.E164MonitorRequest;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -101,15 +103,23 @@ public class KeyTransparencyController {
.build()
));
return new KeyTransparencySearchResponse(
keyTransparencyServiceClient.search(
ByteString.copyFrom(request.aci().toCompactByteArray()),
ByteString.copyFrom(request.aciIdentityKey().serialize()),
request.usernameHash().map(ByteString::copyFrom),
maybeE164SearchRequest,
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize())
.toByteArray());
final SearchResponseV2 searchResponse = keyTransparencyServiceClient.search(
ByteString.copyFrom(request.aci().toCompactByteArray()),
ByteString.copyFrom(request.aciIdentityKey().serialize()),
request.usernameHash().map(ByteString::copyFrom),
maybeE164SearchRequest,
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize());
if (searchResponse.hasPermissionDenied()) {
throw new StatusRuntimeException(Status.PERMISSION_DENIED);
}
if (!searchResponse.hasSearchResponse()) {
throw new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Missing search response"));
}
return new KeyTransparencySearchResponse(searchResponse.getSearchResponse().toByteArray());
} catch (final StatusRuntimeException exception) {
handleKeyTransparencyServiceError(exception);
}
@@ -163,13 +173,22 @@ public class KeyTransparencyController {
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
.build());
return new KeyTransparencyMonitorResponse(keyTransparencyServiceClient.monitor(
final MonitorResponseV2 monitorResponse = keyTransparencyServiceClient.monitor(
aciMonitorRequest,
usernameHashMonitorRequest,
e164MonitorRequest,
request.lastNonDistinguishedTreeHeadSize(),
request.lastDistinguishedTreeHeadSize())
.toByteArray());
request.lastDistinguishedTreeHeadSize());
if (monitorResponse.hasPermissionDenied()) {
throw new StatusRuntimeException(Status.PERMISSION_DENIED);
}
if (!monitorResponse.hasMonitorResponse()) {
throw new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Missing monitor response"));
}
return new KeyTransparencyMonitorResponse(monitorResponse.getMonitorResponse().toByteArray());
} catch (final StatusRuntimeException exception) {
handleKeyTransparencyServiceError(exception);
}
@@ -4,6 +4,8 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
@@ -11,6 +13,7 @@ import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.StringToClassMapItem;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -36,13 +39,13 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
@@ -51,10 +54,14 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationUtil;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
@@ -67,13 +74,9 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
/**
* Endpoints for making one-time donation payments (boost and gift)
* <p>
@@ -87,8 +90,6 @@ public class OneTimeDonationController {
private static final Logger logger = LoggerFactory.getLogger(OneTimeDonationController.class);
private static final String EURO_CURRENCY_CODE = "EUR";
private final Clock clock;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final StripeManager stripeManager;
@@ -97,16 +98,18 @@ public class OneTimeDonationController {
private final ServerZkReceiptOperations zkReceiptOperations;
private final IssuedReceiptsManager issuedReceiptsManager;
private final OneTimeDonationsManager oneTimeDonationsManager;
private final DonationPermitsManager donationPermitsManager;
public OneTimeDonationController(
@Nonnull Clock clock,
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
@Nonnull StripeManager stripeManager,
@Nonnull BraintreeManager braintreeManager,
@Nonnull PayPalDonationsTranslator payPalDonationsTranslator,
@Nonnull ServerZkReceiptOperations zkReceiptOperations,
@Nonnull IssuedReceiptsManager issuedReceiptsManager,
@Nonnull OneTimeDonationsManager oneTimeDonationsManager) {
final Clock clock,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final StripeManager stripeManager,
final BraintreeManager braintreeManager,
final PayPalDonationsTranslator payPalDonationsTranslator,
final ServerZkReceiptOperations zkReceiptOperations,
final IssuedReceiptsManager issuedReceiptsManager,
final OneTimeDonationsManager oneTimeDonationsManager,
final DonationPermitsManager donationPermitsManager) {
this.clock = Objects.requireNonNull(clock);
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
this.stripeManager = Objects.requireNonNull(stripeManager);
@@ -115,6 +118,7 @@ public class OneTimeDonationController {
this.zkReceiptOperations = Objects.requireNonNull(zkReceiptOperations);
this.issuedReceiptsManager = Objects.requireNonNull(issuedReceiptsManager);
this.oneTimeDonationsManager = Objects.requireNonNull(oneTimeDonationsManager);
this.donationPermitsManager = Objects.requireNonNull(donationPermitsManager);
}
public static class CreateBoostRequest {
@@ -145,10 +149,10 @@ public class OneTimeDonationController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Create a Stripe payment intent", description = """
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
""")
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
""")
@ApiResponse(responseCode = "200", description = "Payment Intent created", content = @Content(schema = @Schema(implementation = CreateBoostResponse.class)))
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
@ApiResponse(responseCode = "400", description = """
@@ -162,16 +166,35 @@ public class OneTimeDonationController {
properties = {
@StringToClassMapItem(key = "error", value = String.class)
})))
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
public CompletableFuture<Response> createBoostPaymentIntent(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid CreateBoostRequest request,
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description = "A base64-encoded donation permit retrieved from POST /v1/donation/permit")
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
@NotNull @Valid final CreateBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "boostCreate", userAgent);
final boolean spendSuccessful = donationPermitHeader.map(
permitHeader -> {
try {
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
} catch (final VerificationFailedException e) {
return false;
}
})
.orElse(true);
if (!spendSuccessful) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager))
.thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
@@ -180,47 +203,34 @@ public class OneTimeDonationController {
}
/**
* Validates that the request level is valid, the currency is supported by the {@code manager} and {@code request.paymentMethod},
* and that the amount meets minimum and maximum constraints.
* Validates that the request level is valid, the currency is supported by the {@code manager} and
* {@code request.paymentMethod}, and that the amount meets minimum and maximum constraints.
*
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
*/
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
final CustomerAwareSubscriptionPaymentProcessor manager) {
if (!(request.level == oneTimeDonationConfiguration.gift().level()
|| request.level == oneTimeDonationConfiguration.boost().level())) {
final Map<String, String> errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency,
amount, request.level, request.paymentMethod, oneTimeDonationConfiguration, manager)) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
Map.of("error", "invalid_level");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
Map.of("error", "unsupported_currency");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) ->
Map.of("error", "amount_below_currency_minimum",
"minimum", min.toString());
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) ->
Map.of("error", "amount_above_sepa_limit",
"maximum", max.toString());
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap();
};
if (!errorBody.isEmpty()) {
throw new BadRequestException(
Response.status(Response.Status.BAD_REQUEST).entity(Map.of("error", "invalid_level")).build());
Response.status(Response.Status.BAD_REQUEST).entity(errorBody).build());
}
if (!manager.getSupportedCurrenciesForPaymentMethod(request.paymentMethod)
.contains(request.currency.toLowerCase(Locale.ROOT))) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", "unsupported_currency")).build());
}
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
.get(request.currency.toLowerCase(Locale.ROOT)).minimum();
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
request.currency,
minCurrencyAmountMajorUnits);
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of(
"error", "amount_below_currency_minimum",
"minimum", minCurrencyAmountMajorUnits.toString())).build());
}
if (request.paymentMethod == PaymentMethod.SEPA_DEBIT &&
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
EURO_CURRENCY_CODE,
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of(
"error", "amount_above_sepa_limit",
"maximum", oneTimeDonationConfiguration.sepaMaximumEuros().toString())).build());
}
}
public static class CreatePayPalBoostRequest extends CreateBoostRequest {
@@ -242,9 +252,9 @@ public class OneTimeDonationController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createPayPalBoost(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid CreatePayPalBoostRequest request,
@Context ContainerRequestContext containerRequestContext) {
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreatePayPalBoostRequest request,
@Context final ContainerRequestContext containerRequestContext) {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
@@ -255,21 +265,11 @@ public class OneTimeDonationController {
.thenCompose(_ -> {
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
// These two localizations are a best-effort, and it's possible that the first `locale` and the localized line
// item name will not match. We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
// but that's a moving target, and we can hopefully have one of them be better for the user by selecting
// independently.
final Locale locale = acceptableLanguages.stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLanguages,
PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
payPalDonationsTranslator, acceptableLanguages);
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
locale.toLanguageTag(),
request.returnUrl, request.cancelUrl, localizedLineItemName);
localizedLineItem.locale().toLanguageTag(),
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
})
.thenApply(approvalDetails -> Response.ok(
new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId())).build());
@@ -296,8 +296,8 @@ public class OneTimeDonationController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> confirmPayPalBoost(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid ConfirmPayPalBoostRequest request,
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final ConfirmPayPalBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
if (authenticatedAccount.isPresent()) {
@@ -340,7 +340,7 @@ public class OneTimeDonationController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createBoostReceiptCredentials(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@@ -348,68 +348,56 @@ public class OneTimeDonationController {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
final CompletableFuture<PaymentDetails> paymentDetailsFut = switch (request.processor) {
final CompletableFuture<Optional<PaymentDetails>> paymentDetailsFut = switch (request.processor) {
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
};
return paymentDetailsFut.thenApply(paymentDetails -> {
if (paymentDetails == null) {
return paymentDetailsFut.thenApply(maybePaymentDetails -> {
if (maybePaymentDetails.isEmpty()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} else if (paymentDetails.status() == PaymentStatus.PROCESSING) {
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return Response.noContent().build();
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
}
// The payment was successful, try to issue the receipt credential
long level = oneTimeDonationConfiguration.boost().level();
if (paymentDetails.customMetadata() != null) {
String levelMetadata = paymentDetails.customMetadata()
.getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level()));
try {
level = Long.parseLong(levelMetadata);
} catch (NumberFormatException e) {
logger.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata,
paymentDetails.id(), e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
Duration levelExpiration;
if (oneTimeDonationConfiguration.boost().level() == level) {
levelExpiration = oneTimeDonationConfiguration.boost().expiration();
} else if (oneTimeDonationConfiguration.gift().level() == level) {
levelExpiration = oneTimeDonationConfiguration.gift().expiration();
} else {
logger.error("level ({}) returned from payment intent that is unknown to the server", level);
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
try {
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
} catch (OneTimeDonationUtil.InvalidLevelException _) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
ReceiptCredentialRequest receiptCredentialRequest;
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
} catch (InvalidInputException e) {
} catch (final InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
final long finalLevel = level;
try {
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant());
} catch (final WriteConflictException _) {
} catch (WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelExpiration)
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), finalLevel);
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
@@ -5,6 +5,11 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildCurrencyConfiguration;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildDonationLevelsConfiguration;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalLocale;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.common.annotations.VisibleForTesting;
@@ -15,6 +20,7 @@ import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -36,6 +42,7 @@ import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
@@ -50,11 +57,12 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
@@ -66,6 +74,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
@@ -90,10 +99,6 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequire
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildCurrencyConfiguration;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildDonationLevelsConfiguration;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
@Path("/v1/subscription")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Subscriptions")
public class SubscriptionController {
@@ -108,6 +113,7 @@ public class SubscriptionController {
private final AppleAppStoreManager appleAppStoreManager;
private final BadgeTranslator badgeTranslator;
private final BankMandateTranslator bankMandateTranslator;
private final DonationPermitsManager donationPermitsManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued");
static final String PROCESSOR_TAG_NAME = "processor";
@@ -115,17 +121,18 @@ public class SubscriptionController {
private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType";
public SubscriptionController(
@Nonnull Clock clock,
@Nonnull SubscriptionConfiguration subscriptionConfiguration,
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
@Nonnull SubscriptionManager subscriptionManager,
@Nonnull StripeManager stripeManager,
@Nonnull BraintreeManager braintreeManager,
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
@Nonnull AppleAppStoreManager appleAppStoreManager,
@Nonnull BadgeTranslator badgeTranslator,
@Nonnull BankMandateTranslator bankMandateTranslator,
@NotNull DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
Clock clock,
SubscriptionConfiguration subscriptionConfiguration,
OneTimeDonationConfiguration oneTimeDonationConfiguration,
SubscriptionManager subscriptionManager,
StripeManager stripeManager,
BraintreeManager braintreeManager,
GooglePlayBillingManager googlePlayBillingManager,
AppleAppStoreManager appleAppStoreManager,
BadgeTranslator badgeTranslator,
BankMandateTranslator bankMandateTranslator,
DonationPermitsManager donationPermitsManager,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.subscriptionManager = subscriptionManager;
this.clock = Objects.requireNonNull(clock);
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
@@ -136,7 +143,8 @@ public class SubscriptionController {
this.appleAppStoreManager = appleAppStoreManager;
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.donationPermitsManager = donationPermitsManager;
this.dynamicConfigurationManager = Objects.requireNonNull(dynamicConfigurationManager);
}
@@ -202,15 +210,35 @@ public class SubscriptionController {
period of time will result in the subscription being canceled.
""")
@ApiResponse(responseCode = "200", description = "The subscriber was successfully created or refreshed")
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "subscriberId is malformed")
@ManagedAsync
public Response updateSubscriber(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit. Not required if the subscriber already exists.")
@HeaderParam(HeaderUtils.DONATION_PERMIT)
final Optional<DonationPermitHeader> donationPermitHeader,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
subscriptionManager.updateSubscriber(subscriberCredentials);
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "putSubscriber", userAgent);
final boolean creationPermitted = donationPermitHeader.map(
permitHeader -> {
try {
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
} catch (VerificationFailedException e) {
return false;
}
})
.orElse(true);
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
return Response.ok().build();
}
@@ -226,6 +254,11 @@ public class SubscriptionController {
@RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD)
public CreatePaymentMethodResponse createPaymentMethod(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit")
@HeaderParam(HeaderUtils.DONATION_PERMIT)
final Optional<DonationPermitHeader> donationPermitHeader,
@PathParam("subscriberId") String subscriberId,
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
@@ -243,6 +276,21 @@ public class SubscriptionController {
case UNKNOWN -> throw new BadRequestException("Invalid payment method");
};
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "createPaymentMethod", userAgentString);
final boolean spendSuccessful = donationPermitHeader.map(
permitHeader -> {
try {
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
} catch (VerificationFailedException e) {
return false;
}
})
.orElse(true);
if (!spendSuccessful) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
final String token = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials,
customerAwareSubscriptionPaymentProcessor,
@@ -271,10 +319,7 @@ public class SubscriptionController {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
final Locale locale = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext).stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
final Locale locale = getPayPalLocale(HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext));
final BraintreeManager.PayPalBillingAgreementApprovalDetails billingAgreementApprovalDetails = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials,
@@ -59,8 +59,6 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import org.apache.commons.lang3.Strings;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
@@ -91,7 +89,6 @@ import org.whispersystems.textsecuregcm.registration.MessageTransport;
import org.whispersystems.textsecuregcm.registration.RegistrationFraudException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
import org.whispersystems.textsecuregcm.registration.TransportNotAllowedException;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
@@ -105,7 +102,6 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.telephony.CarrierData;
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
@@ -225,27 +221,13 @@ public class VerificationController {
maybeCarrierData = Optional.empty();
}
final RegistrationServiceSession registrationServiceSession;
try {
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber,
sourceHost,
accountsManager.getByE164(request.number()).isPresent(),
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CancellationException e) {
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException re) {
throw re;
}
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
}
final RegistrationServiceSession registrationServiceSession =
registrationServiceClient.createRegistrationSession(phoneNumber,
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME),
accountsManager.getByE164(request.number()).isPresent(),
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
REGISTRATION_RPC_TIMEOUT);
VerificationSession verificationSession = new VerificationSession(registrationServiceSession.encodedSessionId(),
null,
@@ -654,59 +636,44 @@ public class VerificationController {
clientType,
acceptLanguage.orElse(null),
senderOverride,
REGISTRATION_RPC_TIMEOUT).join();
REGISTRATION_RPC_TIMEOUT);
} catch (final VerificationSessionRateLimitExceededException e) {
throw new ClientErrorException(buildResponseForRateLimitExceeded(verificationSession,
e.getRegistrationSession(),
e.getRetryDuration()));
} catch (final RegistrationServiceException registrationServiceException) {
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> {
final Response response = registrationServiceException instanceof TransportNotAllowedException
? Response.status(418).entity(verificationSessionResponse).build()
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
} catch (final NotPushRegisteredException _) {
}
});
} catch (final CancellationException e) {
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
switch (unwrappedException) {
case RateLimitExceededException rateLimitExceededException -> {
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
final Response response = buildResponseForRateLimitExceeded(verificationSession,
ve.getRegistrationSession(),
ve.getRetryDuration());
throw new ClientErrorException(response);
}
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
}
case RegistrationServiceException registrationServiceException ->
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> {
final Response response = registrationServiceException instanceof TransportNotAllowedException
? Response.status(418).entity(verificationSessionResponse).build()
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
return new ClientErrorException(response);
})
.orElseGet(NotFoundException::new);
case RegistrationFraudException _ -> {
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
.squashDeclinedAttemptErrors()) {
return buildResponse(registrationServiceSession, verificationSession);
} else {
throw unwrappedException.getCause();
}
}
case RegistrationServiceSenderException _ -> throw unwrappedException;
case null, default -> {
logger.error("Registration service failure", unwrappedException);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
return new ClientErrorException(response);
})
.orElseGet(NotFoundException::new);
} catch (final RegistrationFraudException e) {
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
.squashDeclinedAttemptErrors()) {
return buildResponse(registrationServiceSession, verificationSession);
} else {
throw e.getCause();
}
} catch (final RuntimeException e) {
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
} catch (final NotPushRegisteredException _) {
}
});
Metrics.counter(CODE_REQUESTED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
@@ -746,8 +713,7 @@ public class VerificationController {
schema = @Schema(implementation = Integer.class)))
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest)
throws RateLimitExceededException {
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest) {
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
@@ -764,35 +730,17 @@ public class VerificationController {
try {
resultSession = registrationServiceClient.checkVerificationCode(registrationServiceSession.id(),
submitVerificationCodeRequest.code(),
REGISTRATION_RPC_TIMEOUT)
.join();
} catch (final CancellationException e) {
logger.warn("Unexpected cancellation from registration service", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
if (unwrappedException instanceof RateLimitExceededException rateLimitExceededException) {
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
final Response response = buildResponseForRateLimitExceeded(verificationSession, ve.getRegistrationSession(),
ve.getRetryDuration());
throw new ClientErrorException(response);
}
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
} else if (unwrappedException instanceof RegistrationServiceException registrationServiceException) {
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> new ClientErrorException(
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
.orElseGet(NotFoundException::new);
} else {
logger.error("Registration service failure", unwrappedException);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
REGISTRATION_RPC_TIMEOUT);
} catch (final VerificationSessionRateLimitExceededException e) {
throw new ClientErrorException(buildResponseForRateLimitExceeded(verificationSession,
e.getRegistrationSession(),
e.getRetryDuration()));
} catch (final RegistrationServiceException e) {
throw e.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> new ClientErrorException(
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
.orElseGet(NotFoundException::new);
}
boolean existingRRP = false;
@@ -868,9 +816,8 @@ public class VerificationController {
}
try {
final RegistrationServiceSession registrationServiceSession = registrationServiceClient.getSession(sessionId,
REGISTRATION_RPC_TIMEOUT).join()
.orElseThrow(NotFoundException::new);
final RegistrationServiceSession registrationServiceSession =
registrationServiceClient.getSession(sessionId, REGISTRATION_RPC_TIMEOUT).orElseThrow(NotFoundException::new);
if (registrationServiceSession.verified()) {
// Since there is a valid verification session we invalidate the other possible verification mechanism,
@@ -882,14 +829,16 @@ public class VerificationController {
return registrationServiceSession;
} catch (final CompletionException | CancellationException e) {
final Throwable unwrapped = ExceptionUtils.unwrap(e);
if (unwrapped instanceof StatusRuntimeException grpcRuntimeException) {
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
} catch (final StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
} catch (final WebApplicationException e) {
throw e;
} catch (final RuntimeException e) {
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
@@ -44,11 +43,12 @@ import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
@@ -136,11 +136,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount());
for (final ByteString usernameHash : request.getUsernameHashesList()) {
if (usernameHash.size() != AccountController.USERNAME_HASH_LENGTH) {
throw GrpcExceptions.fieldViolation("username_hashes",
String.format("Username hash length must be %d bytes, but was actually %d",
AccountController.USERNAME_HASH_LENGTH, usernameHash.size()));
}
usernameHashes.add(usernameHash.toByteArray());
}
@@ -277,9 +272,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account authenticatedAccount = getAuthenticatedAccount();
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
final ZkCredentialPublicKey zkCredentialKey;
try {
zkCredentialKey = new ZkCredentialPublicKey(request.getPublicKey().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid public key bytes");
}
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
if (authenticatedAccount.getZkCredentialKey().map(zkCredentialKey::equals).orElse(false)) {
return SetZkCredentialKeyResponse.newBuilder()
.setRotationId(Objects.requireNonNull(authenticatedAccount.getZkCredentialKeyRotationId()))
.build();
@@ -11,6 +11,10 @@ import java.time.Instant;
import java.util.HexFormat;
import java.util.Map;
import java.util.stream.IntStream;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.attachments.GetStickerUploadFormRequest;
import org.signal.chat.attachments.GetStickerUploadFormResponse;
import org.signal.chat.attachments.GetUploadFormRequest;
@@ -25,11 +29,14 @@ import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.controllers.StickerController;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
@@ -49,6 +56,9 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
private static final String ATTACHMENT_SIZE_NAME =
MetricsUtil.name(AttachmentsGrpcService.class, "attachmentSize");
public AttachmentsGrpcService(
final ExperimentEnrollmentManager experimentEnrollmentManager,
final RateLimiters rateLimiters,
@@ -89,6 +99,11 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
throw e;
}
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.register(Metrics.globalRegistry)
.record(request.getUploadLength());
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(),
AttachmentUtil.CDN3_EXPERIMENT_NAME);
@@ -1,8 +1,11 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.time.Instant;
import org.signal.chat.donations.CreateDonationPermitRequest;
import org.signal.chat.donations.CreateDonationPermitResponse;
import org.signal.chat.donations.RedeemReceiptRequest;
import org.signal.chat.donations.RedeemReceiptResponse;
import org.signal.chat.donations.SimpleDonationsGrpc;
@@ -10,6 +13,8 @@ import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
@@ -18,8 +23,10 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
@@ -31,6 +38,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
private final AccountsManager accountsManager;
private final BadgesConfiguration badgesConfiguration;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private final DonationPermitsManager donationPermitsManager;
private final RateLimiters rateLimiters;
private static final Logger LOGGER = LoggerFactory.getLogger(DonationsGrpcService.class);
@@ -40,7 +49,9 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
final RedeemedReceiptsManager redeemedReceiptsManager,
final AccountsManager accountsManager,
final BadgesConfiguration badgesConfiguration,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) {
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
final DonationPermitsManager donationPermitsManager,
final RateLimiters rateLimiters) {
this.clock = clock;
this.serverZkReceiptOperations = serverZkReceiptOperations;
@@ -48,6 +59,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
this.accountsManager = accountsManager;
this.badgesConfiguration = badgesConfiguration;
this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory;
this.donationPermitsManager = donationPermitsManager;
this.rateLimiters = rateLimiters;
}
@Override
@@ -101,4 +114,23 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
.build();
}
}
@Override
public CreateDonationPermitResponse createDonationPermit(final CreateDonationPermitRequest request) throws Exception {
final DonationPermitRequest permitRequest;
try {
permitRequest = new DonationPermitRequest(request.getDonationPermitRequest().toByteArray());
} catch (InvalidInputException e) {
throw GrpcExceptions.invalidArguments("invalid permit request");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiters.getCreateDonationPermitLimiter().validate(authenticatedDevice.accountIdentifier(), permitRequest.getPermitCount());
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
return CreateDonationPermitResponse.newBuilder()
.setDonationPermitResponse(ByteString.copyFrom(permitResponse.serialize()))
.build();
}
}
@@ -15,8 +15,10 @@ import org.signal.keytransparency.client.E164MonitorRequest;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.MonitorRequest;
import org.signal.keytransparency.client.MonitorResponse;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchRequest;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.SimpleKeyTransparencyQueryServiceGrpc;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.whispersystems.textsecuregcm.controllers.AccountController;
@@ -39,102 +41,51 @@ public class KeyTransparencyGrpcService extends
}
@Override
public SearchResponse search(final SearchRequest request) throws RateLimitExceededException {
public SearchResponseV2 searchV2(final SearchRequest request) throws RateLimitExceededException {
rateLimiters.getKeyTransparencySearchLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
return client.search(validateSearchRequest(request));
}
@Override
public MonitorResponse monitor(final MonitorRequest request) throws RateLimitExceededException {
public MonitorResponseV2 monitorV2(final MonitorRequest request) throws RateLimitExceededException {
rateLimiters.getKeyTransparencyMonitorLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
return client.monitor(validateMonitorRequest(request));
}
@Override
public DistinguishedResponse distinguished(final DistinguishedRequest request) throws RateLimitExceededException {
public DistinguishedResponse distinguishedV2(final DistinguishedRequest request) throws RateLimitExceededException {
rateLimiters.getKeyTransparencyDistinguishedLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
// A client's very first distinguished request will not have a "last" parameter
if (request.hasLast() && request.getLast() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Last tree head size must be positive").asRuntimeException();
}
return client.distinguished(request);
}
private SearchRequest validateSearchRequest(final SearchRequest request) {
validateAci(request.getAci().toByteArray());
if (request.hasE164SearchRequest()) {
final E164SearchRequest e164SearchRequest = request.getE164SearchRequest();
if (e164SearchRequest.getUnidentifiedAccessKey().isEmpty() != e164SearchRequest.getE164().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Unidentified access key and E164 must be provided together or not at all").asRuntimeException();
throw GrpcExceptions.fieldViolation("e164_search_request", "Unidentified access key and E164 must be provided together or not at all");
}
}
if (!request.getConsistency().hasDistinguished()) {
throw Status.INVALID_ARGUMENT.withDescription("Must provide distinguished tree head size").asRuntimeException();
}
validateConsistencyParameters(request.getConsistency());
return request;
}
private void validateAci(final byte[] aci) {
try {
AciServiceIdentifier.fromBytes(aci);
} catch (IllegalArgumentException e) {
throw GrpcExceptions.fieldViolation("aci", "Invalid ACI");
}
}
private MonitorRequest validateMonitorRequest(final MonitorRequest request) {
final AciMonitorRequest aciMonitorRequest = request.getAci();
validateAci(request.getAci().getAci().toByteArray());
try {
AciServiceIdentifier.fromBytes(aciMonitorRequest.getAci().toByteArray());
} catch (IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid ACI").asRuntimeException();
}
if (aciMonitorRequest.getEntryPosition() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Aci entry position must be positive").asRuntimeException();
}
if (aciMonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Aci commitment index must be 32 bytes").asRuntimeException();
if (!request.getConsistency().hasLast()) {
throw GrpcExceptions.fieldViolation("consistency_last", "Must provide distinguished and last tree head sizes");
}
if (request.hasUsernameHash()) {
final UsernameHashMonitorRequest usernameHashMonitorRequest = request.getUsernameHash();
if (usernameHashMonitorRequest.getUsernameHash().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Username hash cannot be empty").asRuntimeException();
}
if (usernameHashMonitorRequest.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid username hash length").asRuntimeException();
}
if (usernameHashMonitorRequest.getEntryPosition() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Username hash entry position must be positive").asRuntimeException();
}
if (usernameHashMonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Username hash commitment index must be 32 bytes").asRuntimeException();
}
}
if (request.hasE164()) {
final E164MonitorRequest e164MonitorRequest = request.getE164();
if (e164MonitorRequest.getE164().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("E164 cannot be empty").asRuntimeException();
}
if (e164MonitorRequest.getEntryPosition() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("E164 entry position must be positive").asRuntimeException();
}
if (e164MonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("E164 commitment index must be 32 bytes").asRuntimeException();
}
}
if (!request.getConsistency().hasDistinguished() || !request.getConsistency().hasLast()) {
throw Status.INVALID_ARGUMENT.withDescription("Must provide distinguished and last tree head sizes").asRuntimeException();
}
validateConsistencyParameters(request.getConsistency());
return request;
}
private static void validateConsistencyParameters(final ConsistencyParameters consistency) {
if (consistency.getDistinguished() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Distinguished tree head size must be positive").asRuntimeException();
}
if (consistency.hasLast() && consistency.getLast() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Last tree head size must be positive").asRuntimeException();
}
}
}
@@ -0,0 +1,130 @@
package org.whispersystems.textsecuregcm.grpc;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
public class OneTimeDonationUtil {
private static final String EURO_CURRENCY_CODE = "EUR";
private static final Logger LOGGER = LoggerFactory.getLogger(OneTimeDonationUtil.class);
/// Thrown if a one time donation level cannot be parsed or if it is not found in configuration
public static class InvalidLevelException extends Exception {
public InvalidLevelException(final String message) {
super(message);
}
}
public record LocalizedPayPalDonationLineItem(Locale locale, String itemName){}
public record DonationLevelDetails(long level, Duration levelExpiration){}
public sealed interface OneTimeDonationRequestValidationResult permits OneTimeDonationRequestValidationResult.Success,
OneTimeDonationRequestValidationResult.UnsupportedCurrency,
OneTimeDonationRequestValidationResult.UnsupportedLevel,
OneTimeDonationRequestValidationResult.AmountBelowMinimum,
OneTimeDonationRequestValidationResult.AmountAboveSepaLimit {
record Success() implements OneTimeDonationRequestValidationResult {}
record UnsupportedCurrency() implements OneTimeDonationRequestValidationResult {}
record UnsupportedLevel() implements OneTimeDonationRequestValidationResult {}
record AmountBelowMinimum(BigDecimal minimum) implements OneTimeDonationRequestValidationResult {}
record AmountAboveSepaLimit(BigDecimal maximum) implements OneTimeDonationRequestValidationResult {}
}
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
final String currency,
final BigDecimal amount,
final long level,
final PaymentMethod paymentMethod,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final CustomerAwareSubscriptionPaymentProcessor manager
) {
if (!(level == oneTimeDonationConfiguration.gift().level()
|| level == oneTimeDonationConfiguration.boost().level())) {
return new OneTimeDonationRequestValidationResult.UnsupportedLevel();
}
if (!manager.getSupportedCurrenciesForPaymentMethod(paymentMethod)
.contains(currency.toLowerCase(Locale.ROOT))) {
return new OneTimeDonationRequestValidationResult.UnsupportedCurrency();
}
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
.get(currency.toLowerCase(Locale.ROOT)).minimum();
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
currency,
minCurrencyAmountMajorUnits);
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
return new OneTimeDonationRequestValidationResult.AmountBelowMinimum(minCurrencyAmountMajorUnits);
}
if (paymentMethod == PaymentMethod.SEPA_DEBIT &&
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
EURO_CURRENCY_CODE,
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
return new OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(
oneTimeDonationConfiguration.sepaMaximumEuros());
}
return new OneTimeDonationRequestValidationResult.Success();
}
public static LocalizedPayPalDonationLineItem localizePayPalDonationLineItem(
final PayPalDonationsTranslator payPalDonationsTranslator, final List<Locale> acceptableLocales) {
// These two localizations are a best-effort, and it's possible that the first `locale` and the localized line
// item name will not match. We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
// but that's a moving target, and we can hopefully have one of them be better for the user by selecting
// independently.
final Locale locale = SubscriptionsUtil.getPayPalLocale(acceptableLocales);
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLocales,
org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
return new LocalizedPayPalDonationLineItem(locale, localizedLineItemName);
}
public static DonationLevelDetails getLevelDetails(final PaymentDetails paymentDetails,
final OneTimeDonationConfiguration oneTimeDonationConfiguration)
throws InvalidLevelException {
long level = oneTimeDonationConfiguration.boost().level();
if (paymentDetails.customMetadata() != null) {
final String levelMetadata = paymentDetails.customMetadata()
.getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level()));
try {
level = Long.parseLong(levelMetadata);
} catch (final NumberFormatException e) {
LOGGER.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata,
paymentDetails.id(), e);
throw new InvalidLevelException("failed to parse level metadata");
}
}
final Duration levelExpiration;
if (level == oneTimeDonationConfiguration.boost().level()) {
levelExpiration = oneTimeDonationConfiguration.boost().expiration();
} else if (level == oneTimeDonationConfiguration.gift().level()) {
levelExpiration = oneTimeDonationConfiguration.gift().expiration();
} else {
LOGGER.error("level ({}) returned from payment intent that is unknown to the server", level);
throw new InvalidLevelException("unrecognized level");
}
return new DonationLevelDetails(level, levelExpiration);
}
}
@@ -0,0 +1,326 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure;
import com.google.protobuf.ByteString;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.one_time_donations.AmountAboveSepaLimitError;
import org.signal.chat.one_time_donations.AmountBelowMinimumError;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostRequest;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostResponse;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsRequest;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsResponse;
import org.signal.chat.one_time_donations.CreateBoostRequest;
import org.signal.chat.one_time_donations.CreateBoostResponse;
import org.signal.chat.one_time_donations.CreatePayPalBoostRequest;
import org.signal.chat.one_time_donations.CreatePayPalBoostResponse;
import org.signal.chat.one_time_donations.SimpleOneTimeDonationsGrpc;
import org.signal.chat.subscriptions.PaymentRequired;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase {
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
private final PayPalDonationsTranslator payPalDonationsTranslator;
private final OneTimeDonationsManager oneTimeDonationsManager;
private final IssuedReceiptsManager issuedReceiptsManager;
private final ServerZkReceiptOperations zkReceiptOperations;
private final Clock clock;
private final RateLimiters rateLimiters;
private final DonationPermitsManager donationPermitsManager;
public OneTimeDonationsGrpcService(
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final StripeManager stripeManager,
final BraintreeManager braintreeManager,
final PayPalDonationsTranslator payPalDonationsTranslator,
final OneTimeDonationsManager oneTimeDonationsManager,
final IssuedReceiptsManager issuedReceiptsManager,
final ServerZkReceiptOperations zkReceiptOperations,
final Clock clock,
final RateLimiters rateLimiters,
final DonationPermitsManager donationPermitsManager) {
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
this.stripeManager = stripeManager;
this.braintreeManager = braintreeManager;
this.payPalDonationsTranslator = payPalDonationsTranslator;
this.oneTimeDonationsManager = oneTimeDonationsManager;
this.issuedReceiptsManager = issuedReceiptsManager;
this.zkReceiptOperations = zkReceiptOperations;
this.clock = clock;
this.rateLimiters = rateLimiters;
this.donationPermitsManager = donationPermitsManager;
}
@Override
public CreateBoostResponse createBoost(final CreateBoostRequest request) throws RateLimitExceededException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
try {
final DonationPermit donationPermit = new DonationPermit(request.getDonationPermit().toByteArray());
if (!donationPermitsManager.spend(donationPermit)) {
return CreateBoostResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit rejected")
.build())
.build();
}
} catch (InvalidInputException | VerificationFailedException _) {
return CreateBoostResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit rejected")
.build())
.build();
}
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod =
switch (request.getPaymentMethod()) {
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD;
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT;
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL;
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
};
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getLevel(),
paymentMethod,
oneTimeDonationConfiguration,
stripeManager);
return switch (validationResult) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
CreateBoostResponse.newBuilder()
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
CreateBoostResponse.newBuilder()
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
CreateBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit r ->
CreateBoostResponse.newBuilder()
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
.setMaximum(r.maximum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
}
};
}
@Override
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) {
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getLevel(),
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
oneTimeDonationConfiguration,
braintreeManager);
return switch (validationResult) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
CreatePayPalBoostResponse.newBuilder()
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
CreatePayPalBoostResponse.newBuilder()
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
CreatePayPalBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final List<Locale> acceptableLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
payPalDonationsTranslator, acceptableLocales);
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
braintreeManager.createOneTimePayment(
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
localizedLineItem.itemName()).join();
yield CreatePayPalBoostResponse.newBuilder()
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
.setApprovalUrl(approvalDetails.approvalUrl())
.setPaymentId(approvalDetails.paymentId()).build()).build();
}
};
}
@Override
public ConfirmPayPalBoostResponse confirmPayPalBoost(final ConfirmPayPalBoostRequest request)
throws RateLimitExceededException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getLevel(),
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
oneTimeDonationConfiguration,
braintreeManager);
return switch (validationResult) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
ConfirmPayPalBoostResponse.newBuilder()
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
ConfirmPayPalBoostResponse.newBuilder()
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
ConfirmPayPalBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails =
braintreeManager.captureOneTimePayment(
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant());
yield ConfirmPayPalBoostResponse.newBuilder()
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
}
};
}
@Override
public CreateBoostReceiptCredentialsResponse createBoostReceiptCredentials(
final CreateBoostReceiptCredentialsRequest request) {
final PaymentProvider processor;
final Optional<PaymentDetails> maybePaymentDetails;
switch (request.getProcessor()) {
case PAYMENT_PROVIDER_STRIPE -> {
processor = PaymentProvider.STRIPE;
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId()).join();
}
case PAYMENT_PROVIDER_BRAINTREE -> {
processor = PaymentProvider.BRAINTREE;
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId()).join();
}
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
}
if (maybePaymentDetails.isEmpty()) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setPaymentNotFound(NotFound.getDefaultInstance()).build();
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance()).build();
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
final PaymentRequired.Builder paymentRequiredBuilder = PaymentRequired.newBuilder();
if (paymentDetails.chargeFailure() != null) {
paymentRequiredBuilder.setChargeFailure(toChargeFailure(processor, paymentDetails.chargeFailure()));
}
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setPaymentRequired(paymentRequiredBuilder).build();
}
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
try {
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
} catch (final OneTimeDonationUtil.InvalidLevelException e) {
throw GrpcExceptions.unavailable(e.getMessage());
}
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(
request.getReceiptCredentialRequest().toByteArray());
} catch (final InvalidInputException e) {
throw GrpcExceptions.fieldViolation("receipt_credential_request", "invalid receipt credential request");
}
try {
issuedReceiptsManager.recordIssuance(
paymentDetails.id(), processor, receiptCredentialRequest, clock.instant());
} catch (final WriteConflictException e) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance()).build();
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
} catch (final VerificationFailedException e) {
throw GrpcExceptions.fieldViolation("receipt_credential_request",
"receipt credential request failed verification");
}
Metrics.counter(SubscriptionsGrpcService.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionsGrpcService.PROCESSOR_TAG_NAME, processor.toString()),
Tag.of(SubscriptionsGrpcService.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.increment();
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setResult(CreateBoostReceiptCredentialsResponse.CreateBoostReceiptCredentialsResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize()))
.build())
.build();
}
}
@@ -5,12 +5,21 @@
package org.whispersystems.textsecuregcm.grpc;
import java.time.Clock;
import java.util.Optional;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Base64;
import java.util.Optional;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.DeleteAvatarRequest;
import org.signal.chat.profile.DeleteAvatarResponse;
import org.signal.chat.profile.ExtendAvatarTTLRequest;
import org.signal.chat.profile.ExtendAvatarTTLResponse;
import org.signal.chat.profile.GetAvatarUploadFormRequest;
import org.signal.chat.profile.GetAvatarUploadFormResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
@@ -18,44 +27,75 @@ import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.ProfileAnonymousImplBase {
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final ProfileBadgeConverter profileBadgeConverter;
private final ServerZkProfileOperations zkProfileOperations;
private final GenericServerSecretParams genericServerSecretParams;
private final GroupSendTokenUtil groupSendTokenUtil;
private final PostPolicyGenerator policyGenerator;
private final RateLimiters rateLimiters;
private final Clock clock;
public ProfileAnonymousGrpcService(
final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerSecretParams serverSecretParams) {
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final ServerSecretParams serverSecretParams,
final RateLimiters rateLimiters,
final Clock clock) {
this(accountsManager,
profilesManager,
profileBadgeConverter,
policyGenerator,
genericServerSecretParams,
rateLimiters,
clock,
new ServerZkProfileOperations(serverSecretParams),
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
new GroupSendTokenUtil(serverSecretParams, clock));
}
@VisibleForTesting
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final RateLimiters rateLimiters,
final Clock clock,
final ServerZkProfileOperations zkProfileOperations,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.profileBadgeConverter = profileBadgeConverter;
this.policyGenerator = policyGenerator;
this.genericServerSecretParams = genericServerSecretParams;
this.rateLimiters = rateLimiters;
this.clock = clock;
this.zkProfileOperations = zkProfileOperations;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@@ -152,4 +192,92 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
}
@Override
public GetAvatarUploadFormResponse getAvatarUploadForm(final GetAvatarUploadFormRequest request) throws RateLimitExceededException {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
} catch (VerificationFailedException _) {
return GetAvatarUploadFormResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
rateLimiters.getProfileAvatarBytesLimiter().validate(Base64.getEncoder().encodeToString(identity), request.getUploadLength());
final String avatar = ProfileHelper.generateAvatarObjectName();
profilesManager.setAvatarForIdentity(identity, avatar);
return GetAvatarUploadFormResponse.newBuilder()
.setAvatarUploadForm(ProfileGrpcHelper.generateAvatarUploadForm(avatar, request.getUploadLength(), policyGenerator, clock))
.build();
}
@Override
public ExtendAvatarTTLResponse extendAvatarTTL(final ExtendAvatarTTLRequest request) {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
try {
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (VerificationFailedException _) {
return ExtendAvatarTTLResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
return profilesManager.extendAvatarTtlForIdentity(identity)
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
.setPath(extendedPath)
.build())
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public DeleteAvatarResponse deleteAvatar(final DeleteAvatarRequest request) {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
try {
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (VerificationFailedException _) {
return DeleteAvatarResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
profilesManager.deleteAvatarForIdentity(identity);
return DeleteAvatarResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
}
@@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
@@ -17,6 +18,7 @@ import java.util.Optional;
import java.util.UUID;
import org.signal.chat.common.Badge;
import org.signal.chat.common.BadgeSvg;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
@@ -32,6 +34,7 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
@@ -40,6 +43,12 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcHelper {
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
final ProfilesManager profilesManager,
final byte[] requestVersion,
@@ -217,6 +226,20 @@ public class ProfileGrpcHelper {
});
}
public static S3UploadForm generateAvatarUploadForm(final String objectName, final int uploadLength,
final PostPolicyGenerator policyGenerator, final Clock clock) {
final PostPolicyGenerator.SignedPostPolicy policy =
policyGenerator.createFor(objectName, uploadLength, clock.instant());
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
.setKey(objectName)
.setCredential(policy.credential())
.setDate(policy.formattedTimestamp())
.setPolicy(policy.encodedPolicy())
.setSignature(policy.signature())
.build();
}
/**
* Computes the SHA-256 hash of the given data.
* <p>
@@ -5,11 +5,14 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
@@ -17,6 +20,8 @@ import java.util.stream.Collectors;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.GetAvatarCredentialsRequest;
import org.signal.chat.profile.GetAvatarCredentialsResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
@@ -28,6 +33,14 @@ import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
import org.signal.chat.profile.SimpleProfileGrpc;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -52,20 +65,18 @@ import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private static final Logger logger = LoggerFactory.getLogger(ProfileGrpcService.class);
private final Clock clock;
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
private final PostPolicyGenerator policyGenerator;
private final GenericServerSecretParams genericServerSecretParams;
private final ProfileBadgeConverter profileBadgeConverter;
private final RateLimiters rateLimiters;
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
private record AvatarData(Optional<String> currentAvatar,
Optional<String> finalAvatar,
Optional<S3UploadForm> uploadAttributes) {}
@@ -77,6 +88,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters) {
this.clock = clock;
@@ -86,6 +98,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
BadgeConfiguration::getId, Function.identity()));
this.policyGenerator = policyGenerator;
this.genericServerSecretParams = genericServerSecretParams;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
}
@@ -136,7 +149,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
case AVATAR_CHANGE_UPDATE -> {
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
Optional.of(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, policyGenerator, clock)));
}
};
@@ -205,6 +218,39 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
.build());
}
@Override
public GetAvatarCredentialsResponse getAvatarCredentials(final GetAvatarCredentialsRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
if (account.getZkCredentialKey().isEmpty()) {
return GetAvatarCredentialsResponse.newBuilder()
.setMissingZkCredentialKey(FailedPrecondition.newBuilder().setDescription("account requires ZK credential key"))
.build();
}
try {
final AvatarUploadCredentialRequest credentialRequest = new AvatarUploadCredentialRequest(
request.getAvatarCredentialsRequest().toByteArray());
final AvatarUploadCredentialResponse credentialResponse = credentialRequest.issueCredential(
new ServiceId.Aci(account.getIdentifier(IdentityType.ACI)),
account.getZkCredentialKey().get(),
Objects.requireNonNull(account.getZkCredentialKeyRotationId()),
clock.instant().truncatedTo(ChronoUnit.DAYS),
this.genericServerSecretParams);
return GetAvatarCredentialsResponse.newBuilder()
.setAvatarCredentials(ByteString.copyFrom(credentialResponse.serialize()))
.build();
} catch (InvalidInputException | VerificationFailedException _) {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@@ -263,17 +309,4 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
throw GrpcExceptions.invalidArguments("Request must include commitment during migration");
}
}
private S3UploadForm generateAvatarUploadForm(final String objectName) {
final PostPolicyGenerator.SignedPostPolicy policy =
policyGenerator.createFor(objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, clock.instant());
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
.setKey(objectName)
.setCredential(policy.credential())
.setDate(policy.formattedTimestamp())
.setPolicy(policy.encodedPolicy())
.setSignature(policy.signature())
.build();
}
}
@@ -1,6 +1,7 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalLocale;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
@@ -11,8 +12,12 @@ import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse;
@@ -29,6 +34,7 @@ import org.signal.chat.subscriptions.GetReceiptCredentialsResponse;
import org.signal.chat.subscriptions.GetSubscriptionInformationRequest;
import org.signal.chat.subscriptions.GetSubscriptionInformationResponse;
import org.signal.chat.subscriptions.PaymentMethod;
import org.signal.chat.subscriptions.PaymentRequired;
import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest;
import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse;
import org.signal.chat.subscriptions.SetIapSubscriptionRequest;
@@ -38,6 +44,9 @@ import org.signal.chat.subscriptions.SetSubscriptionLevelResponse;
import org.signal.chat.subscriptions.SimpleSubscriptionsGrpc;
import org.signal.chat.subscriptions.UpdateSubscriberRequest;
import org.signal.chat.subscriptions.UpdateSubscriberResponse;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
@@ -46,6 +55,9 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
@@ -54,13 +66,12 @@ import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
@@ -82,6 +93,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final SubscriptionManager subscriptionManager;
private final DonationPermitsManager donationPermitsManager;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
private final GooglePlayBillingManager googlePlayBillingManager;
@@ -90,16 +102,23 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
private final BankMandateTranslator bankMandateTranslator;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionsGrpcService.class, "receiptIssued");
static final String PROCESSOR_TAG_NAME = "processor";
static final String TYPE_TAG_NAME = "type";
private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType";
public SubscriptionsGrpcService(final Clock clock, final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration, final SubscriptionManager subscriptionManager,
final StripeManager stripeManager, final BraintreeManager braintreeManager,
final GooglePlayBillingManager googlePlayBillingManager, final AppleAppStoreManager appleAppStoreManager,
final BadgeTranslator badgeTranslator, final BankMandateTranslator bankMandateTranslator,
final DonationPermitsManager donationPermitsManager, final StripeManager stripeManager,
final BraintreeManager braintreeManager, final GooglePlayBillingManager googlePlayBillingManager,
final AppleAppStoreManager appleAppStoreManager, final BadgeTranslator badgeTranslator,
final BankMandateTranslator bankMandateTranslator,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.clock = clock;
this.subscriptionConfiguration = subscriptionConfiguration;
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
this.subscriptionManager = subscriptionManager;
this.donationPermitsManager = donationPermitsManager;
this.stripeManager = stripeManager;
this.braintreeManager = braintreeManager;
this.googlePlayBillingManager = googlePlayBillingManager;
@@ -115,11 +134,41 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
try {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
subscriptionManager.updateSubscriber(subscriberCredentials);
final boolean creationPermitted;
try {
if (request.getDonationPermit().isEmpty()) {
creationPermitted = false;
} else {
final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray());
creationPermitted = SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock);
}
} catch (final InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid donation permit");
} catch (final VerificationFailedException _) {
return UpdateSubscriberResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit failed verification")
.build())
.build();
}
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionForbiddenException e) {
return UpdateSubscriberResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (SubscriberIdCreationNotPermittedException _) {
if (request.getDonationPermit().isEmpty()) {
throw GrpcExceptions.invalidArguments("donation permit is required to create a subscriber ID");
}
return UpdateSubscriberResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit was not valid")
.build())
.build();
}
}
@@ -144,12 +193,27 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
public CreatePaymentMethodResponse createPaymentMethod(final CreatePaymentMethodRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final PaymentMethod paymentMethod;
final CustomerAwareSubscriptionPaymentProcessor customerAwareSubscriptionPaymentProcessor = switch (request.getPaymentMethod()) {
case PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, PAYMENT_METHOD_IDEAL -> stripeManager;
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
};
try {
final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray());
if (!SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock)) {
return CreatePaymentMethodResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
.build();
}
} catch (final InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid donation permit");
} catch (final VerificationFailedException _) {
return CreatePaymentMethodResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
.build();
}
try {
final String token = subscriptionManager.addPaymentMethodToCustomer(subscriberCredentials,
customerAwareSubscriptionPaymentProcessor,
@@ -173,12 +237,11 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final Locale locale = RequestAttributesUtil.getAcceptableLanguages().stream().filter(r -> !"*".equals(r.getRange()))
.findFirst().map(r -> Locale.forLanguageTag(r.getRange())).orElse(Locale.US);
final Locale locale = getPayPalLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
try {
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
(mgr, customerId) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
locale.toLanguageTag())).join();
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
@@ -309,7 +372,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
.build();
} catch (final SubscriptionProcessorException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setChargeFailure(toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
} catch (final SubscriptionPaymentRequiresActionException e) {
return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build())
.build();
@@ -389,7 +452,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond());
}
if (info.chargeFailure() != null) {
subscription.setChargeFailure(toChargeFailure(info.paymentProvider(), info.chargeFailure()));
subscription.setChargeFailure(SubscriptionsUtil.toChargeFailure(info.paymentProvider(), info.chargeFailure()));
}
return GetSubscriptionInformationResponse.newBuilder().setSuccess(subscription.build()).build();
@@ -404,6 +467,15 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
final SubscriptionManager.ReceiptResult result = subscriptionManager.createReceiptCredentials(
subscriberCredentials, request.getReceiptCredentialRequest().toByteArray(),
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(PROCESSOR_TAG_NAME, result.paymentProvider().toString()),
Tag.of(TYPE_TAG_NAME, "subscription"),
Tag.of(SUBSCRIPTION_TYPE_TAG_NAME,
subscriptionConfiguration.getSubscriptionLevel(result.receiptItem().level()).type().name()
.toLowerCase(Locale.ROOT)),
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.increment();
return GetReceiptCredentialsResponse.newBuilder().setSuccess(
GetReceiptCredentialsResponse.GetReceiptCredentialsResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize()))
@@ -413,11 +485,11 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
.build();
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder().setPaymentRequired(
GetReceiptCredentialsResponse.PaymentRequired.newBuilder()
.setChargeFailure(toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build();
PaymentRequired.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build();
} catch (final SubscriptionPaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder()
.setPaymentRequired(GetReceiptCredentialsResponse.PaymentRequired.newBuilder().build()).build();
.setPaymentRequired(PaymentRequired.newBuilder().build()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
@@ -535,20 +607,4 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
return GetBankMandateResponse.newBuilder().setMandate(mandate).build();
}
private static org.signal.chat.subscriptions.ChargeFailure toChargeFailure(final PaymentProvider processor,
final ChargeFailure chargeFailure) {
final org.signal.chat.subscriptions.ChargeFailure.Builder builder = org.signal.chat.subscriptions.ChargeFailure.newBuilder()
.setProcessor(processor.toProto()).setCode(chargeFailure.code()).setMessage(chargeFailure.message());
if (chargeFailure.outcomeNetworkStatus() != null) {
builder.setOutcomeNetworkStatus(chargeFailure.outcomeNetworkStatus());
}
if (chargeFailure.outcomeReason() != null) {
builder.setOutcomeReason(chargeFailure.outcomeReason());
}
if (chargeFailure.outcomeType() != null) {
builder.setOutcomeType(chargeFailure.outcomeType());
}
return builder.build();
}
}
@@ -1,9 +1,11 @@
package org.whispersystems.textsecuregcm.grpc;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@@ -11,6 +13,8 @@ import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
@@ -18,15 +22,27 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
public class SubscriptionsUtil {
private static final String DONATION_PERMIT_PRESENT_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class,
"donationPermitPresent");
private static final String DONATION_PERMIT_SPEND_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class,
"donationPermitSpend");
@Nullable
public static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
try {
@@ -124,4 +140,48 @@ public class SubscriptionsUtil {
oneTimeDonationConfiguration.gift().expiration())));
return donationLevels;
}
/// Verifies the permit and spends it
///
/// @return `true` if the spend was accepted, otherwise `false`
/// @throws VerificationFailedException if the permit is invalid
public static boolean verifyAndSpendDonationPermit(final DonationPermit permit, final DonationPermitsManager donationPermitsManager, final Clock clock) throws VerificationFailedException {
final boolean spent = donationPermitsManager.spend(permit);
Metrics.counter(DONATION_PERMIT_SPEND_COUNTER_NAME, "outcome", spent ? "success" : "failure").increment();
return spent;
}
public static void recordDonationPermitPresent(final boolean present, final String context, final String userAgent) {
Metrics.counter(DONATION_PERMIT_PRESENT_COUNTER_NAME,
Tags.of("present", String.valueOf(present),
"context", context)
.and(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
}
public static org.signal.chat.subscriptions.ChargeFailure toChargeFailure(final PaymentProvider processor,
final ChargeFailure chargeFailure) {
final org.signal.chat.subscriptions.ChargeFailure.Builder builder = org.signal.chat.subscriptions.ChargeFailure.newBuilder()
.setProcessor(processor.toProto()).setCode(chargeFailure.code()).setMessage(chargeFailure.message());
if (chargeFailure.outcomeNetworkStatus() != null) {
builder.setOutcomeNetworkStatus(chargeFailure.outcomeNetworkStatus());
}
if (chargeFailure.outcomeReason() != null) {
builder.setOutcomeReason(chargeFailure.outcomeReason());
}
if (chargeFailure.outcomeType() != null) {
builder.setOutcomeType(chargeFailure.outcomeType());
}
return builder.build();
}
public static Locale getPayPalLocale(final List<Locale> acceptableLocales) {
return acceptableLocales.stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
}
}
@@ -12,17 +12,19 @@ import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.util.List;
import java.util.Map;
import org.signal.chat.require.ElementConstraint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.validators.Base64UrlFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.ExactlySizeFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidationException;
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.NonEmptyFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.PresentFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.RangeFieldValidator;
@@ -32,17 +34,22 @@ import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
public class ValidatingInterceptor implements ServerInterceptor {
private static final Logger log = LoggerFactory.getLogger(ValidatingInterceptor.class);
private final Map<String, FieldValidator> fieldValidators = Map.of(
"org.signal.chat.require.nonEmpty", new NonEmptyFieldValidator(),
"org.signal.chat.require.present", new PresentFieldValidator(),
"org.signal.chat.require.specified", new EnumSpecifiedFieldValidator(),
"org.signal.chat.require.e164", new E164FieldValidator(),
"org.signal.chat.require.exactlySize", new ExactlySizeFieldValidator(),
"org.signal.chat.require.range", new RangeFieldValidator(),
"org.signal.chat.require.size", new SizeFieldValidator(),
"org.signal.chat.require.base64url", new Base64UrlFieldValidator(),
"org.signal.chat.require.identityType", new ServiceIdentifierIdentityTypeValidator()
);
private static final String REQUIRE_PATH = "org.signal.chat.require.";
private static final String EACH_PATH = "org.signal.chat.require.each";
// The keys in this map correspond to the names of our custom FieldOptions as well as the names in the fields of
// `ElementConstraint` which itself is the value of the `each` FieldOption. For this reason it's a good idea to make
// the names match when they refer to the same validator.
private final static Map<String, FieldValidator<?>> VALIDATORS = Map.of(
"nonEmpty", new NonEmptyFieldValidator(),
"specified", new EnumSpecifiedFieldValidator(),
"e164", new E164FieldValidator(),
"exactlySize", new ExactlySizeFieldValidator(),
"range", new RangeFieldValidator(),
"size", new SizeFieldValidator(),
"base64url", new Base64UrlFieldValidator(),
"identityType", new ServiceIdentifierIdentityTypeValidator(),
"present", new PresentFieldValidator());
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
@@ -67,13 +74,13 @@ public class ValidatingInterceptor implements ServerInterceptor {
validateMessage(message);
super.onMessage(message);
} catch (RuntimeException runtimeException) {
final StatusRuntimeException grpcException = switch (runtimeException) {
case StatusRuntimeException e -> e;
default -> {
log.error("Failure applying request validation to message {}", call.getMethodDescriptor().getFullMethodName(), runtimeException);
yield GrpcExceptions.unavailable("failure applying request validation");
}
};
final StatusRuntimeException grpcException = runtimeException instanceof StatusRuntimeException sre
? sre
: GrpcExceptions.unavailable("failure applying request validation");
if (grpcException.getStatus().getCode() != Status.Code.INVALID_ARGUMENT) {
log.error("Failure applying request validation to message {}",
call.getMethodDescriptor().getFullMethodName(), runtimeException);
}
call.close(grpcException.getStatus(), grpcException.getTrailers());
forwardCalls = false;
}
@@ -89,45 +96,95 @@ public class ValidatingInterceptor implements ServerInterceptor {
}
private void validateMessage(final Object message) {
if (message instanceof Message msg) {
for (final Descriptors.FieldDescriptor fd : msg.getDescriptorForType().getFields()) {
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : fd.getOptions().getAllFields().entrySet()) {
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
final String extensionName = extensionFieldDescriptor.getFullName();
if (!(message instanceof Message msg)) {
return;
}
for (final Descriptors.FieldDescriptor fd : msg.getDescriptorForType().getFields()) {
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : fd.getOptions().getAllFields().entrySet()) {
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
// If this is a oneof, but this field isn't set, we shouldn't validate it. We assume if you have a validator
// that requires presence, you don't actually want presence enforcement on a oneof case.
if (fd.getRealContainingOneof() != null && !msg.hasField(fd)) {
continue;
}
// first validate the field
final FieldValidator validator = fieldValidators.get(extensionName);
// not all extensions are validators, so `validator` value here could legitimately be `null`
if (validator != null) {
try {
validator.validate(entry.getValue(), fd, msg);
} catch (FieldValidationException e) {
throw GrpcExceptions.fieldViolation(fd.getName(),
"extension %s: %s".formatted(extensionName, e.getMessage()));
}
if (!extensionFieldDescriptor.getFullName().startsWith(REQUIRE_PATH) || (fd.getRealContainingOneof() != null && !msg.hasField(fd))) {
// Either this is a non-require extension, or this is oneof but this field isn't set. In the latter case
// we assume if you have a validator that requires presence, you don't actually want presence enforcement on
// a oneof. In either case we should just skip this validator.
} else if (extensionFieldDescriptor.getFullName().equals(EACH_PATH)) {
if (!(entry.getValue() instanceof ElementConstraint elementConstraint)) {
throw new IllegalStateException("'each' value must be an ElementConstraint");
}
validateRepeatedElementConstraints(elementConstraint, msg, fd);
} else {
validateField(getValidatorOrThrow(extensionFieldDescriptor), entry.getValue(), msg, fd);
}
}
// Recursively validate the field's value(s) if it is a message or a repeated field
// gRPC's proto deserialization limits nesting to 100 so this has bounded stack usage
if (fd.isRepeated() && msg.getField(fd) instanceof List list) {
// Checking for repeated fields also handles maps, because maps are syntax sugar for repeated MapEntries
// which themselves are Messages that will be recursively descended.
for (final Object o : list) {
validateMessage(o);
}
} else if (fd.hasPresence() && msg.hasField(fd)) {
// If the field has presence information and is present, recursively validate it. Not all fields have
// presence, but we only validate Message type fields anyway, which always have explicit presence.
validateMessage(msg.getField(fd));
// Recursively validate the field's value(s) if it is a message or a repeated field
// gRPC's proto deserialization limits nesting to 100 so this has bounded stack usage
if (fd.isRepeated() && msg.getField(fd) instanceof List list) {
// Checking for repeated fields also handles maps, because maps are syntax sugar for repeated MapEntries
// which themselves are Messages that will be recursively descended.
for (final Object o : list) {
validateMessage(o);
}
} else if (fd.hasPresence() && msg.hasField(fd)) {
// If the field has presence information and is present, recursively validate it. Not all fields have
// presence, but we only validate Message type fields anyway, which always have explicit presence.
validateMessage(msg.getField(fd));
}
}
}
private void validateField(final FieldValidator<?> validator, final Object extensionValue, final Message msg, final Descriptors.FieldDescriptor fd) {
// for the fields with an `optional` modifier, checking if the field was set
// and if not, checking if extension allows missing optional field
if (fd.hasPresence() && !msg.hasField(fd)) {
switch (validator.getMissingOptionalAction()) {
case FAIL -> throw fieldViolation(fd, validator.getExtensionName(), "extension requires a value to be set");
case SUCCEED -> {
return;
}
case VALIDATE_DEFAULT_VALUE -> {}
}
}
try {
validator.validate(extensionValue, fd, msg.getField(fd));
} catch (FieldValidationException e) {
throw fieldViolation(fd, validator.getExtensionName(), e.getMessage());
}
}
private void validateRepeatedElementConstraints(
final ElementConstraint elementConstraint,
final Message message,
final Descriptors.FieldDescriptor fd) {
if (!fd.isRepeated() || fd.isMapField()) {
throw new IllegalStateException("each may only be applied to repeated fields");
}
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : elementConstraint.getAllFields().entrySet()) {
final FieldValidator<?> elementValidator = getValidatorOrThrow(entry.getKey());
final int count = message.getRepeatedFieldCount(fd);
for (int i = 0; i < count; i++) {
final Object element = message.getRepeatedField(fd, i);
try {
elementValidator.validate(entry.getValue(), fd, element);
} catch (final FieldValidationException e) {
throw fieldViolation(fd, entry.getKey().getFullName(), "element [%d]: %s".formatted(i, e.getMessage()));
}
}
}
}
private StatusRuntimeException fieldViolation(final Descriptors.FieldDescriptor fd, final String extensionName, final String message) {
return GrpcExceptions.fieldViolation(fd.getName(), "extension %s: %s".formatted(extensionName, message));
}
private static FieldValidator<?> getValidatorOrThrow(final Descriptors.FieldDescriptor extensionFd) {
final FieldValidator<?> validator = VALIDATORS.get(extensionFd.getName());
if (validator == null) {
throw new IllegalStateException("unrecognized extension " + extensionFd.getFullName());
}
return validator;
}
}
@@ -8,10 +8,9 @@ import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Metrics;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufAllocatorMetricProvider;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
@@ -34,15 +33,19 @@ import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.Mapping;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicOmnibusConfiguration;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/// An HTTP/2 server that proxies H2 streams to configurable backends via path-based routing
@@ -55,10 +58,12 @@ public class OmnibusH2Server implements Managed {
new OmnibusExceptionHandler("omnibus-handshake", List.of(SocketException.class, DecoderException.class, IOException.class));
private static final OmnibusExceptionHandler SESSION_EXCEPTION_HANDLER =
new OmnibusExceptionHandler("omnibus-session", List.of(Http2Exception.class));
private static final OmnibusLoadShedHandler LOAD_SHED_HANDLER = new OmnibusLoadShedHandler();
private static final String IDLE_DISCONNECT_COUNTER_NAME = MetricsUtil.name(OmnibusH2Server.class, "idleDisconnect");
private final @Nullable Mapping<String, SslContext> sslContextBySni;
private final OmnibusRouter router;
private final Supplier<DynamicOmnibusConfiguration> configurationSupplier;
private final Duration idleTimeout;
private final DefaultEventLoopGroup localEventLoopGroup;
private final NioEventLoopGroup nioEventLoopGroup;
@@ -68,20 +73,24 @@ public class OmnibusH2Server implements Managed {
/// Create an omnibus server
///
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
/// @param bindAddress The address the server should listen on
/// @param router How the server should select backends based on request paths
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
/// @param bindAddress The address the server should listen on
/// @param router How the server should select backends based on request paths
/// @param configurationSupplier Dynamic configuration supplier
/// @param idleTimeout How long to wait before terminating idle TCP connections
public OmnibusH2Server(
final @Nullable Mapping<String, SslContext> sslContextBySni,
final NioEventLoopGroup nioEventLoopGroup,
final DefaultEventLoopGroup localEventLoopGroup,
final SocketAddress bindAddress,
final OmnibusRouter router,
final Supplier<DynamicOmnibusConfiguration> configurationSupplier,
final Duration idleTimeout) {
this.sslContextBySni = sslContextBySni;
this.configurationSupplier = configurationSupplier;
this.nioEventLoopGroup = nioEventLoopGroup;
this.localEventLoopGroup = localEventLoopGroup;
this.bindAddress = bindAddress;
@@ -114,7 +123,15 @@ public class OmnibusH2Server implements Managed {
ch.pipeline().addLast(new ProxyProtocolHandler());
ch.pipeline().addLast(new ProxyMessageAttributeSetterHandler());
if (sslContextBySni == null) {
configureH2Pipeline(ch.pipeline());
// Defer setting up the H2 pipeline until the channel is active, so we know we can immediately write
// to it if we need to.
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
configureH2Pipeline(ctx.pipeline());
ctx.pipeline().remove(this);
}
});
} else {
ch.pipeline().addLast(new SniHandler(sslContextBySni));
ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) {
@@ -156,6 +173,11 @@ public class OmnibusH2Server implements Managed {
// Advertise support for RFC-8441 extended connect
final Http2Settings settings = Http2Settings.defaultSettings().connectProtocolEnabled(true);
pipeline.addLast(Http2FrameCodecBuilder.forServer().initialSettings(settings).build());
if (shouldRejectConnection()) {
pipeline.addLast(LOAD_SHED_HANDLER);
return;
}
pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(final Http2StreamChannel ch) {
@@ -164,4 +186,11 @@ public class OmnibusH2Server implements Managed {
}));
pipeline.addLast(SESSION_EXCEPTION_HANDLER);
}
private boolean shouldRejectConnection() {
final DynamicOmnibusConfiguration configuration = configurationSupplier.get();
final BigDecimal rejectionRatio = configuration.rejectConnectionRatio();
return rejectionRatio.compareTo(BigDecimal.ZERO) > 0 &&
ThreadLocalRandom.current().nextDouble() < rejectionRatio.doubleValue();
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.util.ReferenceCountUtil;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
@ChannelHandler.Sharable
public class OmnibusLoadShedHandler extends ChannelInboundHandlerAdapter {
// Error code to put in GOAWAY frames that indicate load-shedding. 0x40
// is an arbitrary non-reserved code per https://datatracker.ietf.org/doc/html/rfc7540#section-7
@VisibleForTesting
static final int LOAD_SHED_ERROR_CODE = 0x40;
private static final Counter LOAD_SHED_COUNTER =
Metrics.counter(MetricsUtil.name(OmnibusLoadShedHandler.class, "loadShed"));
@Override
public void handlerAdded(final ChannelHandlerContext ctx) {
LOAD_SHED_COUNTER.increment();
final DefaultHttp2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(LOAD_SHED_ERROR_CODE);
ctx.writeAndFlush(goAwayFrame).addListener(ChannelFutureListener.CLOSE);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// Drop any attempts to open streams
ReferenceCountUtil.release(msg);
}
}
@@ -6,16 +6,12 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.Descriptors;
import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
import org.whispersystems.textsecuregcm.util.Util;
import java.util.Base64;
import java.util.Objects;
import java.util.Set;
/// Validate that a string field is a valid base64 url string (padded or unpadded)
public class Base64UrlFieldValidator extends BaseFieldValidator<Boolean> {
public class Base64UrlFieldValidator extends FieldValidator<Boolean> {
public Base64UrlFieldValidator() {
super("base64url", Set.of(Descriptors.FieldDescriptor.Type.STRING), MissingOptionalAction.SUCCEED, false);
@@ -1,143 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.validators;
import static java.util.Objects.requireNonNull;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.Set;
public abstract class BaseFieldValidator<T> implements FieldValidator {
private final String extensionName;
private final Set<Descriptors.FieldDescriptor.Type> supportedTypes;
private final MissingOptionalAction missingOptionalAction;
private final boolean applicableToRepeated;
protected enum MissingOptionalAction {
FAIL,
SUCCEED,
VALIDATE_DEFAULT_VALUE
}
protected BaseFieldValidator(
final String extensionName,
final Set<Descriptors.FieldDescriptor.Type> supportedTypes,
final MissingOptionalAction missingOptionalAction,
final boolean applicableToRepeated) {
this.extensionName = requireNonNull(extensionName);
this.supportedTypes = requireNonNull(supportedTypes);
this.missingOptionalAction = missingOptionalAction;
this.applicableToRepeated = applicableToRepeated;
}
@Override
public void validate(
final Object extensionValue,
final Descriptors.FieldDescriptor fd,
final Message msg) throws FieldValidationException {
final T extensionValueTyped = resolveExtensionValue(extensionValue);
// for the fields with an `optional` modifier, checking if the field was set
// and if not, checking if extension allows missing optional field
if (fd.hasPresence() && !msg.hasField(fd)) {
switch (missingOptionalAction) {
case FAIL -> {
throw new FieldValidationException("extension requires a value to be set");
}
case SUCCEED -> {
return;
}
case VALIDATE_DEFAULT_VALUE -> {
// just continuing
}
}
}
// for the `repeated` fields, checking if it's supported by the extension
if (fd.isRepeated()) {
if (applicableToRepeated) {
validateRepeatedField(extensionValueTyped, fd, msg);
return;
}
throw new IllegalArgumentException("can't apply extension %s to `repeated` field %s"
.formatted(extensionName, fd.getFullName()));
}
// checking field type against the set of supported types
final Descriptors.FieldDescriptor.Type type = fd.getType();
if (!supportedTypes.contains(type)) {
throw new IllegalArgumentException("can't apply extension %s to field %s of type %s".formatted(
extensionName, fd.getFullName(), type));
}
switch (type) {
case INT64, UINT64, INT32, FIXED64, FIXED32, UINT32, SFIXED32, SFIXED64, SINT32, SINT64 ->
validateIntegerNumber(extensionValueTyped, ((Number) msg.getField(fd)).longValue(), type);
case STRING -> validateStringValue(extensionValueTyped, (String) msg.getField(fd));
case BYTES -> validateBytesValue(extensionValueTyped, (ByteString) msg.getField(fd));
case ENUM -> validateEnumValue(extensionValueTyped, (Descriptors.EnumValueDescriptor) msg.getField(fd));
case MESSAGE -> {
validateMessageValue(extensionValueTyped, (Message) msg.getField(fd));
}
case FLOAT, DOUBLE, BOOL, GROUP -> {
// at this moment, there are no validations specific to these types of fields
}
}
}
protected abstract T resolveExtensionValue(final Object extensionValue) throws FieldValidationException;
protected void validateRepeatedField(
final T extensionValue,
final Descriptors.FieldDescriptor fd,
final Message msg) throws FieldValidationException {
throw new UnsupportedOperationException("`validateRepeatedField` method needs to be implemented");
}
protected void validateIntegerNumber(
final T extensionValue,
final long fieldValue, final Descriptors.FieldDescriptor.Type type) throws FieldValidationException {
throw new UnsupportedOperationException("`validateIntegerNumber` method needs to be implemented");
}
protected void validateStringValue(
final T extensionValue,
final String fieldValue) throws FieldValidationException {
throw new UnsupportedOperationException("`validateStringValue` method needs to be implemented");
}
protected void validateBytesValue(
final T extensionValue,
final ByteString fieldValue) throws FieldValidationException {
throw new UnsupportedOperationException("`validateBytesValue` method needs to be implemented");
}
protected void validateEnumValue(
final T extensionValue,
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException {
throw new UnsupportedOperationException("`validateEnumValue` method needs to be implemented");
}
protected void validateMessageValue(
final T extensionValue,
final Message message) throws FieldValidationException {
throw new UnsupportedOperationException("`validateMessageValue` method needs to be implemented");
}
protected static boolean requireFlagExtension(final Object extensionValue) throws FieldValidationException {
if (extensionValue instanceof Boolean flagIsOn && flagIsOn) {
return true;
}
throw new UnsupportedOperationException("only value `true` is allowed");
}
}
@@ -11,7 +11,7 @@ import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
import org.whispersystems.textsecuregcm.util.Util;
public class E164FieldValidator extends BaseFieldValidator<Boolean> {
public class E164FieldValidator extends FieldValidator<Boolean> {
public E164FieldValidator() {
super("e164", Set.of(Descriptors.FieldDescriptor.Type.STRING), MissingOptionalAction.SUCCEED, false);
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.Descriptors;
import java.util.Set;
public class EnumSpecifiedFieldValidator extends BaseFieldValidator<Boolean> {
public class EnumSpecifiedFieldValidator extends FieldValidator<Boolean> {
public EnumSpecifiedFieldValidator() {
super("specified", Set.of(Descriptors.FieldDescriptor.Type.ENUM), MissingOptionalAction.FAIL, false);
@@ -7,11 +7,10 @@ package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.List;
import java.util.Set;
public class ExactlySizeFieldValidator extends BaseFieldValidator<Set<Integer>> {
public class ExactlySizeFieldValidator extends FieldValidator<Set<Integer>> {
public ExactlySizeFieldValidator() {
super("exactlySize", Set.of(
@@ -50,11 +49,10 @@ public class ExactlySizeFieldValidator extends BaseFieldValidator<Set<Integer>>
protected void validateRepeatedField(
final Set<Integer> permittedSizes,
final Descriptors.FieldDescriptor fd,
final Message msg) throws FieldValidationException {
final int size = msg.getRepeatedFieldCount(fd);
if (permittedSizes.contains(size)) {
final List<?> repeated) throws FieldValidationException {
if (permittedSizes.contains(repeated.size())) {
return;
}
throw new FieldValidationException("list size is [%d] but expected to be one of %s".formatted(size, permittedSizes));
throw new FieldValidationException("list size is [%d] but expected to be one of %s".formatted(repeated.size(), permittedSizes));
}
}
@@ -5,11 +5,134 @@
package org.whispersystems.textsecuregcm.grpc.validators;
import static java.util.Objects.requireNonNull;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.List;
import java.util.Set;
public interface FieldValidator {
public abstract class FieldValidator<T> {
void validate(Object extensionValue, Descriptors.FieldDescriptor fd, Message msg)
throws FieldValidationException;
private final String extensionName;
private final Set<Descriptors.FieldDescriptor.Type> supportedTypes;
private final MissingOptionalAction missingOptionalAction;
private final boolean applicableToRepeated;
public enum MissingOptionalAction {
FAIL,
SUCCEED,
VALIDATE_DEFAULT_VALUE
}
protected FieldValidator(
final String extensionName,
final Set<Descriptors.FieldDescriptor.Type> supportedTypes,
final MissingOptionalAction missingOptionalAction,
final boolean applicableToRepeated) {
this.extensionName = requireNonNull(extensionName);
this.supportedTypes = requireNonNull(supportedTypes);
this.missingOptionalAction = missingOptionalAction;
this.applicableToRepeated = applicableToRepeated;
}
public MissingOptionalAction getMissingOptionalAction() {
return missingOptionalAction;
}
public String getExtensionName() {
return extensionName;
}
/// Validate a field
///
/// @param extensionValue The value of the option this field was annotated with
/// @param fd The descriptor of the field to validate
/// @param fieldValue The value of the field to validate
/// @throws FieldValidationException if a field constraint was violated
public final void validate(
final Object extensionValue,
final Descriptors.FieldDescriptor fd,
final Object fieldValue) throws FieldValidationException {
final T extensionValueTyped = resolveExtensionValue(extensionValue);
// for the `repeated` fields, checking if it's supported by the extension
if (fd.isRepeated() && fieldValue instanceof List list) {
if (!applicableToRepeated) {
throw new IllegalArgumentException("can't apply extension %s to `repeated` field %s"
.formatted(extensionName, fd.getFullName()));
}
validateRepeatedField(extensionValueTyped, fd, list);
return;
}
final Descriptors.FieldDescriptor.Type type = fd.getType();
if (!supportedTypes.contains(type)) {
throw new IllegalArgumentException("can't apply extension %s to field %s of type %s".formatted(
extensionName, fd.getFullName(), type));
}
switch (type) {
case INT64, UINT64, INT32, FIXED64, FIXED32, UINT32, SFIXED32, SFIXED64, SINT32, SINT64 ->
validateIntegerNumber(extensionValueTyped, ((Number) fieldValue).longValue(), type);
case STRING -> validateStringValue(extensionValueTyped, (String) fieldValue);
case BYTES -> validateBytesValue(extensionValueTyped, (ByteString) fieldValue);
case ENUM -> validateEnumValue(extensionValueTyped, (Descriptors.EnumValueDescriptor) fieldValue);
case MESSAGE -> validateMessageValue(extensionValueTyped, (Message) fieldValue);
case FLOAT, DOUBLE, BOOL, GROUP -> {
// at this moment, there are no validations specific to these types of fields
}
}
}
protected abstract T resolveExtensionValue(final Object extensionValue) throws FieldValidationException;
protected void validateRepeatedField(
final T extensionValue,
final Descriptors.FieldDescriptor fd,
final List<?> repeated) throws FieldValidationException {
throw new UnsupportedOperationException("`validateRepeatedField` method needs to be implemented");
}
protected void validateIntegerNumber(
final T extensionValue,
final long fieldValue, final Descriptors.FieldDescriptor.Type type) throws FieldValidationException {
throw new UnsupportedOperationException("`validateIntegerNumber` method needs to be implemented");
}
protected void validateStringValue(
final T extensionValue,
final String fieldValue) throws FieldValidationException {
throw new UnsupportedOperationException("`validateStringValue` method needs to be implemented");
}
protected void validateBytesValue(
final T extensionValue,
final ByteString fieldValue) throws FieldValidationException {
throw new UnsupportedOperationException("`validateBytesValue` method needs to be implemented");
}
protected void validateEnumValue(
final T extensionValue,
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException {
throw new UnsupportedOperationException("`validateEnumValue` method needs to be implemented");
}
protected void validateMessageValue(
final T extensionValue,
final Message message) throws FieldValidationException {
throw new UnsupportedOperationException("`validateMessageValue` method needs to be implemented");
}
protected static boolean requireFlagExtension(final Object extensionValue) throws FieldValidationException {
if (extensionValue instanceof Boolean flagIsOn && flagIsOn) {
return true;
}
throw new UnsupportedOperationException("only value `true` is allowed");
}
}
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
public class NonEmptyFieldValidator extends BaseFieldValidator<Boolean> {
public class NonEmptyFieldValidator extends FieldValidator<Boolean> {
public NonEmptyFieldValidator() {
super("nonEmpty", Set.of(
@@ -49,8 +49,8 @@ public class NonEmptyFieldValidator extends BaseFieldValidator<Boolean> {
protected void validateRepeatedField(
final Boolean extensionValue,
final Descriptors.FieldDescriptor fd,
final Message msg) throws FieldValidationException {
if (msg.getRepeatedFieldCount(fd) > 0) {
final List<?> repeated) throws FieldValidationException {
if (repeated.size() > 0) {
return;
}
throw new FieldValidationException("repeated field is expected to be non-empty");
@@ -9,7 +9,7 @@ import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.Set;
public class PresentFieldValidator extends BaseFieldValidator<Boolean> {
public class PresentFieldValidator extends FieldValidator<Boolean> {
public PresentFieldValidator() {
super("present",
@@ -9,7 +9,7 @@ import com.google.protobuf.Descriptors;
import java.util.Set;
import org.signal.chat.require.ValueRangeConstraint;
public class RangeFieldValidator extends BaseFieldValidator<Range> {
public class RangeFieldValidator extends FieldValidator<Range> {
private static final Set<Descriptors.FieldDescriptor.Type> UNSIGNED_TYPES = Set.of(
Descriptors.FieldDescriptor.Type.FIXED32,
@@ -12,7 +12,7 @@ import java.util.Set;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
public class ServiceIdentifierIdentityTypeValidator extends BaseFieldValidator<IdentityType> {
public class ServiceIdentifierIdentityTypeValidator extends FieldValidator<IdentityType> {
public ServiceIdentifierIdentityTypeValidator() {
super("identityType", Set.of(Descriptors.FieldDescriptor.Type.MESSAGE), MissingOptionalAction.SUCCEED, false);
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.List;
import java.util.Set;
import org.signal.chat.require.SizeConstraint;
public class SizeFieldValidator extends BaseFieldValidator<Range> {
public class SizeFieldValidator extends FieldValidator<Range> {
public SizeFieldValidator() {
super("size", Set.of(
@@ -45,8 +45,8 @@ public class SizeFieldValidator extends BaseFieldValidator<Range> {
}
@Override
protected void validateRepeatedField(final Range range, final Descriptors.FieldDescriptor fd, final Message msg) throws FieldValidationException {
final int size = msg.getRepeatedFieldCount(fd);
protected void validateRepeatedField(final Range range, final Descriptors.FieldDescriptor fd, final List<?> repeated) throws FieldValidationException {
final int size = repeated.size();
if (size < range.min() || size > range.max()) {
throw new FieldValidationException("field value is [%d] but expected to be within the [%d, %d] range".formatted(
size, range.min(), range.max()));
@@ -29,8 +29,10 @@ import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.KeyTransparencyQueryServiceGrpc;
import org.signal.keytransparency.client.MonitorRequest;
import org.signal.keytransparency.client.MonitorResponse;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchRequest;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -110,7 +112,7 @@ public class KeyTransparencyServiceClient implements Managed {
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public SearchResponse search(
public SearchResponseV2 search(
final ByteString aci,
final ByteString aciIdentityKey,
final Optional<ByteString> usernameHash,
@@ -132,13 +134,13 @@ public class KeyTransparencyServiceClient implements Managed {
return search(searchRequestBuilder.build());
}
public SearchResponse search(final SearchRequest request) {
public SearchResponseV2 search(final SearchRequest request) {
return stub.withDeadline(toDeadline(KEY_TRANSPARENCY_RPC_TIMEOUT))
.search(request);
.searchV2(request);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public MonitorResponse monitor(final AciMonitorRequest aciMonitorRequest,
public MonitorResponseV2 monitor(final AciMonitorRequest aciMonitorRequest,
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest,
final Optional<E164MonitorRequest> e164MonitorRequest,
final long lastTreeHeadSize,
@@ -155,12 +157,11 @@ public class KeyTransparencyServiceClient implements Managed {
return monitor(monitorRequestBuilder.build());
}
public MonitorResponse monitor(final MonitorRequest request) {
public MonitorResponseV2 monitor(final MonitorRequest request) {
return stub.withDeadline(toDeadline(KEY_TRANSPARENCY_RPC_TIMEOUT))
.monitor(request);
.monitorV2(request);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public DistinguishedResponse getDistinguishedKey(final Optional<Long> lastTreeHeadSize) {
final DistinguishedRequest request = lastTreeHeadSize.map(
@@ -171,7 +172,7 @@ public class KeyTransparencyServiceClient implements Managed {
public DistinguishedResponse distinguished(final DistinguishedRequest request) {
return stub.withDeadline(toDeadline(KEY_TRANSPARENCY_RPC_TIMEOUT))
.distinguished(request);
.distinguishedV2(request);
}
private static Deadline toDeadline(final Duration timeout) {
@@ -28,6 +28,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
ALLOCATE_DEVICE("allocateDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
VERIFY_DEVICE("verifyDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
PROFILE("profile", new RateLimiterConfig(4320, Duration.ofSeconds(20), true)),
PROFILE_AVATAR_BYTES("profileAvatarBytes", new RateLimiterConfig(DataSize.mebibytes(100).toBytes(), Duration.ofNanos(10000), true)),
STICKER_PACK("stickerPack", new RateLimiterConfig(50, Duration.ofMinutes(72), false)),
USERNAME_LOOKUP("usernameLookup", new RateLimiterConfig(100, Duration.ofMinutes(15), true)),
USERNAME_SET("usernameSet", new RateLimiterConfig(100, Duration.ofMinutes(15), false)),
@@ -134,6 +135,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.PROFILE);
}
public RateLimiter getProfileAvatarBytesLimiter() {
return forDescriptor(For.PROFILE_AVATAR_BYTES);
}
public RateLimiter getStickerPackLimiter() {
return forDescriptor(For.STICKER_PACK);
}
@@ -19,32 +19,31 @@ import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Base64;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.signal.registration.rpc.CheckVerificationCodeRequest;
import org.signal.registration.rpc.CheckVerificationCodeResponse;
import org.signal.registration.rpc.CreateRegistrationSessionRequest;
import org.signal.registration.rpc.CreateRegistrationSessionResponse;
import org.signal.registration.rpc.GetRegistrationSessionMetadataRequest;
import org.signal.registration.rpc.GetRegistrationSessionMetadataResponse;
import org.signal.registration.rpc.RegistrationServiceGrpc;
import org.signal.registration.rpc.RegistrationSessionMetadata;
import org.signal.registration.rpc.SendVerificationCodeRequest;
import org.signal.registration.rpc.SendVerificationCodeResponse;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.controllers.VerificationSessionRateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.util.CompletableFutureUtil;
public class RegistrationServiceClient implements Managed {
private static final Base64.Encoder BASE64_UNPADDED_ENCODER = Base64.getEncoder().withoutPadding();
private final ManagedChannel channel;
private final RegistrationServiceGrpc.RegistrationServiceFutureStub stub;
private final Executor callbackExecutor;
private final RegistrationServiceGrpc.RegistrationServiceBlockingStub stub;
private final byte[] collationKeySalt;
/**
@@ -68,8 +67,7 @@ public class RegistrationServiceClient implements Managed {
final int port,
final CallCredentials callCredentials,
final String caCertificatePem,
final byte[] collationKeySalt,
final Executor callbackExecutor) throws IOException {
final byte[] collationKeySalt) throws IOException {
try (final ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(caCertificatePem.getBytes(StandardCharsets.UTF_8))) {
final ChannelCredentials tlsChannelCredentials = TlsChannelCredentials.newBuilder()
@@ -81,9 +79,8 @@ public class RegistrationServiceClient implements Managed {
.build();
}
this.stub = RegistrationServiceGrpc.newFutureStub(channel).withCallCredentials(callCredentials);
this.stub = RegistrationServiceGrpc.newBlockingStub(channel).withCallCredentials(callCredentials);
this.collationKeySalt = collationKeySalt;
this.callbackExecutor = callbackExecutor;
// Fail fast: reject bad keys
try {
@@ -93,52 +90,54 @@ public class RegistrationServiceClient implements Managed {
}
}
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
public RegistrationServiceSession createRegistrationSession(
final Phonenumber.PhoneNumber phoneNumber,
final String sourceHost,
final boolean accountExistsWithPhoneNumber,
@Nullable final String clientMcc,
@Nullable final String clientMnc,
final Duration timeout) {
final Duration timeout) throws RateLimitExceededException {
final long e164 = Long.parseLong(
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
final String rateLimitCollationKey = hmac(sourceHost);
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
final CreateRegistrationSessionResponse response = stub.withDeadline(toDeadline(timeout))
.createSession(CreateRegistrationSessionRequest.newBuilder()
.setE164(e164)
.setAccountExistsWithE164(accountExistsWithPhoneNumber)
.setRateLimitCollationKey(rateLimitCollationKey)
.setMcc(clientMcc != null ? clientMcc : "")
.setMnc(clientMnc != null ? clientMnc : "")
.build()), callbackExecutor)
.thenApply(response -> switch (response.getResponseCase()) {
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
.build());
case ERROR -> {
switch (response.getError().getErrorType()) {
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
new RateLimitExceededException(response.getError().getMayRetry()
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
: null
));
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER -> throw new IllegalArgumentException();
default -> throw new RuntimeException(
"Unrecognized error type from registration service: " + response.getError().getErrorType());
}
}
return switch (response.getResponseCase()) {
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
case RESPONSE_NOT_SET -> throw new RuntimeException("No response from registration service");
});
case ERROR -> {
switch (response.getError().getErrorType()) {
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED ->
throw new RateLimitExceededException(response.getError().getMayRetry()
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
: null
);
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER -> throw new IllegalArgumentException();
default -> throw new RuntimeException(
"Unrecognized error type from registration service: " + response.getError().getErrorType());
}
}
case RESPONSE_NOT_SET -> throw new RuntimeException("No response from registration service");
};
}
public CompletableFuture<RegistrationServiceSession> sendVerificationCode(final byte[] sessionId,
public RegistrationServiceSession sendVerificationCode(final byte[] sessionId,
final MessageTransport messageTransport,
final ClientType clientType,
@Nullable final String acceptLanguage,
@Nullable final String senderOverride,
final Duration timeout) {
final Duration timeout)
throws VerificationSessionRateLimitExceededException, RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException {
final SendVerificationCodeRequest.Builder requestBuilder = SendVerificationCodeRequest.newBuilder()
.setSessionId(ByteString.copyFrom(sessionId))
@@ -153,102 +152,95 @@ public class RegistrationServiceClient implements Managed {
requestBuilder.setSenderName(senderOverride);
}
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
.sendVerificationCode(requestBuilder.build()), callbackExecutor)
.thenApply(response -> {
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
new VerificationSessionRateLimitExceededException(
buildSessionResponseFromMetadata(response.getSessionMetadata()),
response.getError().getMayRetry()
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
: null,
true));
final SendVerificationCodeResponse response =
stub.withDeadline(toDeadline(timeout)).sendVerificationCode(requestBuilder.build());
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new CompletionException(
new RegistrationServiceException(null));
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new VerificationSessionRateLimitExceededException(
buildSessionResponseFromMetadata(response.getSessionMetadata()),
response.getError().getMayRetry()
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
: null,
true);
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_ALREADY_VERIFIED -> throw new CompletionException(
new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata())));
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new RegistrationServiceException(null);
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED -> throw new CompletionException(
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
throw new CompletionException(new RegistrationFraudException(
RegistrationServiceSenderException.rejected(response.getError().getMayRetry())));
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT -> throw new CompletionException(
RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry()));
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED -> throw new CompletionException(
RegistrationServiceSenderException.unknown(response.getError().getMayRetry()));
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED -> throw new CompletionException(
new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata())));
case SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE -> throw new CompletionException(
RegistrationServiceSenderException.unavailable(response.getError().getMayRetry()));
case SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_ALREADY_VERIFIED ->
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
default -> throw new CompletionException(
new RuntimeException("Failed to send verification code: " + response.getError().getErrorType()));
}
} else {
return buildSessionResponseFromMetadata(response.getSessionMetadata());
}
});
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED ->
throw RegistrationServiceSenderException.rejected(response.getError().getMayRetry());
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
throw new RegistrationFraudException(
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT ->
throw RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry());
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED ->
throw RegistrationServiceSenderException.unknown(response.getError().getMayRetry());
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED ->
throw new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
case SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE ->
throw RegistrationServiceSenderException.unavailable(response.getError().getMayRetry());
default -> throw new RuntimeException("Failed to send verification code: " + response.getError().getErrorType());
}
} else {
return buildSessionResponseFromMetadata(response.getSessionMetadata());
}
}
public CompletableFuture<RegistrationServiceSession> checkVerificationCode(final byte[] sessionId,
public RegistrationServiceSession checkVerificationCode(final byte[] sessionId,
final String verificationCode,
final Duration timeout) {
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
final Duration timeout) throws VerificationSessionRateLimitExceededException, RegistrationServiceException {
final CheckVerificationCodeResponse response = stub.withDeadline(toDeadline(timeout))
.checkVerificationCode(CheckVerificationCodeRequest.newBuilder()
.setSessionId(ByteString.copyFrom(sessionId))
.setVerificationCode(verificationCode)
.build()), callbackExecutor)
.thenApply(response -> {
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(
new VerificationSessionRateLimitExceededException(
buildSessionResponseFromMetadata(response.getSessionMetadata()),
response.getError().getMayRetry()
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
: null,
true));
.build());
case CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT, CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPT_EXPIRED ->
throw new CompletionException(
new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()))
);
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED -> throw new VerificationSessionRateLimitExceededException(
buildSessionResponseFromMetadata(response.getSessionMetadata()),
response.getError().getMayRetry()
? Duration.ofSeconds(response.getError().getRetryAfterSeconds())
: null,
true);
case CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new CompletionException(
new RegistrationServiceException(null)
);
case CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT, CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPT_EXPIRED ->
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
default -> throw new CompletionException(
new RuntimeException("Failed to check verification code: " + response.getError().getErrorType()));
}
} else {
return buildSessionResponseFromMetadata(response.getSessionMetadata());
}
});
case CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND -> throw new RegistrationServiceException(null);
default -> throw new RuntimeException("Failed to check verification code: " + response.getError().getErrorType());
}
} else {
return buildSessionResponseFromMetadata(response.getSessionMetadata());
}
}
public CompletableFuture<Optional<RegistrationServiceSession>> getSession(final byte[] sessionId,
final Duration timeout) {
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout)).getSessionMetadata(
GetRegistrationSessionMetadataRequest.newBuilder()
.setSessionId(ByteString.copyFrom(sessionId)).build()), callbackExecutor)
.thenApply(response -> {
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case GET_REGISTRATION_SESSION_METADATA_ERROR_TYPE_NOT_FOUND -> {
return Optional.empty();
}
default -> throw new RuntimeException("Failed to get session: " + response.getError().getErrorType());
}
}
public Optional<RegistrationServiceSession> getSession(final byte[] sessionId, final Duration timeout) {
final GetRegistrationSessionMetadataResponse response = stub.withDeadline(toDeadline(timeout))
.getSessionMetadata(GetRegistrationSessionMetadataRequest.newBuilder()
.setSessionId(ByteString.copyFrom(sessionId)).build());
return Optional.of(buildSessionResponseFromMetadata(response.getSessionMetadata()));
});
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case GET_REGISTRATION_SESSION_METADATA_ERROR_TYPE_NOT_FOUND -> {
return Optional.empty();
}
default -> throw new RuntimeException("Failed to get session: " + response.getError().getErrorType());
}
}
return Optional.of(buildSessionResponseFromMetadata(response.getSessionMetadata()));
}
private static RegistrationServiceSession buildSessionResponseFromMetadata(
@@ -288,7 +280,7 @@ public class RegistrationServiceClient implements Managed {
}
}
private String hmac(String sourceHost) {
private String hmac(final String sourceHost) {
final Mac hmacSha256 = getInitializedMac();
hmacSha256.update(sourceHost.getBytes(StandardCharsets.UTF_8));
@@ -303,7 +295,6 @@ public class RegistrationServiceClient implements Managed {
}
}
private static Mac getInitializedMac(byte[] key) throws InvalidKeyException {
try {
final Mac hmacSha256 = Mac.getInstance("HmacSHA256");
@@ -9,12 +9,9 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.micrometer.core.instrument.Metrics;
@@ -33,6 +30,7 @@ import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,6 +41,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
@JsonFilter("Account")
public class Account {
@@ -128,7 +127,9 @@ public class Account {
@JsonProperty("zck")
@Nullable
private byte[] zkCredentialKey;
@JsonSerialize(using = ZkCredentialPublicKeyAdapter.Serializer.class)
@JsonDeserialize(using = ZkCredentialPublicKeyAdapter.Deserializer.class)
private ZkCredentialPublicKey zkCredentialKey;
@JsonProperty("zckr")
@Nullable
@@ -560,12 +561,11 @@ public class Account {
this.usernameHolds = usernameHolds;
}
@Nullable
public byte[] getZkCredentialKey() {
return zkCredentialKey;
public Optional<ZkCredentialPublicKey> getZkCredentialKey() {
return Optional.ofNullable(zkCredentialKey);
}
public void setZkCredentialKey(@Nullable final byte[] zkCredentialKey) {
public void setZkCredentialKey(@Nullable final ZkCredentialPublicKey zkCredentialKey) {
this.zkCredentialKey = zkCredentialKey;
}
@@ -327,7 +327,8 @@ public class Accounts {
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
// Carry over the existing ZK credential key to the new account
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey());
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
final List<TransactWriteItem> writeItems = new ArrayList<>();
@@ -0,0 +1,162 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.BiConsumer;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.reactivestreams.Subscription;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.BaseSubscriber;
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
public class AcknowledgementMirroringMessageStream implements MessageStream {
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private final FoundationDbMessageStream foundationDbMessageStream;
private final Set<UUID> messagesPendingAcknowledgement = new HashSet<>();
private static final int HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD = 1024;
@VisibleForTesting
static final int MAX_PENDING_ACKNOWLEDGEMENTS = 8192;
@VisibleForTesting
static final int FOUNDATIONDB_REQUEST_SIZE = 100;
private static final Counter HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER =
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "highPendingAcknowledgementCount"));
private static final Counter MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER =
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "maxPendingAcknowledgementLimitBreached"));
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry.Envelope> {
private final BiConsumer<UUID, Long> mirroredMessageHandler;
private long mirroredEntriesDelivered = 0;
private long requested = 0;
private FoundationDbSubscriber(final BiConsumer<UUID, Long> mirroredMessageHandler) {
this.mirroredMessageHandler = mirroredMessageHandler;
}
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
final boolean isMirroredMessage = switch (messageStreamEntry) {
case MessageStreamEntry.Envelope envelopeEntry ->
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
case MessageStreamEntry.QueueEmpty _ -> false;
};
if (!isMirroredMessage) {
return;
}
final boolean requestMore;
synchronized (this) {
requestMore = ++mirroredEntriesDelivered > requested;
if (requestMore) {
requested += FOUNDATIONDB_REQUEST_SIZE;
}
}
if (requestMore) {
request(FOUNDATIONDB_REQUEST_SIZE);
}
}
@Override
protected void hookOnSubscribe(final Subscription subscription) {
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
// to avoid with this subscriber
}
@Override
protected void hookOnNext(final MessageStreamEntry.Envelope envelope) {
mirroredMessageHandler.accept(
UUIDUtil.fromByteString(envelope.message().getServerGuid()), envelope.message().getServerTimestamp());
}
}
public AcknowledgementMirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
final FoundationDbMessageStream foundationDbMessageStream) {
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
this.foundationDbMessageStream = foundationDbMessageStream;
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber(this::handleMirroredMessageAcknowledged);
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
.cast(MessageStreamEntry.Envelope.class)
.subscribe(subscriber);
return JdkFlowAdapter.publisherToFlowPublisher(
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
// Mirror demand and termination signals to the FoundationDB message stream
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
.doOnComplete(subscriber::dispose));
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
// in Redis/DynamoDB
if (messageGuid.version() == 8) {
handleMirroredMessageAcknowledged(messageGuid, serverTimestamp);
}
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
}
private void handleMirroredMessageAcknowledged(final UUID messageGuid, final long serverTimestamp) {
// Before we can acknowledge and delete the message in FoundationDB, two things need to happen:
//
// 1. The client needs to acknowledge the message on the Redis/DDB stream.
// 2. The message needs to pass through the FoundationDB message stream pipeline because it needs to be registered
// in the acknowledged message buffer machinery before it can be deleted.
//
// We can't guarantee the order in which these two things happen, so we use a synchronized set to coordinate and
// determine when both have happened.
synchronized (messagesPendingAcknowledgement) {
if (messagesPendingAcknowledgement.remove(messageGuid)) {
// One of the two streams had already acknowledged this message, and this is the second acknowledgement. Now we
// can pass the acknowledgement along to FoundationDB.
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
} else {
// Either this message came from FoundationDB and got auto-acknowledged before getting explicitly acknowledged
// on the Redis/DynamoDB stream or the message got explicitly acknowledged on the Redis/DynamoDB stream before
// passing through the FoundationDB stream. Either way, wait for both streams to have done their part.
if (messagesPendingAcknowledgement.add(messageGuid)) {
if (messagesPendingAcknowledgement.size() == HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD) {
HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER.increment();
}
if (messagesPendingAcknowledgement.size() > MAX_PENDING_ACKNOWLEDGEMENTS) {
MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER.increment();
throw new IllegalStateException("Too many pending acknowledgements");
}
}
}
}
}
}
@@ -158,21 +158,24 @@ public class ChangeNumberManager {
final Account updatedAccount = accountsManager.changeNumber(
account.getIdentifier(IdentityType.ACI), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
.build());
if (!messagesByDeviceId.isEmpty()) {
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
.build());
messageSender.sendMessages(updatedAccount,
serviceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
senderUserAgent);
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages for {}", account.getIdentifier(IdentityType.ACI), e);
throw e;
messageSender.sendMessages(updatedAccount,
serviceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
senderUserAgent);
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages for {}",
account.getIdentifier(IdentityType.ACI), e);
throw e;
}
}
return updatedAccount;
@@ -1,66 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
public class DeletionMirroringRedisDynamoDbMessageStream implements MessageStream {
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private final FoundationDbMessageStore foundationDbMessageStore;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final AciServiceIdentifier accountIdentifier;
private final byte deviceId;
private static final Logger logger = LoggerFactory.getLogger(DeletionMirroringRedisDynamoDbMessageStream.class);
public DeletionMirroringRedisDynamoDbMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
final FoundationDbMessageStore foundationDbMessageStore,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final UUID accountIdentifier,
final byte deviceId) {
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
this.foundationDbMessageStore = foundationDbMessageStore;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
this.deviceId = deviceId;
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
return redisDynamoDbMessageStream.getMessages();
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
// in Redis/DynamoDB
if (messageGuid.version() == 8 &&
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
foundationDbMessageStore.delete(accountIdentifier, deviceId, messageGuid)
.whenComplete((_, throwable) -> {
if (throwable != null) {
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
messageGuid, throwable);
}
});
}
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
}
}
@@ -0,0 +1,56 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.util.AttributeValues.b;
import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
public class DonationPermits {
public static final String KEY_SPEND_ID = "I"; // B (HashKey)
public static final String KEY_EXPIRATION = "E"; // N
private final String table;
private final Duration expiration;
private final DynamoDbClient dynamoDbClient;
public DonationPermits(String tableName, Duration expiration,
DynamoDbClient dynamoDbClient) {
this.table = tableName;
this.expiration = expiration;
this.dynamoDbClient = dynamoDbClient;
}
public boolean spend(final byte[] spendId, final Instant now) {
final UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_SPEND_ID, b(spendId)))
.conditionExpression("attribute_not_exists(#id)")
.returnValues(ReturnValue.NONE)
.updateExpression("SET #exp = :exp")
.expressionAttributeNames(Map.of(
"#id", KEY_SPEND_ID,
"#exp", KEY_EXPIRATION))
.expressionAttributeValues(Map.of(
":exp", n(now.plus(expiration).getEpochSecond())))
.build();
try {
dynamoDbClient.updateItem(updateItemRequest);
return true;
} catch (final ConditionalCheckFailedException _) {
return false;
}
}
}
@@ -0,0 +1,52 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.time.Clock;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.signal.libsignal.zkgroup.donation.DonationPermitDerivedKeyPair;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
public class DonationPermitsManager {
private final DonationPermits donationPermits;
private final ServerSecretParams serverSecretParams;
private final Clock clock;
public DonationPermitsManager(final DonationPermits donationPermits, final ServerSecretParams serverSecretParams,
final Clock clock) {
this.donationPermits = donationPermits;
this.serverSecretParams = serverSecretParams;
this.clock = clock;
}
/// Verifies and then spends the given {@link DonationPermit}
///
/// @return whether the spend was successful
/// @throws VerificationFailedException if the permit was not valid (expired or otherwise)
public boolean spend(final DonationPermit donationPermit) throws VerificationFailedException {
// Permits must be verified with the key pair that issued them, which can be re-derived from the embedded expiration
final DonationPermitDerivedKeyPair issuingKeyPair = DonationPermitDerivedKeyPair.forExpiration(
donationPermit.getExpiration(), serverSecretParams);
donationPermit.verify(issuingKeyPair, clock.instant());
return donationPermits.spend(donationPermit.getSpendId(), clock.instant());
}
/// Issues {@link DonationPermitResponse} with an expiration derived from the current time
public DonationPermitResponse issue(final DonationPermitRequest permitRequest) {
final DonationPermitDerivedKeyPair currentDerivedKeyPair = DonationPermitDerivedKeyPair.forExpiration(
DonationPermitResponse.defaultExpiration(clock.instant()),
serverSecretParams);
return permitRequest.issue(currentDerivedKeyPair);
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
/// A message stream publishes an ordered stream of Signal messages from a destination device's queue and provides a
/// mechanism for consumers to acknowledge receipt of delivered messages.
@@ -38,6 +38,7 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
@@ -279,12 +280,15 @@ public class MessagesManager {
}
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
return new DeletionMirroringRedisDynamoDbMessageStream(
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice),
foundationDbMessageStore,
experimentEnrollmentManager,
destinationUuid,
destinationDevice.getId());
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
destinationUuid, destinationDevice);
return experimentEnrollmentManager.isEnrolled(destinationUuid, MIRROR_DELETIONS_EXPERIMENT_NAME)
? new AcknowledgementMirroringMessageStream(
redisDynamoDbMessageStream,
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
: redisDynamoDbMessageStream;
}
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
@@ -0,0 +1,106 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
public class ProfileAvatars {
private final DynamoDbClient dynamoDbClient;
private final String tableName;
private final Duration expiration;
private final Clock clock;
// Identity that owns this profile; hash key; byte array
@VisibleForTesting
static final String KEY_IDENTITY = "I";
// URL of the avatar; string
@VisibleForTesting
static final String ATTR_URL = "U";
// Expiration timestamp, in seconds since the epoch, of the avatar; number
@VisibleForTesting
static final String ATTR_TTL = "E";
public ProfileAvatars(final DynamoDbClient dynamoDbClient, final String tableName, final Duration expiration, final
Clock clock) {
this.dynamoDbClient = dynamoDbClient;
this.tableName = tableName;
this.expiration = expiration;
this.clock = clock;
}
/// Sets the avatar URL for an identity
///
/// @return the previous URL, if any
public Optional<String> setAvatarUrl(final byte[] identity, final String url) {
final PutItemResponse response = dynamoDbClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity),
ATTR_URL, AttributeValues.fromString(url),
ATTR_TTL, AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
.returnValues(ReturnValue.ALL_OLD)
.build());
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
}
/// @return the avatar URL, if present
public Optional<String> updateAvatarTtl(final byte[] identity) {
final UpdateItemResponse response;
try {
response = dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.conditionExpression("attribute_exists(#url)")
.updateExpression("SET #ttl = :ttl")
.expressionAttributeNames(Map.of(
"#ttl", ATTR_TTL,
"#url", ATTR_URL))
.expressionAttributeValues(
Map.of(":ttl", AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
.returnValues(ReturnValue.ALL_OLD)
.build());
} catch (ConditionalCheckFailedException _) {
return Optional.empty();
}
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
}
/// @return the deleted avatar URL, if present
public Optional<String> deleteAvatarUrl(final byte[] identity) {
final DeleteItemResponse response = dynamoDbClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.returnValues(ReturnValue.ALL_OLD)
.build());
if (!response.hasAttributes()) {
return Optional.empty();
}
return Optional.ofNullable(response.attributes().get(ATTR_URL))
.map(AttributeValue::s);
}
}
@@ -14,7 +14,9 @@ import io.lettuce.core.RedisException;
import io.lettuce.core.ScriptOutputType;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -29,9 +31,13 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.MetadataDirective;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
public class ProfilesManager {
@@ -44,6 +50,7 @@ public class ProfilesManager {
private final Profiles profilesV1;
private final ProfilesV2 profilesV2;
private final ProfileAvatars profileAvatars;
private final FaultTolerantRedisClusterClient cacheCluster;
private final ScheduledExecutorService retryExecutor;
private final S3AsyncClient s3Client;
@@ -57,17 +64,19 @@ public class ProfilesManager {
public ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final ProfileAvatars profileAvatars,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket) throws IOException {
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
this(profilesV1, profilesV2, profileAvatars, cacheCluster, retryExecutor, s3Client, bucket,
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
}
@VisibleForTesting
ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final ProfileAvatars profileAvatars,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
@@ -75,6 +84,7 @@ public class ProfilesManager {
final ClusterLuaScript setLuaScript) {
this.profilesV1 = profilesV1;
this.profilesV2 = profilesV2;
this.profileAvatars = profileAvatars;
this.cacheCluster = cacheCluster;
this.retryExecutor = retryExecutor;
this.s3Client = s3Client;
@@ -124,12 +134,10 @@ public class ProfilesManager {
redisSet(uuid, versionedProfile, versionedProfileV1);
}
/**
* Delete all profiles for the given uuid.
* <p>
* Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
* deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
*/
/// Delete all profiles for the given uuid.
///
/// Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
/// deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
@@ -149,7 +157,7 @@ public class ProfilesManager {
.bucket(bucket)
.key(avatar)
.build())
.handle((ignored, throwable) -> {
.whenComplete((_, throwable) -> {
final String outcome;
if (throwable != null) {
logger.warn("Error deleting avatar", throwable);
@@ -159,7 +167,6 @@ public class ProfilesManager {
}
Metrics.counter(DELETE_AVATAR_COUNTER_NAME, "outcome", outcome).increment();
return null;
})
.thenRun(Util.NOOP);
}
@@ -284,4 +291,51 @@ public class ProfilesManager {
static byte[] getCacheKeyV1(UUID uuid) {
return (CACHE_PREFIX_V1 + '{' + uuid.toString() + '}').getBytes();
}
public void deleteAvatarForIdentity(final byte[] identity) {
profileAvatars.deleteAvatarUrl(identity).ifPresent(avatar -> Mono.fromFuture(() ->
deleteAvatar(avatar))
.retry(3)
.onErrorComplete()
.block());
}
/// Sets an avatar for the identity. If there was already an avatar, it will be deleted from storage.
public void setAvatarForIdentity(byte[] identity, String avatar) {
profileAvatars.setAvatarUrl(identity, avatar).map(previousAvatar -> Mono.fromFuture(() ->
deleteAvatar(previousAvatar))
.retry(3)
.onErrorComplete()
.block());
}
public Optional<String> extendAvatarTtlForIdentity(final byte[] identity) {
final Optional<String> maybePath = profileAvatars.updateAvatarTtl(identity);
return maybePath.map(key -> {
try {
// copying the object to itself extends the expiration...
Mono.fromFuture(() -> s3Client.copyObject(CopyObjectRequest.builder()
.sourceBucket(bucket)
.sourceKey(key)
.destinationBucket(bucket)
.destinationKey(key)
.metadataDirective(MetadataDirective.REPLACE)
// ...but there needs to be a trivial change, otherwise it is rejected
.metadata(Map.of("t", String.valueOf(Instant.now().getEpochSecond())))
.build()))
.retryWhen(Retry.max(3).filter(e -> !(e instanceof NoSuchKeyException)))
.block();
return key;
} catch (NoSuchKeyException _) {
logger.warn("avatar expected to be present is gone");
profileAvatars.deleteAvatarUrl(identity);
return null;
}
});
}
}
@@ -9,10 +9,14 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.adapter.JdkFlowAdapter;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
public class RedisDynamoDbMessageStream implements MessageStream {
@@ -25,6 +29,14 @@ public class RedisDynamoDbMessageStream implements MessageStream {
private final RedisDynamoDbMessagePublisher messagePublisher;
private static final String MESSAGE_READ_COUNTER_NAME =
name(RedisDynamoDbMessageStream.class, "messagesRead");
private static final String MESSAGE_ACKNOWLEDGED_COUNTER_NAME =
name(RedisDynamoDbMessageStream.class, "messagesAcknowledged");
private static final String UUID_VERSION_TAG = "uuidVersion";
public RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
final MessagesCache messagesCache,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
@@ -54,11 +66,22 @@ public class RedisDynamoDbMessageStream implements MessageStream {
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
return messagePublisher;
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
.doOnNext(messageStreamEntry -> {
if (messageStreamEntry instanceof MessageStreamEntry.Envelope(org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope message)) {
final UUID messageGuid = UUIDUtil.fromByteString(message.getServerGuid());
Metrics.counter(MESSAGE_READ_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
.increment();
}
}));
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
Metrics.counter(MESSAGE_ACKNOWLEDGED_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
.increment();
return messagesCache.remove(accountIdentifier, device.getId(), messageGuid)
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
.orElseGet(() ->
@@ -12,7 +12,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -23,26 +22,25 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
/**
@@ -105,16 +103,23 @@ public class SubscriptionManager {
* already exists, its last access time will be updated.
*
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
* @param createPermitted Whether creating a new subscriber is permitted if one does not exist
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
* @throws SubscriberIdCreationNotPermittedException if a new subscriber ID would be created, but the caller does not permit it
*/
public void updateSubscriber(final SubscriberCredentials subscriberCredentials)
throws SubscriptionForbiddenException {
public void updateSubscriber(final SubscriberCredentials subscriberCredentials, final boolean createPermitted)
throws SubscriptionForbiddenException, SubscriberIdCreationNotPermittedException {
final Subscriptions.GetResult getResult =
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
throw new SubscriptionForbiddenException("subscriberId mismatch");
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
if (!createPermitted) {
throw new SubscriberIdCreationNotPermittedException();
}
// create a customer and write it to ddb
final Subscriptions.Record updatedRecord = subscriptions.create(subscriberCredentials.subscriberUser(),
subscriberCredentials.hmac(),
@@ -5,7 +5,23 @@ import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -13,28 +29,60 @@ import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import javax.annotation.Nullable;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
/// catching up to end-of-queue,and an infinite stream for live updates.
class FoundationDbMessagePublisher {
private final Database database;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
private final Clock clock;
/// Keeps track of the key from which to start reading on the next iteration
private volatile KeySelector beginKeyCursor;
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
private final KeySelector endKeyExclusive;
/// Keeps track of the key from which to start reading on the next iteration
private volatile KeySelector beginKeyCursor;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
@Nullable private final byte[] presenceKey;
// An ID for this specific stream for use when checking "ownership" of a presence value.
private final int streamId = NEXT_STREAM_ID.getAndIncrement();
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
@Nullable private final byte[] messagesAvailableWatchKey;
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
/// is started for the page fetch operations.
private final Supplier<Consumer<Transaction>> beforePageFetch;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
private State state = State.MESSAGES_AVAILABLE;
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
/// Reference to the sink we publish messages to.
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
/// A future for refreshing the connected client's presence value at regular intervals.
@Nullable private ScheduledFuture<?> renewPresenceFuture;
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
enum State {
/// Messages are likely available in the queue. Initial state.
@@ -70,49 +118,52 @@ class FoundationDbMessagePublisher {
FETCH_OR_PUBLISH_ERROR_OCCURRED
}
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
@Nullable private final byte[] messagesAvailableWatchKey;
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
/// is started for the page fetch operations.
private final Supplier<Consumer<Transaction>> beforePageFetch;
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
private State state = State.MESSAGES_AVAILABLE;
/// Reference to the sink we publishes messages to.
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
FoundationDbMessagePublisher(
final Database database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
@Nullable final byte[] presenceKey,
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
@Nullable final byte[] messagesAvailableWatchKey,
@Nullable final BiConsumer<State, State> stateChangeListener,
final Supplier<Consumer<Transaction>> beforePageFetch) {
this.database = database;
this.clock = clock;
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.database = database;
this.maxMessagesPerScan = maxMessagesPerScan;
this.presenceKey = presenceKey;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
this.beforePageFetch = beforePageFetch;
this.messagePublisher = Flux.create(emitter -> {
if (!terminateOnQueueEmpty) {
Objects.requireNonNull(presenceKey);
Objects.requireNonNull(presenceRenewalExecutorService);
}
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
this.emitter = emitter;
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
emitter.onDispose(this::onDispose);
}).doOnSubscribe(_ -> {
if (!terminateOnQueueEmpty) {
// Establish presence immediately and block until we do. We must establish presence for watches to work as
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
// exception.
database.run(transaction -> {
setPresence(transaction);
return null;
});
// Refresh presence at regular intervals
startPresenceRenewal(presenceRenewalExecutorService);
}
});
}
@@ -121,18 +172,22 @@ class FoundationDbMessagePublisher {
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
public static FoundationDbMessagePublisher createFinitePublisher(
final Database database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
final Supplier<Consumer<Transaction>> beforePageFetch) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
return new FoundationDbMessagePublisher(database,
clock,
beginKeyInclusive,
endKeyExclusive,
database,
maxMessagesPerScan,
null,
null,
null,
null,
beforePageFetch);
}
@@ -140,17 +195,23 @@ class FoundationDbMessagePublisher {
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
/// messages and is now waiting for a live stream of new messages.
public static FoundationDbMessagePublisher createInfinitePublisher(
final Database database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
final byte[] presenceKey,
final ScheduledExecutorService presenceRenewalExecutorService,
final byte[] messagesAvailableWatchKey,
final Supplier<Consumer<Transaction>> beforePageFetch) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
return new FoundationDbMessagePublisher(database,
clock,
beginKeyInclusive,
endKeyExclusive,
database,
maxMessagesPerScan,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
null,
beforePageFetch);
@@ -192,6 +253,7 @@ class FoundationDbMessagePublisher {
setState(State.MESSAGES_AVAILABLE, event);
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
}
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> setState(State.MESSAGE_AVAILABLE_SIGNAL_BUFFERED, event);
case FETCH_OR_PUBLISH_ERROR_OCCURRED -> setState(State.ERROR, event);
default -> knownTransition = false;
}
@@ -247,27 +309,33 @@ class FoundationDbMessagePublisher {
///
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
return database.runAsync(transaction -> {
doBeforePageFetch.accept(transaction);
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
.thenApply(lastKeyReadAndItems -> {
// Set our beginning key to just past the last key read so that we're ready for our next fetch
lastKeyReadAndItems.first()
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
final List<FoundationDbMessageStreamEntry.Message> items = lastKeyReadAndItems.second();
if (items.size() < maxMessagesPerScan) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
if (!terminateOnQueueEmpty) {
setWatch(transaction);
}
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
setWatch(transaction);
}
return items;
});
}
);
return lastKeyReadAndItems;
});
})
// Defer any state mutations until after the transaction has been committed. The transaction block can
// fail/retry, and we don't want to trigger spurious state transitions when that happens.
.thenApply(lastKeyReadAndItems -> {
// Set our beginning key to just past the last key read so that we're ready for our next fetch
lastKeyReadAndItems.first()
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
}
return lastKeyReadAndItems.second();
});
}
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
@@ -338,15 +406,6 @@ class FoundationDbMessagePublisher {
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
}
private synchronized void onDispose() {
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
// in evaluating the state machine when there's no live subscription.
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
}
cancelWatch();
}
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
private synchronized void cancelWatch() {
@@ -355,4 +414,76 @@ class FoundationDbMessagePublisher {
}
}
private synchronized void startPresenceRenewal(final ScheduledExecutorService presenceRenewalExecutorService) {
final long renewalIntervalMillis =
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
renewPresenceFuture = presenceRenewalExecutorService.scheduleWithFixedDelay(this::renewPresence,
renewalIntervalMillis,
renewalIntervalMillis,
TimeUnit.MILLISECONDS);
}
private synchronized void renewPresence() {
if (state == State.TERMINATED || state == State.ERROR) {
return;
}
database.runAsync(transaction -> {
setPresence(transaction);
return CompletableFuture.completedFuture(null);
})
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to renew presence; will terminate publisher", throwable);
terminateWithError(throwable);
}
});
}
private void setPresence(final Transaction transaction) {
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
}
@VisibleForTesting
synchronized void clearPresence() {
if (renewPresenceFuture != null) {
renewPresenceFuture.cancel(true);
}
if (!terminateOnQueueEmpty) {
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
transaction.clear(presenceKey);
}
}))
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear presence on disposal", throwable);
}
});
}
}
@VisibleForTesting
synchronized void terminateWithError(final Throwable throwable) {
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.ERROR, Event.INTERNAL_TRIGGER);
}
emitter.error(throwable);
}
private synchronized void onDispose() {
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
// in evaluating the state machine when there's no live subscription.
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
}
cancelWatch();
clearPresence();
}
}
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.Range;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.subspace.Subspace;
import com.apple.foundationdb.tuple.Tuple;
@@ -9,28 +10,32 @@ import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.Hashing;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
/// An implementation of a message store backed by FoundationDB.
@@ -47,12 +52,20 @@ import org.whispersystems.textsecuregcm.util.Util;
public class FoundationDbMessageStore {
private final Database[][] databasesByEpoch;
private final Map<Database, VersionstampClock> versionstampClocks;
private final int[] liveEpochs;
private final int activeEpoch;
private final VersionstampUUIDCipher versionstampUUIDCipher;
private final ScheduledExecutorService presenceRenewalExecutorService;
private final Clock clock;
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
private static final int PRESENCE_VALUE_LENGTH = 28;
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
private static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
@VisibleForTesting
static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
/// The (approximate) transaction size beyond which we do not add more messages in a transaction. The estimated size
/// includes only message payloads (and not key reads/writes) which we assume will dominate the total
@@ -71,12 +84,6 @@ public class FoundationDbMessageStore {
private static final Timer INSERT_MESSAGE_BATCH_TIMER =
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessageBatchTimer"));
private static final Counter DELETE_MESSAGE_COUNTER =
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessage"));
private static final Timer DELETE_MESSAGE_TIMER =
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessageTimer"));
/// Result of inserting a message for a particular device
///
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
@@ -88,19 +95,31 @@ public class FoundationDbMessageStore {
boolean present) {
}
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpoch,
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
final int activeEpoch,
final VersionstampUUIDCipher versionstampUUIDCipher,
final ScheduledExecutorService presenceRenewalExecutorService,
final Clock clock) {
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
databasesByEpoch.forEach((epoch, databases) ->
databasesByEpochMap.forEach((epoch, databases) ->
databasesByEpochArray[epoch] = databases.toArray(Database[]::new));
this.databasesByEpoch = databasesByEpochArray;
this.liveEpochs = IntStream.range(0, MAX_EPOCHS).filter(e -> databasesByEpochArray[e] != null).toArray();
this.activeEpoch = activeEpoch;
this.versionstampUUIDCipher = versionstampUUIDCipher;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.versionstampClocks = databasesByEpochMap.values().stream()
.flatMap(List::stream)
.distinct()
.collect(Collectors.toMap(Function.identity(),
db -> new VersionstampClock(db, clock),
(_, _) -> {
throw new AssertionError("Source stream had duplicates after distinct()");
},
IdentityHashMap::new));
this.clock = clock;
}
@@ -324,27 +343,6 @@ public class FoundationDbMessageStore {
});
}
// Note that this method is intended only for initial migration support; in general, callers should clear messages
// by acknowledging messages via a `FoundationDbMessageStream`.
public CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
}
private CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
final Timer.Sample sample = Timer.start();
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
transaction.clear(messageKey);
return CompletableFuture.completedFuture(null);
})
.thenRun(() -> {
sample.stop(DELETE_MESSAGE_TIMER);
DELETE_MESSAGE_COUNTER.increment();
});
}
public void clearAll(final AciServiceIdentifier aci) {
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
transaction.clear(getAccountSubspace(aci).range());
@@ -367,14 +365,14 @@ public class FoundationDbMessageStore {
.forEach(action);
}
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
}
@VisibleForTesting
MessageStream getMessages(final AciServiceIdentifier aci,
final Device destinationDevice,
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
final byte deviceId,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
@@ -382,19 +380,74 @@ public class FoundationDbMessageStore {
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length];
for (int epoch = 0; epoch < databasesByEpoch.length; epoch++) {
databasesForQueueByEpoch[epoch] = databasesByEpoch[epoch] != null
? getDatabases(epoch)[hashAciToShardNumber(aci, epoch)]
: null;
for (final int epoch : liveEpochs) {
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
}
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
getPresenceKey(aci, deviceId),
getMessagesAvailableWatchKey(aci),
databasesForQueueByEpoch,
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
maxMessagesPerScan,
maxUnacknowledgedMessages,
doAfterCleanup);
doAfterCleanup,
presenceRenewalExecutorService,
clock);
}
/// Record the versionstamp for the current time in each database's versionstamp clock.
public void recordVersionstamps() {
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
versionstampClock.recordVersionstampAndTime();
}
}
/// Delete messages for the given devices that were inserted before the given time.
///
/// This issues one range delete for every account/device pair in the map for each actual underlying FoundationDB
/// cluster that ever hosted that account in a configured epoch (not just the current epoch). While range deletes are
/// efficient, they can potentially induce significant load on the storage process, so callers should be judicious
/// with flow control when calling this method.
///
/// @param accountDeviceIdentifiers a map from ACI to the list of device IDs for which expired messages should be
/// trimmed. Note that, depending on the sharding schema of the configured message store, it is possible that we will
/// issue a range clear for every device in a single transaction. One range clear involves two keys, each of which has
/// an ACI, device ID, and versionstamp, along with overhead to identify the relevant subspace; given the 10MB
/// transaction limit and a healthy margin for safety, this means there should be well under 100,000 total
/// account/device pairs supplied in a single call to this method.
///
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
/// date.
@VisibleForTesting
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
accountDeviceIdentifiers.forEach((aci, deviceIds) -> {
for (final byte deviceId : deviceIds) {
final Subspace queueSubspace = getDeviceQueueSubspace(aci, deviceId);
IntStream.of(liveEpochs)
.mapToObj(e -> getShardForAci(aci, e))
.distinct()
.forEach(database -> queueSubspacesToTrimByDatabase.computeIfAbsent(database, _ -> new ArrayList<>()).add(queueSubspace));
}
});
queueSubspacesToTrimByDatabase.forEach((database, queueSubspaces) -> {
// It's OK that this puts reading the versionstamp in a separate transaction from the deletes; versionstamp clock
// entries are effectively immutable and we're looking for one that was written presumably very far in the past,
// so there's no conflict to avoid
versionstampClocks.get(database).getVersionstamp(cutoffTime).ifPresent(cutoffVersionstamp -> {
database.run(transaction -> {
transaction.options().setPriorityBatch();
for (final Subspace queueSubspace : queueSubspaces) {
transaction.clear(new Range(queueSubspace.getKey(), queueSubspace.pack(Tuple.from(cutoffVersionstamp))));
}
return null;
});
});
});
}
static Versionstamp getVersionstamp(final byte[] messageKey) {
@@ -463,19 +516,56 @@ public class FoundationDbMessageStore {
}
@VisibleForTesting
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).pack("p");
static byte[] getServerId() {
return SERVER_ID;
}
@VisibleForTesting
boolean isClientPresent(final byte[] presenceValueBytes) {
if (presenceValueBytes == null) {
static byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).pack("p");
}
static byte[] getPresenceValue(final Instant timestamp, final int streamId) {
return ByteBuffer.allocate(PRESENCE_VALUE_LENGTH)
.put(SERVER_ID)
.putInt(streamId)
.putLong(timestamp.toEpochMilli())
.array();
}
@VisibleForTesting
static byte[] getPresenceServerId(final byte[] presenceValue) {
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
}
return Arrays.copyOfRange(presenceValue, 0, 16);
}
@VisibleForTesting
static int getPresenceStreamId(final byte[] presenceValue) {
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
}
return ByteBuffer.wrap(presenceValue).getInt(16);
}
@VisibleForTesting
static Instant getPresenceTimestamp(final byte[] presenceValue) {
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
}
return Instant.ofEpochMilli(ByteBuffer.wrap(presenceValue).getLong(20));
}
@VisibleForTesting
boolean isClientPresent(@Nullable final byte[] presenceValue) {
if (presenceValue == null) {
return false;
}
final long presenceValue = Conversions.byteArrayToLong(presenceValueBytes);
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
// containing the timestamp (seconds since epoch) that the client updates periodically.
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= PRESENCE_STALE_THRESHOLD.toSeconds();
return Duration.between(getPresenceTimestamp(presenceValue), clock.instant()).compareTo(PRESENCE_STALE_THRESHOLD) <= 0;
}
}
@@ -13,6 +13,7 @@ import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IdentityHashMap;
@@ -23,6 +24,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;
@@ -41,6 +43,7 @@ import reactor.util.function.Tuples;
public class FoundationDbMessageStream implements MessageStream {
private final Subspace deviceQueueSubspace;
private final byte[] presenceKey;
private final byte[] messagesAvailableWatchKey;
private final Database[] databasesByEpoch;
private final MessageGuidCodec messageGuidCodec;
@@ -48,12 +51,21 @@ public class FoundationDbMessageStream implements MessageStream {
private final int maxMessagesPerScan;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
private final ScheduledExecutorService presenceRenewalExecutorService;
private final Clock clock;
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
private final Counter messageReadCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
private final Counter messageAcknowledgedCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "messagesAcknowledged"));
private final Counter staleEphemeralMessagesCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 100;
@VisibleForTesting
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
@@ -63,19 +75,25 @@ public class FoundationDbMessageStream implements MessageStream {
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
final byte[] presenceKey,
final byte[] messagesAvailableWatchKey,
final Database[] databasesByEpoch,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
final Runnable doAfterCleanup,
final ScheduledExecutorService presenceRenewalExecutorService,
final Clock clock) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.presenceKey = presenceKey;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.databasesByEpoch = databasesByEpoch;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.clock = clock;
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
@@ -116,6 +134,11 @@ public class FoundationDbMessageStream implements MessageStream {
sink.next(messageStreamEntry);
})
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
.doOnNext(messageStreamEntry -> {
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
messageReadCounter.increment();
}
})
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
}
@@ -149,9 +172,10 @@ public class FoundationDbMessageStream implements MessageStream {
return maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
database,
clock,
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive,
database,
maxMessagesPerScan,
() -> this.clearAcknowledgedMessages(database))
.getMessages())
@@ -178,10 +202,13 @@ public class FoundationDbMessageStream implements MessageStream {
.orElseGet(() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
return FoundationDbMessagePublisher.createInfinitePublisher(
database,
clock,
infinitePublisherBeginKey,
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
database,
maxMessagesPerScan,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
() -> clearAcknowledgedMessages(database)).getMessages();
})
@@ -225,6 +252,8 @@ public class FoundationDbMessageStream implements MessageStream {
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
messageAcknowledgedCounter.increment();
return CompletableFuture.completedFuture(null);
}
@@ -133,7 +133,7 @@ public class AppleAppStoreClient {
final APIError apiError = e.getApiError();
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", apiError != null ? apiError.name() : "http_" + e.getHttpStatusCode())).increment();
throw switch (e.getApiError()) {
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> new SubscriptionNotFoundException();
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
case null, default -> throw e;
@@ -183,7 +183,7 @@ public class AppleAppStoreClient {
private static boolean shouldRetry(Throwable e) {
return e instanceof APIException apiException && switch (apiException.getApiError()) {
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE, ACCOUNT_NOT_FOUND_RETRYABLE -> true;
case null, default -> false;
};
}
@@ -128,7 +128,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return paymentMethod == PaymentMethod.PAYPAL;
}
public CompletableFuture<PaymentDetails> getPaymentDetails(final String paymentId) {
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentId) {
return CompletableFuture.supplyAsync(() -> {
try {
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
@@ -136,14 +136,14 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
chargeFailure = createChargeFailure(transaction);
}
return new PaymentDetails(transaction.getGraphQLId(),
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
transaction.getCustomFields(),
getPaymentStatus(transaction.getStatus()),
transaction.getCreatedAt().toInstant(),
chargeFailure);
chargeFailure));
} catch (final NotFoundException e) {
return null;
return Optional.empty();
}
}, executor);
}
@@ -242,7 +242,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}, executor);
}
public CompletableFuture<PaymentDetails> getPaymentDetails(String paymentIntentId) {
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentIntentId) {
return CompletableFuture.supplyAsync(() -> {
try {
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
@@ -255,14 +255,14 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
return new PaymentDetails(paymentIntent.getId(),
return Optional.of(new PaymentDetails(paymentIntent.getId(),
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
getPaymentStatusForStatus(paymentIntent.getStatus()),
Instant.ofEpochSecond(paymentIntent.getCreated()),
chargeFailure);
chargeFailure));
} catch (StripeException e) {
if (e.getStatusCode() == 404) {
return null;
return Optional.empty();
} else {
throw new CompletionException(e);
}
@@ -0,0 +1,13 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
public class SubscriberIdCreationNotPermittedException extends SubscriptionException {
public SubscriberIdCreationNotPermittedException() {
super(null);
}
}
@@ -38,6 +38,8 @@ public final class HeaderUtils {
public static final String GROUP_SEND_TOKEN = "Group-Send-Token";
public static final String DONATION_PERMIT = "Donation-Permit";
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = MetricsUtil.name(HeaderUtils.class,
"invalidAcceptLanguage");
@@ -0,0 +1,56 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Base64;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
public class ZkCredentialPublicKeyAdapter {
public static class Serializer extends JsonSerializer<ZkCredentialPublicKey> {
@Override
public void serialize(final ZkCredentialPublicKey zkCredentialPublicKey,
final JsonGenerator jsonGenerator,
final SerializerProvider serializers) throws IOException {
jsonGenerator.writeString(Base64.getEncoder().encodeToString(zkCredentialPublicKey.serialize()));
}
}
public static class Deserializer extends JsonDeserializer<ZkCredentialPublicKey> {
@Override
public ZkCredentialPublicKey deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
final byte[] zkCredentialPublicKeyBytes;
try {
zkCredentialPublicKeyBytes = Base64.getDecoder().decode(parser.getValueAsString());
} catch (final IllegalArgumentException e) {
throw new JsonParseException(parser, "Could not parse key as a base64-encoded value", e);
}
if (zkCredentialPublicKeyBytes.length == 0) {
return null;
}
try {
return new ZkCredentialPublicKey(zkCredentialPublicKeyBytes);
} catch (final InvalidInputException e) {
// this should really never happen, as ZkCredentialPublicKey simply extends ByteArray
throw new JsonParseException(parser, "Could not interpret bytes as a ZK credential public key", e);
}
}
}
}
@@ -69,6 +69,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
@@ -220,6 +221,8 @@ public record CommandDependencies(
.threads(1).build();
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
.threads(1).build();
final ScheduledExecutorService presenceRenewalExecutor =
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(1).build();
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
configuration.getSecureStorageServiceConfiguration());
@@ -266,6 +269,8 @@ public record CommandDependencies(
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV1().getTableName());
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
configuration.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV2().getTableName());
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
@@ -313,8 +318,9 @@ public record CommandDependencies(
configuration.getFoundationDbMessagesConfiguration().activeEpoch(),
new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
configuration.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
presenceRenewalExecutor,
Clock.systemUTC());
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getReportMessage().getTableName(),
@@ -34,17 +34,17 @@ service KeyTransparencyQueryService {
* subsequent Search and Monitor requests. It should be the first key
* transparency RPC a client calls.
*/
rpc Distinguished(DistinguishedRequest) returns (DistinguishedResponse) {}
rpc DistinguishedV2(DistinguishedRequest) returns (DistinguishedResponse) {}
/**
* An endpoint used by clients to search for one or more identifiers in the transparency log.
* The server returns proof that the identifier(s) exist in the log.
*/
rpc Search(SearchRequest) returns (SearchResponse) {}
rpc SearchV2(SearchRequest) returns (SearchResponseV2) {}
/**
* An endpoint that allows users to monitor a group of identifiers by returning proof that the log continues to be
* constructed correctly in later entries for those identifiers.
*/
rpc Monitor(MonitorRequest) returns (MonitorResponse) {}
rpc MonitorV2(MonitorRequest) returns (MonitorResponseV2) {}
}
message SearchRequest {
@@ -112,6 +112,19 @@ message SearchResponse {
optional CondensedTreeSearchResponse username_hash = 4;
}
/**
* Indicates that the client is not authorized to make the request because
* it did not provide the correct set of data.
*/
message PermissionDenied {}
message SearchResponseV2 {
oneof response {
SearchResponse search_response = 1;
PermissionDenied permission_denied = 2;
}
}
/**
* The tree head size(s) to prove consistency against. A client's very first
* key transparency request should be looking up the "distinguished" key;
@@ -124,13 +137,11 @@ message ConsistencyParameters {
* This field may be omitted if the client is looking up an identifier
* for the first time.
*/
optional uint64 last = 1;
optional uint64 last = 1 [(org.signal.chat.require.range) = {min: 1}];
/**
* The distinguished tree head size to prove consistency against.
* This field may be omitted when the client is looking up the
* "distinguished" key for the very first time.
*/
optional uint64 distinguished = 2;
uint64 distinguished = 2 [(org.signal.chat.require.range) = {min: 1}];
}
/**
@@ -143,7 +154,7 @@ message DistinguishedRequest {
* exception of a client's very first request, this field should always be
* set.
*/
optional uint64 last = 1;
optional uint64 last = 1 [(org.signal.chat.require.range) = {min: 1}];
}
/**
@@ -343,20 +354,20 @@ message MonitorRequest {
message AciMonitorRequest {
bytes aci = 1 [(org.signal.chat.require.exactlySize) = 16];
uint64 entry_position = 2;
uint64 entry_position = 2 [(org.signal.chat.require.range) = {min: 1}];
bytes commitment_index = 3 [(org.signal.chat.require.exactlySize) = 32];
}
message UsernameHashMonitorRequest {
bytes username_hash = 1 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 32];
uint64 entry_position = 2;
bytes commitment_index = 3 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 32];
bytes username_hash = 1 [(org.signal.chat.require.exactlySize) = 32];
uint64 entry_position = 2 [(org.signal.chat.require.range) = {min: 1}];
bytes commitment_index = 3 [(org.signal.chat.require.exactlySize) = 32];
}
message E164MonitorRequest {
optional string e164 = 1 [(org.signal.chat.require.e164) = true];
uint64 entry_position = 2;
bytes commitment_index = 3 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 32];
string e164 = 1 [(org.signal.chat.require.e164) = true];
uint64 entry_position = 2 [(org.signal.chat.require.range) = {min: 1}];
bytes commitment_index = 3 [(org.signal.chat.require.exactlySize) = 32];
}
message MonitorProof {
@@ -397,3 +408,10 @@ message MonitorResponse {
*/
repeated bytes inclusion = 5;
}
message MonitorResponseV2 {
oneof response {
MonitorResponse monitor_response = 1;
PermissionDenied permission_denied = 2;
}
}
@@ -49,3 +49,8 @@ The chat server may return the following errors from any RPC
When logging error responses, clients may always log the status code, domain, and reason.
For errors with domain `grpc.chat.signal.org` and reason `CONSTRAINT_VIOLATED`, clients should check the `details` field for a `BadRequest` proto. If present, they should log the `field` of each violation in `field_violations`.
### GOAWAY
In a partial or total server outage, the server may start rejecting new connection requests or terminating existing connections with an HTTP/2 GOAWAY frame with code 0x40.
If clients receive a 0x40 GOAWAY they should retry connections with an aggressive exponential backoff.
@@ -105,9 +105,8 @@ message ClearRegistrationLockResponse {
}
message ReserveUsernameHashRequest {
// A prioritized list of username hashes to attempt to reserve. Each hash must
// be exactly 32 bytes.
repeated bytes username_hashes = 1 [(require.size) = {min: 1, max: 20}];
// A prioritized list of username hashes to attempt to reserve.
repeated bytes username_hashes = 1 [(require.size) = {min: 1, max: 20}, (require.each) = {exactlySize: 32}];
}
message UsernameNotAvailable {}
@@ -270,7 +269,7 @@ message LookupUsernameLinkResponse {
}
message SetZkCredentialKeyRequest {
// A serialized Ristretto key with a one-byte type prefix
// A serialized libsignal ZkCredentialPublicKey
bytes public_key = 1 [(require.exactlySize) = 33];
}
@@ -21,6 +21,11 @@ service Donations {
// responses will include the corresponding badge (if configured as visible)
// until the expiration time on the receipt.
rpc RedeemReceipt(RedeemReceiptRequest) returns (RedeemReceiptResponse) {}
// Generate a set of anonymous, single-use, permits for use with /v1/subscription endpoints.
//
// If rate limited, reduce requested permit count and/or try again after the prescribed delay.
rpc CreateDonationPermit(CreateDonationPermitRequest) returns (CreateDonationPermitResponse) {}
}
message RedeemReceiptRequest {
@@ -41,5 +46,14 @@ message RedeemReceiptResponse {
// The receipt was already redeemed for a different account
errors.FailedPrecondition already_redeemed = 3 [(tag.reason) = "already_redeemed"];
}
}
message CreateDonationPermitRequest {
// a serialized libsignal DonationPermitRequest
bytes donation_permit_request = 1 [(require.nonEmpty) = true];
}
message CreateDonationPermitResponse {
// a serialized libsignal DonationPermitResponse
bytes donation_permit_response = 1;
}
@@ -385,19 +385,19 @@ message MismatchedDevices {
// A list of device IDs that are linked to the destination account, but were
// not included in the collection of messages bound for the destination
// account.
repeated uint32 missing_devices = 2 [(require.range).max = 0x7f];
repeated uint32 missing_devices = 2 [(require.each) = {range: {max: 0x7f}}];
// A list of device IDs that were included in the collection of messages bound
// for the destination account, but are not currently linked to the
// destination account.
repeated uint32 extra_devices = 3 [(require.range).max = 0x7f];
repeated uint32 extra_devices = 3 [(require.each) = {range: {max: 0x7f}}];
// A list of device IDs that present in the collection of messages bound for
// the destination account and are linked to the destination account, but have
// a different registration ID than the registration ID presented by the
// sender (indicating that the destination device has likely been replaced by
// another device).
repeated uint32 stale_devices = 4 [(require.range).max = 0x7f];
repeated uint32 stale_devices = 4 [(require.each) = {range: {max: 0x7f}}];
}
message MultiRecipientMismatchedDevices {
@@ -0,0 +1,167 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.one_time_donations;
import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/tag.proto";
import "org/signal/chat/subscriptions.proto";
// Service for making one-time donation payments (boost and gift)
//
// Note that these are siblings of the RPCs in the Subscriptions service. One-time payments do
// not require the subscription management methods in that service, though the configuration at
// Subscriptions.GetConfiguration is shared between subscription and one-time payments.
service OneTimeDonations {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Create a Stripe payment intent and return a client secret that can be used to complete the payment.
// Once the payment is complete, the paymentIntentId can be used with CreateBoostReceiptCredentials
rpc CreateBoost(CreateBoostRequest) returns (CreateBoostResponse) {}
// Create a PayPal one-time payment.
// Once the payment is complete, call ConfirmPayPalBoost with the payment ID and token
rpc CreatePayPalBoost(CreatePayPalBoostRequest) returns (CreatePayPalBoostResponse) {}
// Confirm a PayPal one-time payment
rpc ConfirmPayPalBoost(ConfirmPayPalBoostRequest) returns (ConfirmPayPalBoostResponse) {}
// Obtain a ZK receipt credential for a completed one-time donation payment.
// The receipt credential can then be used to redeem the one-time donation entitlement
// via Donations.RedeemReceipt
rpc CreateBoostReceiptCredentials(CreateBoostReceiptCredentialsRequest) returns (CreateBoostReceiptCredentialsResponse) {}
}
// The amount is below the minimum for the currency.
message AmountBelowMinimumError {
// The minimum amount for the currency
string minimum = 1;
}
// The SEPA Direct Debit amount exceeds the allowed maximum.
message AmountAboveSepaLimitError {
// The maximum amount for a SEPA transaction
string maximum = 1;
}
message CreateBoostRequest {
// ISO 4217 currency code, case-insensitive (e.g. "usd", "EUR")
string currency = 1 [(require.exactlySize) = 3];
// The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)
uint64 amount = 2 [(require.range).min = 1];
// The level for the boost payment
uint64 level = 3 [(require.range).min = 1];
// The payment method
subscriptions.PaymentMethod payment_method = 4 [(require.specified) = true];
// A donation permit retrieved from Donations.createDonationPermit
bytes donation_permit = 5 [(require.nonEmpty) = true];
}
message CreateBoostResponse {
oneof response {
// A client secret that can be used to complete a stripe PaymentIntent
string client_secret = 1;
// The amount is below the minimum for the currency
AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"];
// The amount exceeds the maximum for SEPA Direct Debit
AmountAboveSepaLimitError amount_above_sepa_limit = 3 [(tag.reason) = "amount_above_sepa_limit"];
// The requested currency is not supported for the given payment method
errors.FailedPrecondition unsupported_currency = 4 [(tag.reason) = "unsupported_currency"];
// The requested level is not a valid one-time donation level
errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"];
// Donation permit was invalid or already spent
errors.FailedZkAuthentication permit_rejected = 6 [(tag.reason) = "permit_rejected"];
}
}
message CreatePayPalBoostRequest {
// ISO 4217 currency code, case-insensitive (e.g. "usd", "EUR")
string currency = 1 [(require.exactlySize) = 3];
// Amount in the currency's minor unit (e.g. cents for USD), must be >= 1
uint64 amount = 2 [(require.range).min = 1];
// Donation level.
uint64 level = 3 [(require.range).min = 1];
// URL to redirect the user to after PayPal approval
string return_url = 4 [(require.nonEmpty) = true];
// URL to redirect the user to if they cancel
string cancel_url = 5 [(require.nonEmpty) = true];
}
message CreatePayPalBoostResponse {
message CreatePayPalBoostResult {
string approval_url = 1;
string payment_id = 2;
}
oneof response {
CreatePayPalBoostResult result = 1;
// The amount is below the minimum for the currency
AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"];
// The requested currency is not supported for PayPal
errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"];
// The requested level is not a valid one-time donation level
errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"];
}
}
message ConfirmPayPalBoostRequest {
// ISO 4217 currency code, case-insensitive (e.g. "usd", "EUR")
string currency = 1 [(require.exactlySize) = 3];
// Amount in the currency's minor unit, must be >= 1
uint64 amount = 2 [(require.range).min = 1];
// Donation level.
uint64 level = 3 [(require.range).min = 1];
// PayPal payer ID from the approval redirect
string payer_id = 4 [(require.nonEmpty) = true];
// PayPal payment ID (PAYID-…) from CreatePayPalBoost
string payment_id = 5 [(require.nonEmpty) = true];
// PayPal payment token (EC-…) from the approval redirect
string payment_token = 6 [(require.nonEmpty) = true];
}
message ConfirmPayPalBoostResponse {
message ConfirmPayPalBoostResult {
string payment_id = 1;
}
oneof response {
ConfirmPayPalBoostResult result = 1;
// The amount is below the minimum for the currency
AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"];
// The requested currency is not supported for PayPal
errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"];
// The requested level is not a valid one-time donation level
errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"];
}
}
message CreateBoostReceiptCredentialsRequest {
// a payment ID from the processor
string payment_intent_id = 1 [(require.nonEmpty) = true];
// ZK blind-signature receipt credential request bytes
bytes receipt_credential_request = 2 [(require.nonEmpty) = true];
// The processor that handled the payment
subscriptions.PaymentProvider processor = 3 [(require.specified) = true];
}
message CreateBoostReceiptCredentialsResponse {
message CreateBoostReceiptCredentialsResult {
bytes receipt_credential_response = 1;
}
oneof response {
CreateBoostReceiptCredentialsResult result = 1;
// Payment is still processing; client should retry
errors.FailedPrecondition payment_still_processing = 2 [(tag.reason) = "payment_still_processing"];
// Payment failed
subscriptions.PaymentRequired payment_required = 3 [(tag.reason) = "payment_required"];
// Payment intent not found
errors.NotFound payment_not_found = 4 [(tag.reason) = "payment_not_found"];
// A receipt credential was already issued for this payment
errors.FailedPrecondition receipt_already_issued = 5 [(tag.reason) = "receipt_already_issued"];
}
}
@@ -9,6 +9,8 @@ option java_multiple_files = true;
package org.signal.chat.profile;
import "google/protobuf/empty.proto";
import "org/signal/chat/common.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/require.proto";
@@ -26,6 +28,11 @@ service Profile {
// Retrieves unversioned profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
// Returns anonymous credentials that may be presented with avatar operations in ProfilesAnonymous
//
// Note: `Accounts.SetZkCredentialKey` is a pre-requisite for this RPC
rpc GetAvatarCredentials(GetAvatarCredentialsRequest) returns (GetAvatarCredentialsResponse) {}
}
// Provides methods for working with profiles and profile-related data using "unidentified access"
@@ -41,6 +48,24 @@ service ProfileAnonymous {
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {}
// Retrieves a profile key credential.
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {}
// Returns credentials to upload a v2 avatar. After uploading the avatar, the client
// must call SetProfile with the new avatar URL in the encrypted `data`.
//
// Because avatars are uploaded anonymously, they have an expiration equal to the
// idle account expiration. Clients must periodically (recommended: every 90 days)
// call ExtendAvatarTTL to extend the TTl.
//
// Note: any existing avatar associated with these credentials will be deleted immediately
rpc GetAvatarUploadForm(GetAvatarUploadFormRequest) returns (GetAvatarUploadFormResponse) {}
// Extends the TTL of the avatar currently associated with the request’s avatar auth credential
rpc ExtendAvatarTTL(ExtendAvatarTTLRequest) returns (ExtendAvatarTTLResponse) {}
// Deletes the avatar currently associated with the request’s avatar auth credential.
//
// Clients must also call SetProfile to remove the avatar from the encrypted `data`.
rpc DeleteAvatar(DeleteAvatarRequest) returns (DeleteAvatarResponse) {}
}
message SetProfileV1Request {
@@ -325,3 +350,59 @@ enum CredentialType {
CREDENTIAL_TYPE_UNSPECIFIED = 0;
CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY = 1;
}
// avatar auth
message GetAvatarCredentialsRequest {
bytes avatar_credentials_request = 1;
}
message GetAvatarCredentialsResponse {
oneof response {
bytes avatar_credentials = 1;
// the client must call Accounts.SetZkCredentialKey to call this method
errors.FailedPrecondition missing_zk_credential_key = 2 [(tag.reason) = "missing_zk_credential_key"];
}
}
message GetAvatarUploadFormRequest {
bytes avatar_credentials_presentation = 1;
// The length of the attachment for the requested upload form. Uploads
// performed with this form will be limited to the provided length.
uint32 upload_length = 2 [(require.range) = {min: 1, max: 10485760 /* 10 MiB */}];
}
message GetAvatarUploadFormResponse {
oneof response {
common.S3UploadForm avatar_upload_form = 1;
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
}
}
message ExtendAvatarTTLRequest {
bytes avatar_credentials_presentation = 1;
}
message ExtendAvatarTTLResponse {
oneof response {
// The avatar that was extended. May be used as a check against state de-synchronization.
string path = 1;
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
// the identity does not have an active avatar
errors.NotFound not_found = 3 [(tag.reason) = "no_active_avatar"];
}
}
message DeleteAvatarRequest {
bytes avatar_credentials_presentation = 1;
}
message DeleteAvatarResponse {
oneof response {
google.protobuf.Empty success = 1;
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
}
}
@@ -178,7 +178,40 @@ extend google.protobuf.FieldOptions {
*/
optional IdentityType identityType = 70009;
// next 70010
/*
* Applies element-wise constraints to the elements of a `repeated` field.
* Top-level `require.*` annotations on a `repeated` field constrain the
* collection itself (e.g. element count), `each` constrains the
* individual elements.
*
* ```
* import "org/signal/chat/require.proto";
*
* message Data {
* // 1-20 username hashes, each exactly 32 bytes
* repeated bytes username_hashes = 1 [
* (require.size) = {min: 1, max: 20},
* (require.each) = { exactlySize: 32 }
* ];
* }
* ```
*
* Applicable only to `repeated` fields.
*/
optional ElementConstraint each = 70010;
// next 70011
}
message ElementConstraint {
optional bool nonEmpty = 1;
optional SizeConstraint size = 2;
repeated uint32 exactlySize = 3;
optional bool e164 = 4;
optional bool base64url = 5;
optional ValueRangeConstraint range = 6;
optional IdentityType identityType = 7;
optional bool specified = 8;
}
message SizeConstraint {
@@ -108,7 +108,10 @@ service Subscriptions {
}
message UpdateSubscriberRequest {
bytes subscriberId = 1 [(require.exactlySize) = 32];
bytes subscriber_id = 1 [(require.exactlySize) = 32];
// A libsignal DonationPermit from rpc Donations.CreateDonationPermit.
// Not required if the subscriber already exists.
bytes donation_permit = 2;
}
message UpdateSubscriberResponse {
@@ -116,6 +119,8 @@ message UpdateSubscriberResponse {
google.protobuf.Empty success = 1;
// subscriberId authentication failure
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 2 [(tag.reason) = "subscriber_id_mismatch"];
// The donation permit was expired or already spent
errors.FailedZkAuthentication permit_rejected = 3 [(tag.reason) = "permit_rejected"];
}
}
@@ -171,8 +176,10 @@ enum SubscriptionStatus {
message CreatePaymentMethodRequest {
// Only PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, and PAYMENT_METHOD_IDEAL are supported;
// other values will result in an INVALID_ARGUMENT error.
bytes subscriberId = 1 [(require.exactlySize) = 32];
PaymentMethod paymentMethod = 2 [(require.specified) = true];
bytes subscriber_id = 1 [(require.exactlySize) = 32];
PaymentMethod payment_method = 2 [(require.specified) = true];
// a libsignal DonationPermit from rpc Donations.CreateDonationPermit
bytes donation_permit = 3 [(require.nonEmpty) = true];
}
message CreatePaymentMethodResponse {
@@ -188,6 +195,8 @@ message CreatePaymentMethodResponse {
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
// New payment processor does not match existing processor associated with the subscription
errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"];
// The donation permit was expired or already spent
errors.FailedZkAuthentication permit_rejected = 5 [(tag.reason) = "permit_rejected"];
}
}
@@ -286,6 +295,10 @@ message ChargeFailure {
optional string outcome_type = 6;
}
message PaymentRequired {
optional ChargeFailure charge_failure = 1;
}
message SetSubscriptionLevelResponse {
message SetSubscriptionLevelResult {
uint64 level = 1;
@@ -358,10 +371,6 @@ message GetReceiptCredentialsResponse {
bytes receiptCredentialResponse = 1;
}
message PaymentRequired {
optional ChargeFailure charge_failure = 1;
}
oneof response {
GetReceiptCredentialsResult success = 1;
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.auth;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -23,7 +22,6 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@@ -78,8 +76,8 @@ class PhoneVerificationTokenManagerTest {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER, true, null, null, null, 0))));
.thenReturn(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER, true, null, null, null, 0)));
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
@@ -92,7 +90,7 @@ class PhoneVerificationTokenManagerTest {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
.thenReturn(Optional.empty());
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
@@ -105,8 +103,8 @@ class PhoneVerificationTokenManagerTest {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER + "0", true, null, null, null, 0))));
.thenReturn(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER + "0", true, null, null, null, 0)));
assertThrows(BadRequestException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
@@ -119,8 +117,8 @@ class PhoneVerificationTokenManagerTest {
final byte[] sessionId = TestRandomUtil.nextBytes(16);
when(registrationServiceClient.getSession(eq(sessionId), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER, false, null, null, null, 0))));
.thenReturn(Optional.of(
new RegistrationServiceSession(sessionId, PHONE_NUMBER, false, null, null, null, 0)));
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
@@ -131,13 +129,9 @@ class PhoneVerificationTokenManagerTest {
@ParameterizedTest
@MethodSource
void verifyRegistrationServiceClientException(final Throwable registrationServiceClientException,
final Class<Throwable> expectedExceptionClass) throws ExecutionException, InterruptedException, TimeoutException {
final Class<Throwable> expectedExceptionClass) {
@SuppressWarnings("unchecked") final CompletableFuture<Optional<RegistrationServiceSession>> mockFuture
= mock(CompletableFuture.class);
when(mockFuture.get(anyLong(), any())).thenThrow(registrationServiceClientException);
when(registrationServiceClient.getSession(any(), any())).thenReturn(mockFuture);
when(registrationServiceClient.getSession(any(), any())).thenThrow(registrationServiceClientException);
assertThrows(expectedExceptionClass, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
PHONE_NUMBER,
@@ -147,10 +141,9 @@ class PhoneVerificationTokenManagerTest {
private static List<Arguments> verifyRegistrationServiceClientException() {
return List.of(
Arguments.arguments(new ExecutionException(Status.INVALID_ARGUMENT.asRuntimeException()), BadRequestException.class),
Arguments.arguments(new ExecutionException(Status.RESOURCE_EXHAUSTED.asRuntimeException()), ServerErrorException.class),
Arguments.arguments(new CancellationException(), ServerErrorException.class),
Arguments.arguments(new TimeoutException(), ServerErrorException.class)
Arguments.arguments(Status.INVALID_ARGUMENT.asRuntimeException(), BadRequestException.class),
Arguments.arguments(Status.RESOURCE_EXHAUSTED.asRuntimeException(), ServerErrorException.class),
Arguments.arguments(Status.DEADLINE_EXCEEDED.asRuntimeException(), ServerErrorException.class)
);
}
}
@@ -10,27 +10,31 @@ import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.io.IOException;
import org.whispersystems.textsecuregcm.storage.FoundationDbDatabaseLifecycleManager;
import org.whispersystems.textsecuregcm.storage.ServiceContainerFoundationDbDatabaseLifecycleManager;
import org.whispersystems.textsecuregcm.storage.TestcontainersFoundationDbDatabaseLifecycleManager;
@JsonTypeName("local")
public class LocalFoundationDbDatabaseFactory implements FoundationDbDatabaseFactory {
@JsonIgnore
private final TestcontainersFoundationDbDatabaseLifecycleManager testcontainersFoundationDbDatabaseLifecycleManager;
@JsonIgnore
private Database database;
private LocalFoundationDbDatabaseFactory() {
this.testcontainersFoundationDbDatabaseLifecycleManager = new TestcontainersFoundationDbDatabaseLifecycleManager();
}
@Override
public synchronized Database build(final FDB fdb) throws IOException {
if (database == null) {
Runtime.getRuntime().addShutdownHook(new Thread(testcontainersFoundationDbDatabaseLifecycleManager::closeDatabase));
testcontainersFoundationDbDatabaseLifecycleManager.initializeDatabase(fdb);
database = testcontainersFoundationDbDatabaseLifecycleManager.getDatabase();
final String serviceContainerNamePrefix = System.getProperty("foundationDb.serviceContainerNamePrefix");
final FoundationDbDatabaseLifecycleManager lifecycleManager = serviceContainerNamePrefix != null
? new ServiceContainerFoundationDbDatabaseLifecycleManager(serviceContainerNamePrefix + "0")
: new TestcontainersFoundationDbDatabaseLifecycleManager();
Runtime.getRuntime().addShutdownHook(new Thread(lifecycleManager::closeDatabase));
lifecycleManager.initializeDatabase(fdb);
database = lifecycleManager.getDatabase();
}
return database;
@@ -18,9 +18,7 @@ import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
@@ -41,7 +39,7 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
private SecretBytes collationKeySalt;
@Override
public RegistrationServiceClient build(final Environment environment, final Executor callbackExecutor,
public RegistrationServiceClient build(final Environment environment,
final ScheduledExecutorService identityRefreshExecutor) {
try {
@@ -56,11 +54,11 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
private final static Map<String, RegistrationServiceSession> SESSIONS = new ConcurrentHashMap<>();
public StubRegistrationServiceClient(final String registrationCaCertificate, final byte[] collationKeySalt) throws IOException {
super("example.com", 8080, null, registrationCaCertificate, collationKeySalt, null);
super("example.com", 8080, null, registrationCaCertificate, collationKeySalt);
}
@Override
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
public RegistrationServiceSession createRegistrationSession(
final Phonenumber.PhoneNumber phoneNumber,
final String sourceHost,
final boolean accountExistsWithPhoneNumber,
@@ -77,18 +75,18 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
Instant.now().plus(Duration.ofMinutes(10)).toEpochMilli());
SESSIONS.put(Base64.getEncoder().encodeToString(id), session);
return CompletableFuture.completedFuture(session);
return session;
}
@Override
public CompletableFuture<RegistrationServiceSession> sendVerificationCode(final byte[] sessionId,
public RegistrationServiceSession sendVerificationCode(final byte[] sessionId,
final MessageTransport messageTransport, final ClientType clientType, final @Nullable String acceptLanguage,
final @Nullable String senderOverride, final Duration timeout) {
return CompletableFuture.completedFuture(SESSIONS.get(Base64.getEncoder().encodeToString(sessionId)));
return SESSIONS.get(Base64.getEncoder().encodeToString(sessionId));
}
@Override
public CompletableFuture<RegistrationServiceSession> checkVerificationCode(final byte[] sessionId,
public RegistrationServiceSession checkVerificationCode(final byte[] sessionId,
final String verificationCode, final Duration timeout) {
final RegistrationServiceSession session = SESSIONS.get(Base64.getEncoder().encodeToString(sessionId));
@@ -97,14 +95,12 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
Instant.now().plus(Duration.ofMinutes(10)).toEpochMilli());
SESSIONS.put(Base64.getEncoder().encodeToString(sessionId), updatedSession);
return CompletableFuture.completedFuture(updatedSession);
return updatedSession;
}
@Override
public CompletableFuture<Optional<RegistrationServiceSession>> getSession(final byte[] sessionId,
final Duration timeout) {
return CompletableFuture.completedFuture(
Optional.ofNullable(SESSIONS.get(Base64.getEncoder().encodeToString(sessionId))));
public Optional<RegistrationServiceSession> getSession(final byte[] sessionId, final Duration timeout) {
return Optional.ofNullable(SESSIONS.get(Base64.getEncoder().encodeToString(sessionId)));
}
}
@@ -5,12 +5,26 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.time.Instant;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
@@ -31,5 +45,32 @@ class AbstractV1SubscriptionControllerTest {
static final ServerZkReceiptOperations ZK_OPS = mock(ServerZkReceiptOperations.class);
private static final ServerSecretParams DONATION_PERMITS_SECRET_PARAMS = ServerSecretParams.generate();
static final DonationPermits DONATION_PERMITS = mock(DonationPermits.class);
static final DonationPermitsManager DONATION_PERMITS_MANAGER = new DonationPermitsManager(DONATION_PERMITS, DONATION_PERMITS_SECRET_PARAMS, CLOCK);
String getDonationPermitHeader() {
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(1);
final DonationPermitRequest permitRequest = context.request();
final DonationPermitResponse permitResponse = DONATION_PERMITS_MANAGER.issue(permitRequest);
try {
final List<DonationPermit> donationPermits = context.receive(permitResponse,
DONATION_PERMITS_SECRET_PARAMS.getPublicParams(), CLOCK.instant());
return Base64.getEncoder().encodeToString(donationPermits.getFirst().serialize());
} catch (final VerificationFailedException e) {
throw new RuntimeException(e);
}
}
/// Sets up stubbing so that spendIds are spend-once
protected void setUpDonationPermitsSpendStubbing(final DonationPermits donationPermits) {
final Set<String> spent = new HashSet<>();
when(donationPermits.spend(any(byte[].class), any(Instant.class)))
.thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class))));
}
}
@@ -51,6 +51,8 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
@@ -78,7 +80,9 @@ class DonationControllerTest {
}
private final TestClock clock = TestClock.pinned(Instant.ofEpochSecond(nowEpochSeconds));
private final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
private final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(mock(DonationPermits.class), serverSecretParams, clock);
private RedeemedReceiptsManager redeemedReceiptsManager;
private AccountsManager accountsManager;
@@ -117,7 +121,7 @@ class DonationControllerTest {
.addProvider(RateLimitExceededExceptionMapper.class)
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new DonationController(clock, mock(ServerZkReceiptOperations.class), redeemedReceiptsManager, accountsManager,
getBadgesConfiguration(), receiptCredentialPresentationFactory, serverSecretParams, rateLimiters))
getBadgesConfiguration(), receiptCredentialPresentationFactory, donationPermitsManager, rateLimiters))
.build();
resources.before();
}
@@ -54,8 +54,10 @@ import org.signal.keytransparency.client.DistinguishedResponse;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.FullTreeHead;
import org.signal.keytransparency.client.MonitorResponse;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchProof;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.UpdateValue;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
@@ -143,7 +145,10 @@ public class KeyTransparencyControllerTest {
usernameHash.ifPresent(ignored -> searchResponseBuilder.setUsernameHash(CondensedTreeSearchResponse.getDefaultInstance()));
when(keyTransparencyServiceClient.search(any(), any(), any(), any(), any(), anyLong()))
.thenReturn(searchResponseBuilder.build());
.thenReturn(SearchResponseV2.newBuilder()
.setSearchResponse(searchResponseBuilder.build())
.build()
);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/key-transparency/search")
@@ -291,7 +296,9 @@ public class KeyTransparencyControllerTest {
@Test
void monitorSuccess() {
when(keyTransparencyServiceClient.monitor(any(), any(), any(), anyLong(), anyLong()))
.thenReturn(MonitorResponse.getDefaultInstance());
.thenReturn(MonitorResponseV2.newBuilder()
.setMonitorResponse(MonitorResponse.getDefaultInstance())
.build());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/key-transparency/monitor")
@@ -306,7 +313,7 @@ public class KeyTransparencyControllerTest {
final KeyTransparencyMonitorResponse keyTransparencyMonitorResponse = response.readEntity(
KeyTransparencyMonitorResponse.class);
assertNotNull(keyTransparencyMonitorResponse.serializedResponse());
assertArrayEquals(MonitorResponse.getDefaultInstance().toByteArray(), keyTransparencyMonitorResponse.serializedResponse());
verify(keyTransparencyServiceClient, times(1)).monitor(
any(), any(), any(), eq(3L), eq(4L));
@@ -25,13 +25,10 @@ import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
@@ -41,10 +38,16 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
@@ -54,7 +57,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@ExtendWith(DropwizardExtensionsSupport.class)
@@ -67,7 +70,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
private static final OneTimeDonationController ONE_TIME_CONTROLLER = new OneTimeDonationController(CLOCK,
ONETIME_CONFIG, STRIPE_MANAGER, BRAINTREE_MANAGER, PAYPAL_ONE_TIME_DONATION_LINE_ITEM_TRANSLATOR,
ZK_OPS, ISSUED_RECEIPTS_MANAGER, ONE_TIME_DONATIONS_MANAGER);
ZK_OPS, ISSUED_RECEIPTS_MANAGER, ONE_TIME_DONATIONS_MANAGER, DONATION_PERMITS_MANAGER);
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
@@ -82,7 +85,11 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
@BeforeEach
void setUp() {
reset(CLOCK, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, PAYPAL_ONE_TIME_DONATION_LINE_ITEM_TRANSLATOR);
reset(CLOCK, DONATION_PERMITS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, PAYPAL_ONE_TIME_DONATION_LINE_ITEM_TRANSLATOR);
setUpDonationPermitsSpendStubbing(DONATION_PERMITS);
when(CLOCK.instant()).thenReturn(Instant.now());
when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE);
when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE);
@@ -101,69 +108,80 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
.thenReturn(Set.of("usd", "jpy"));
}
@Test
void testCreateBoostPaymentIntentAmountBelowCurrencyMinimum() {
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
.request()
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.post(Entity.json("""
{
"currency": "USD",
"amount": 249
}
"""));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.hasEntity()).isTrue();
final Map responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("error")).isEqualTo("amount_below_currency_minimum");
assertThat(responseMap.get("minimum")).isEqualTo("2.50");
"""))) {
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.hasEntity()).isTrue();
final Map<?, ?> responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("error")).isEqualTo("amount_below_currency_minimum");
assertThat(responseMap.get("minimum")).isEqualTo("2.50");
}
}
@Test
void testCreateBoostPaymentIntentAmountAboveSepaLimit() {
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.SEPA_DEBIT))
.thenReturn(Set.of("eur"));
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
.request()
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.post(Entity.json("""
{
"currency": "EUR",
"amount": 1000001,
"paymentMethod": "SEPA_DEBIT"
}
"""));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.hasEntity()).isTrue();
"""))) {
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.hasEntity()).isTrue();
final Map responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("error")).isEqualTo("amount_above_sepa_limit");
assertThat(responseMap.get("maximum")).isEqualTo("10000");
final Map<?, ?> responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("error")).isEqualTo("amount_above_sepa_limit");
assertThat(responseMap.get("maximum")).isEqualTo("10000");
}
}
@Test
void testCreateBoostPaymentIntentUnsupportedCurrency() {
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.SEPA_DEBIT))
.thenReturn(Set.of("eur"));
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
.request()
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.post(Entity.json("""
{
"currency": "USD",
"amount": 3000,
"paymentMethod": "SEPA_DEBIT"
}
"""));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.hasEntity()).isTrue();
"""))) {
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.hasEntity()).isTrue();
final Map responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("error")).isEqualTo("unsupported_currency");
final Map<?, ?> responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("error")).isEqualTo("unsupported_currency");
}
}
@Test
void testCreateBoostPaymentIntent() {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) {
when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk);
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(STRIPE_MANAGER.createPaymentIntent(anyString(), anyLong(), anyLong(), any()))
@@ -172,13 +190,15 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
String clientSecret = "some_client_secret";
when(PAYMENT_INTENT.getClientSecret()).thenReturn(clientSecret);
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
.request()
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.post(Entity.json("""
{"currency": "USD", "amount": 300}
"""
));
assertThat(response.getStatus()).isEqualTo(200);
))) {
assertThat(response.getStatus()).isEqualTo(donationPermitSpendOk ? 200 : 401);
}
}
@Test
@@ -192,7 +212,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
when(payPalOneTimePaymentApprovalDetails.approvalUrl()).thenReturn("approvalUrl");
when(payPalOneTimePaymentApprovalDetails.paymentId()).thenReturn("someId");
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/create")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/create")
.request()
.post(Entity.json("""
{
@@ -202,44 +222,48 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
"returnUrl": "returnUrl"
}
"""
));
assertThat(response.getStatus()).isEqualTo(200);
))) {
assertThat(response.getStatus()).isEqualTo(200);
}
}
@Test
void createBoostReceiptInvalid() {
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
// invalid, request body should have receiptCredentialRequest
.post(Entity.json("{\"paymentIntentId\": \"foo\"}"));
assertThat(response.getStatus()).isEqualTo(422);
.post(Entity.json("{\"paymentIntentId\": \"foo\"}"))) {
assertThat(response.getStatus()).isEqualTo(422);
}
}
@ParameterizedTest
@MethodSource
void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure) {
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(new PaymentDetails(
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
"id",
Collections.emptyMap(),
PaymentStatus.FAILED,
Instant.now(),
chargeFailure)
chargeFailure))
));
Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
.post(Entity.json("""
{
"paymentIntentId": "foo",
"receiptCredentialRequest": "abcd",
"processor": "STRIPE"
}
"""));
assertThat(response.getStatus()).isEqualTo(402);
{
"paymentIntentId": "foo",
"receiptCredentialRequest": "abcd",
"processor": "STRIPE"
}
"""))) {
assertThat(response.getStatus()).isEqualTo(402);
if (expectChargeFailure) {
assertThat(response.readEntity(OneTimeDonationController.CreateBoostReceiptCredentialsErrorResponse.class).chargeFailure()).isEqualTo(chargeFailure);
} else {
assertThat(response.readEntity(String.class)).isEqualTo("{}");
if (expectChargeFailure) {
assertThat(response.readEntity(OneTimeDonationController.CreateBoostReceiptCredentialsErrorResponse.class)
.chargeFailure()).isEqualTo(chargeFailure);
} else {
assertThat(response.readEntity(String.class)).isEqualTo("{}");
}
}
}
@@ -265,30 +289,32 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
new ChargeFailure("2046", "Declined", null, null, null))));
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
.request()
.post(Entity.json(Map.of("payerId", "payer123",
"paymentId", "PAYID-456",
"paymentToken", "EC-789",
"currency", "usd",
"amount", 300)));
"amount", 300)))) {
assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE);
assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE);
final Map responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("processor")).isEqualTo("BRAINTREE");
assertThat(responseMap.get("chargeFailure")).asInstanceOf(
InstanceOfAssertFactories.map(String.class, Object.class))
.extracting("code")
.isEqualTo("2046");
final Map<?, ?> responseMap = response.readEntity(Map.class);
assertThat(responseMap.get("processor")).isEqualTo("BRAINTREE");
assertThat(responseMap.get("chargeFailure")).asInstanceOf(
InstanceOfAssertFactories.map(String.class, Object.class))
.extracting("code")
.isEqualTo("2046");
}
}
@Test
void createBoostReceiptNoRequest() {
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
.post(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(422);
.post(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(422);
}
}
@Test
@@ -297,22 +323,23 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(new PaymentDetails(
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
"id",
Collections.emptyMap(),
PaymentStatus.SUCCEEDED,
Instant.now(),
null)));
null))));
doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordIssuance(any(), any(), any(), any());
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
.post(Entity.json(Map.of(
"paymentIntentId", "foo",
"receiptCredentialRequest", Base64.getEncoder().encodeToString(receiptCredentialRequest.serialize()),
"processor", "STRIPE"
)));
assertThat(response.getStatus()).isEqualTo(409);
)))) {
assertThat(response.getStatus()).isEqualTo(409);
}
}
}
@@ -92,9 +92,9 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequire
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@@ -117,7 +117,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
SUBSCRIPTION_CONFIG, ONETIME_CONFIG,
new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER),
ZK_OPS, ISSUED_RECEIPTS_MANAGER), STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER,
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DYNAMIC_CONFIGURATION_MANAGER);
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DONATION_PERMITS_MANAGER, DYNAMIC_CONFIGURATION_MANAGER);
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
.addProvider(AuthHelper.getAuthFilter())
@@ -131,7 +131,11 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
@BeforeEach
void setUp() {
reset(CLOCK, SUBSCRIPTIONS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER, BADGE_TRANSLATOR);
reset(CLOCK, DONATION_PERMITS, SUBSCRIPTIONS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER, BADGE_TRANSLATOR);
setUpDonationPermitsSpendStubbing(DONATION_PERMITS);
when(CLOCK.instant()).thenReturn(Instant.now());
when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE);
when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE);
@@ -163,8 +167,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
@BeforeEach
void setUp() {
when(CLOCK.instant()).thenReturn(Instant.now());
final byte[] subscriberUserAndKey = new byte[32];
Arrays.fill(subscriberUserAndKey, (byte) 1);
subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
@@ -189,12 +191,13 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
final String level = String.valueOf(levelId);
final String idempotencyKey = UUID.randomUUID().toString();
final Response response = RESOURCE_EXTENSION.target(
try (Response response = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getStatus()).isEqualTo(200);
}
}
@Test
@@ -205,14 +208,16 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
final String level = String.valueOf(levelId);
final String idempotencyKey = UUID.randomUUID().toString();
final Response response = RESOURCE_EXTENSION.target(
final Map<?, ?> responseMap;
try (Response response = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE);
assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE);
final Map responseMap = response.readEntity(Map.class);
responseMap = response.readEntity(Map.class);
}
assertThat(responseMap.get("processor")).isEqualTo("STRIPE");
assertThat(responseMap.get("chargeFailure")).asInstanceOf(
InstanceOfAssertFactories.map(String.class, Object.class))
@@ -238,12 +243,13 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
final String level = String.valueOf(levelId);
final String idempotencyKey = UUID.randomUUID().toString();
final Response response = RESOURCE_EXTENSION.target(
try (Response response = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey))
.request()
.put(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(409);
assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message");
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(409);
assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message");
}
}
@Test
@@ -263,13 +269,15 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
when(SUBSCRIPTIONS.get(eq(Arrays.copyOfRange(subscriberUserAndKey, 0, 16)), any()))
.thenReturn(Subscriptions.GetResult.found(record));
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/create_payment_method", subscriberId))
.request()
.post(Entity.json(""));
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.post(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(409);
assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message");
assertThat(response.getStatus()).isEqualTo(409);
assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message");
}
}
@Test
@@ -280,27 +288,26 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
final String level = String.valueOf(levelId);
final String idempotencyKey = UUID.randomUUID().toString();
final Response response = RESOURCE_EXTENSION.target(
try (Response response = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class))
.satisfies(errorResponse ->
assertThat(errorResponse.errors())
.anySatisfy(error ->
assertThat(error.type())
.isEqualTo(
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION)));
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class))
.satisfies(errorResponse ->
assertThat(errorResponse.errors())
.anySatisfy(error ->
assertThat(error.type())
.isEqualTo(
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION)));
}
}
}
@Test
void createSubscriber() {
when(CLOCK.instant()).thenReturn(Instant.now());
// basic create
final byte[] subscriberUserAndKey = new byte[32];
Arrays.fill(subscriberUserAndKey, (byte) 1);
@@ -316,30 +323,34 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(record);
final Response createResponse = RESOURCE_EXTENSION.target(String.format("/v1/subscription/%s", subscriberId))
try (Response createResponse = RESOURCE_EXTENSION.target(String.format("/v1/subscription/%s", subscriberId))
.request()
.put(Entity.json(""));
assertThat(createResponse.getStatus()).isEqualTo(200);
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.put(Entity.json(""))) {
assertThat(createResponse.getStatus()).isEqualTo(200);
}
// creating should be idempotent
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.found(record));
final Response idempotentCreateResponse = RESOURCE_EXTENSION.target(
try (Response idempotentCreateResponse = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s", subscriberId))
.request()
.put(Entity.json(""));
assertThat(idempotentCreateResponse.getStatus()).isEqualTo(200);
.put(Entity.json(""))) {
assertThat(idempotentCreateResponse.getStatus()).isEqualTo(200);
}
// when the manager returns `null`, it means there was a password mismatch from the storage layer `create`.
// this could happen if there is a race between two concurrent `create` requests for the same user ID
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED);
when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(null);
final Response managerCreateNullResponse = RESOURCE_EXTENSION.target(
try (Response managerCreateNullResponse = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s", subscriberId))
.request()
.put(Entity.json(""));
assertThat(managerCreateNullResponse.getStatus()).isEqualTo(403);
.put(Entity.json(""))) {
assertThat(managerCreateNullResponse.getStatus()).isEqualTo(403);
}
final byte[] subscriberUserAndMismatchedKey = new byte[32];
Arrays.fill(subscriberUserAndMismatchedKey, 0, 16, (byte) 1);
@@ -349,24 +360,26 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
// a password mismatch for an existing record
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.PASSWORD_MISMATCH);
final Response passwordMismatchResponse = RESOURCE_EXTENSION.target(
try (Response passwordMismatchResponse = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s", mismatchedSubscriberId))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
assertThat(passwordMismatchResponse.getStatus()).isEqualTo(403);
assertThat(passwordMismatchResponse.getStatus()).isEqualTo(403);
}
// invalid request data is a 404
final byte[] malformedUserAndKey = new byte[16];
Arrays.fill(malformedUserAndKey, (byte) 1);
final String malformedUserId = Base64.getEncoder().encodeToString(malformedUserAndKey);
final Response malformedUserAndKeyResponse = RESOURCE_EXTENSION.target(
try (Response malformedUserAndKeyResponse = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s", malformedUserId))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
assertThat(malformedUserAndKeyResponse.getStatus()).isEqualTo(404);
assertThat(malformedUserAndKeyResponse.getStatus()).isEqualTo(404);
}
}
@Test
@@ -375,7 +388,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
Arrays.fill(subscriberUserAndKey, (byte) 1);
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED);
final Map<String, AttributeValue> dynamoItem = Map.of(Subscriptions.KEY_PASSWORD, b(new byte[16]),
@@ -386,12 +398,14 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class))).thenReturn(record);
final Response createSubscriberResponse = RESOURCE_EXTENSION
try (Response createSubscriberResponse = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s", subscriberId))
.request()
.put(Entity.json(""));
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.put(Entity.json(""))) {
assertThat(createSubscriberResponse.getStatus()).isEqualTo(200);
assertThat(createSubscriberResponse.getStatus()).isEqualTo(200);
}
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(record));
@@ -415,15 +429,17 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
when(STRIPE_MANAGER.createPaymentMethodSetupToken(customerId))
.thenReturn(clientSecret);
final SubscriptionController.CreatePaymentMethodResponse createPaymentMethodResponse = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/create_payment_method", subscriberId))
.request()
.post(Entity.json(""))
.readEntity(SubscriptionController.CreatePaymentMethodResponse.class);
assertThat(createPaymentMethodResponse.processor()).isEqualTo(PaymentProvider.STRIPE);
assertThat(createPaymentMethodResponse.clientSecret()).isEqualTo(clientSecret);
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.post(Entity.json(""))) {
final SubscriptionController.CreatePaymentMethodResponse createPaymentMethodResponse =
response.readEntity(SubscriptionController.CreatePaymentMethodResponse.class);
assertThat(createPaymentMethodResponse.processor()).isEqualTo(PaymentProvider.STRIPE);
assertThat(createPaymentMethodResponse.clientSecret()).isEqualTo(clientSecret);
}
}
@Test
@@ -443,16 +459,16 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
.thenReturn(record);
// set up mocks
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(record));
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, 5, "usd", "abcd"))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(409);
assertThat(response.getStatus()).isEqualTo(409);
}
}
@ParameterizedTest
@@ -482,26 +498,26 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
.thenReturn(record);
// set up mocks
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(record));
when(BRAINTREE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId("subscription"));
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, levelId, "usd", "abcd"))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
verify(BRAINTREE_MANAGER).createSubscription(eq(customerId), eq(expectedProcessorId), eq(levelId), eq(0L));
verifyNoMoreInteractions(BRAINTREE_MANAGER);
verify(BRAINTREE_MANAGER).createSubscription(eq(customerId), eq(expectedProcessorId), eq(levelId), eq(0L));
verifyNoMoreInteractions(BRAINTREE_MANAGER);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class))
.extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level)
.isEqualTo(levelId);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class))
.extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level)
.isEqualTo(levelId);
}
}
@ParameterizedTest
@@ -530,7 +546,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
.thenReturn(record);
// set up mocks
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(record));
@@ -546,27 +561,28 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
}
final String idempotencyKey = "abcd";
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, requestLevel, requestCurrency,
idempotencyKey))
.request()
.put(Entity.json(""));
.put(Entity.json(""))) {
verify(BRAINTREE_MANAGER).getSubscription(any());
verify(BRAINTREE_MANAGER).getLevelAndCurrencyForSubscription(any());
verify(BRAINTREE_MANAGER).getSubscription(any());
verify(BRAINTREE_MANAGER).getLevelAndCurrencyForSubscription(any());
if (expectUpdate) {
verify(BRAINTREE_MANAGER).updateSubscription(any(), any(), eq(requestLevel), eq(idempotencyKey));
verify(SUBSCRIPTIONS).subscriptionLevelChanged(any(), any(), eq(requestLevel), eq(updatedSubscriptionId));
if (expectUpdate) {
verify(BRAINTREE_MANAGER).updateSubscription(any(), any(), eq(requestLevel), eq(idempotencyKey));
verify(SUBSCRIPTIONS).subscriptionLevelChanged(any(), any(), eq(requestLevel), eq(updatedSubscriptionId));
}
verifyNoMoreInteractions(BRAINTREE_MANAGER);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class))
.extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level)
.isEqualTo(requestLevel);
}
verifyNoMoreInteractions(BRAINTREE_MANAGER);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class))
.extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level)
.isEqualTo(requestLevel);
}
static Stream<Arguments> setSubscriptionLevelExistingSubscription() {
@@ -600,7 +616,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class)))
.thenReturn(record);
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(record));
@@ -610,17 +625,19 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(201, "usd"));
// Try to change from a backup subscription (201) to a donation subscription (5)
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, 5, "usd", "abcd"))
.request()
.put(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class))
.extracting(resp -> resp.errors())
.asInstanceOf(InstanceOfAssertFactories.list(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.class))
.hasSize(1).first()
.extracting(error -> error.type())
.isEqualTo(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL);
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class))
.extracting(SubscriptionController.SetSubscriptionLevelErrorResponse::errors)
.asInstanceOf(
InstanceOfAssertFactories.list(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.class))
.hasSize(1).first()
.extracting(SubscriptionController.SetSubscriptionLevelErrorResponse.Error::type)
.isEqualTo(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL);
}
}
@Test
@@ -646,14 +663,15 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
when(APPSTORE_MANAGER.validateTransaction(eq(originalTxId)))
.thenReturn(99L);
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/appstore/%s", subscriberId, originalTxId))
.request()
.post(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level())
.isEqualTo(99L);
.post(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level())
.isEqualTo(99L);
}
verify(SUBSCRIPTIONS, times(1)).setIapPurchase(
any(),
@@ -687,13 +705,14 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
when(validatedToken.getLevel()).thenReturn(99L);
when(PLAY_MANAGER.validateToken(eq(purchaseToken))).thenReturn(validatedToken);
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/playbilling/%s", subscriberId, purchaseToken))
.request()
.post(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level())
.isEqualTo(99L);
.post(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level())
.isEqualTo(99L);
}
verify(SUBSCRIPTIONS, times(1)).setIapPurchase(
any(),
@@ -729,13 +748,14 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
when(PLAY_MANAGER.validateToken(eq(newPurchaseToken))).thenReturn(validatedToken);
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/playbilling/%s", subscriberId, newPurchaseToken))
.request()
.post(Entity.json(""));
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level())
.isEqualTo(99L);
.post(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level())
.isEqualTo(99L);
}
verify(SUBSCRIPTIONS, times(1)).setIapPurchase(
any(),
@@ -754,7 +774,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
Arrays.fill(subscriberUserAndKey, (byte) 1);
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(Subscriptions.Record.from(
Arrays.copyOfRange(subscriberUserAndKey, 0, 16),
@@ -772,13 +791,15 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
final ReceiptCredentialRequest receiptRequest = new ClientZkReceiptOperations(
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
final Response response = RESOURCE_EXTENSION
final Map<?, ?> responseMap;
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/receipt_credentials", subscriberId))
.request()
.post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())));
.post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())))) {
assertThat(response.getStatus()).isEqualTo(402);
final Map responseMap = response.readEntity(Map.class);
assertThat(response.getStatus()).isEqualTo(402);
responseMap = response.readEntity(Map.class);
}
assertThat(responseMap.get("processor")).isEqualTo("STRIPE");
assertThat(responseMap.get("chargeFailure")).asInstanceOf(
InstanceOfAssertFactories.map(String.class, Object.class))
@@ -793,7 +814,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
Arrays.fill(subscriberUserAndKey, (byte) 1);
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(Subscriptions.Record.from(
Arrays.copyOfRange(subscriberUserAndKey, 0, 16),
@@ -813,12 +833,13 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
final ReceiptCredentialRequest receiptRequest = new ClientZkReceiptOperations(
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/receipt_credentials", subscriberId))
.request()
.post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())));
.post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())))) {
assertThat(response.getStatus()).isEqualTo(409);
assertThat(response.getStatus()).isEqualTo(409);
}
}
@ParameterizedTest
@@ -844,7 +865,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
final ReceiptCredentialResponse receiptCredentialResponse = mock(ReceiptCredentialResponse.class);
when(CLOCK.instant()).thenReturn(Instant.now());
when(SUBSCRIPTIONS.get(any(), any()))
.thenReturn(Subscriptions.GetResult.found(record));
when(BRAINTREE_MANAGER.getReceiptItem(subscriptionId)).thenReturn(
@@ -854,11 +874,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
level));
when(ZK_OPS.issueReceiptCredential(any(), anyLong(), eq(level))).thenReturn(receiptCredentialResponse);
when(receiptCredentialResponse.serialize()).thenReturn(new byte[0]);
final Response response = RESOURCE_EXTENSION
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/receipt_credentials", subscriberId))
.request()
.post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())));
assertThat(response.getStatus()).isEqualTo(200);
.post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())))) {
assertThat(response.getStatus()).isEqualTo(200);
}
long expectedExpiration = Instant.EPOCH
// Truncated current time is day 1
@@ -988,13 +1009,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
assertThat(badge.getName()).isEqualTo("gift1");
}));
assertThat(levelsMap).extractingByKey(5L).satisfies(level -> {
assertThat(level).extracting(LevelConfiguration::badge)
.satisfies(badge -> {
assertThat(badge.getId()).isEqualTo("B1");
assertThat(badge.getName()).isEqualTo("name1");
});
});
assertThat(levelsMap).extractingByKey(5L).satisfies(level ->
assertThat(level).extracting(LevelConfiguration::badge)
.satisfies(badge -> {
assertThat(badge.getId()).isEqualTo("B1");
assertThat(badge.getName()).isEqualTo("name1");
}));
assertThat(levelsMap).extractingByKey(15L).satisfies(level ->
assertThat(level).extracting(LevelConfiguration::badge)
@@ -1003,13 +1023,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
assertThat(badge.getName()).isEqualTo("name2");
}));
assertThat(levelsMap).extractingByKey(35L).satisfies(level -> {
assertThat(level).extracting(LevelConfiguration::badge)
.satisfies(badge -> {
assertThat(badge.getId()).isEqualTo("B3");
assertThat(badge.getName()).isEqualTo("name3");
});
});
assertThat(levelsMap).extractingByKey(35L).satisfies(level ->
assertThat(level).extracting(LevelConfiguration::badge)
.satisfies(badge -> {
assertThat(badge.getId()).isEqualTo("B3");
assertThat(badge.getName()).isEqualTo("name3");
}));
});
assertThat(response.backup().levels()).containsOnlyKeys("201").extractingByKey("201").satisfies(configuration -> {
@@ -44,7 +44,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
@@ -121,8 +120,8 @@ class VerificationControllerTest {
private final RateLimiter captchaLimiter = mock(RateLimiter.class);
private final RateLimiter pushChallengeLimiter = mock(RateLimiter.class);
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
DynamicConfigurationManager.class);
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
private final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
private final ResourceExtension resources = ResourceExtension.builder()
@@ -206,9 +205,9 @@ class VerificationControllerTest {
}
@Test
void createSessionRateLimited() {
void createSessionRateLimited() throws RateLimitExceededException {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
.thenThrow(new RateLimitExceededException(null));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
@@ -220,9 +219,9 @@ class VerificationControllerTest {
}
@Test
void createSessionRegistrationServiceError() {
void createSessionRegistrationServiceError() throws RateLimitExceededException {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("expected service error")));
.thenThrow(new RuntimeException("expected service error"));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
@@ -235,12 +234,10 @@ class VerificationControllerTest {
@ParameterizedTest
@MethodSource
void createBeninSessionSuccess(final String requestedNumber, final String expectedNumber) {
void createBeninSessionSuccess(final String requestedNumber, final String expectedNumber)
throws RateLimitExceededException {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
.thenReturn(new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null, SESSION_EXPIRATION_SECONDS));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
@@ -269,17 +266,14 @@ class VerificationControllerTest {
}
@Test
void createBeninSessionFailure() {
void createBeninSessionFailure() throws RateLimitExceededException {
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
.thenReturn(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
@@ -293,12 +287,9 @@ class VerificationControllerTest {
@ParameterizedTest
@MethodSource
void createSessionSuccess(final String pushToken, final String pushTokenType,
final List<VerificationSession.Information> expectedRequestedInformation) {
final List<VerificationSession.Information> expectedRequestedInformation) throws RateLimitExceededException {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
.thenReturn(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
@@ -325,13 +316,10 @@ class VerificationControllerTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void createSessionReregistration(final boolean isReregistration) throws NumberParseException {
void createSessionReregistration(final boolean isReregistration)
throws NumberParseException, RateLimitExceededException {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
.thenReturn(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS));
when(accountsManager.getByE164(NUMBER))
.thenReturn(isReregistration ? Optional.of(mock(Account.class)) : Optional.empty());
@@ -371,7 +359,7 @@ class VerificationControllerTest {
@Test
void patchSessionNotFound() {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
.thenReturn(Optional.empty());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodeSessionId(SESSION_ID))
@@ -389,9 +377,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(
new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(),
@@ -430,9 +416,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
@@ -462,9 +446,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
@@ -494,9 +476,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(VerificationSession.Information.PUSH_CHALLENGE),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
@@ -525,9 +505,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
@@ -568,9 +546,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
"challenge",
@@ -613,8 +589,7 @@ class VerificationControllerTest {
true, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(), List.of(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
@@ -644,9 +619,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
"challenge",
@@ -687,9 +660,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
@@ -731,9 +702,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
"challenge",
@@ -779,7 +748,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
null,
@@ -829,7 +798,7 @@ class VerificationControllerTest {
@Test
void getSessionInvalidArgs() {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.failedFuture(new StatusRuntimeException(Status.INVALID_ARGUMENT)));
.thenThrow(new StatusRuntimeException(Status.INVALID_ARGUMENT));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodeSessionId(SESSION_ID))
@@ -843,7 +812,7 @@ class VerificationControllerTest {
@Test
void getSessionNotFound() {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
.thenReturn(Optional.empty());
when(verificationSessionManager.findForId(encodeSessionId(SESSION_ID)))
.thenReturn(Optional.empty());
@@ -856,10 +825,7 @@ class VerificationControllerTest {
}
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS))));
.thenReturn(Optional.of(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS)));
request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodeSessionId(SESSION_ID))
@@ -873,7 +839,7 @@ class VerificationControllerTest {
@Test
void getSessionError() {
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
.thenThrow(new RuntimeException());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodeSessionId(SESSION_ID))
@@ -888,10 +854,7 @@ class VerificationControllerTest {
void getSessionSuccess() {
final String encodedSessionId = encodeSessionId(SESSION_ID);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS))));
.thenReturn(Optional.of(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(mock(VerificationSession.class)));
@@ -911,9 +874,7 @@ class VerificationControllerTest {
true, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(mock(VerificationSession.class)));
@@ -929,18 +890,19 @@ class VerificationControllerTest {
}
@Test
void requestVerificationCodeAlreadyVerified() {
void requestVerificationCodeAlreadyVerified()
throws RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
true, null, null,
null, SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(registrationServiceSession));
.thenReturn(registrationServiceSession);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -963,9 +925,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null,
List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
@@ -994,9 +954,7 @@ class VerificationControllerTest {
false, null, null, null,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
@@ -1017,20 +975,19 @@ class VerificationControllerTest {
}
@Test
void requestVerificationCodeRateLimitExceeded() {
void requestVerificationCodeRateLimitExceeded()
throws RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null,
null, SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(
new CompletionException(new VerificationSessionRateLimitExceededException(registrationServiceSession,
Duration.ofMinutes(1), true))));
.thenThrow(new VerificationSessionRateLimitExceededException(registrationServiceSession, Duration.ofMinutes(1), true));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1048,19 +1005,19 @@ class VerificationControllerTest {
}
@Test
void requestVerificationCodeTransportNotAllowed() {
void requestVerificationCodeTransportNotAllowed()
throws RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null,
null, SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(
new CompletionException(new TransportNotAllowedException(registrationServiceSession))));
.thenThrow(new TransportNotAllowedException(registrationServiceSession));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1081,18 +1038,18 @@ class VerificationControllerTest {
@CartesianTest
void requestVerificationCodeSuccess(@CartesianTest.Values(booleans = {true, false}) final boolean accountExistsWithNumber,
@CartesianTest.Values(booleans = {true, false}) final boolean enrolledInExperiment)
throws NotPushRegisteredException {
throws NotPushRegisteredException, RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null,
null, SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(registrationServiceSession));
.thenReturn(registrationServiceSession);
final UUID accountIdentifier = UUID.randomUUID();
@@ -1130,21 +1087,20 @@ class VerificationControllerTest {
@ParameterizedTest
@MethodSource
void requestVerificationCodeExternalServiceRefused(final boolean expectedPermanent, final String expectedReason,
final RegistrationServiceSenderException exception) {
final RegistrationServiceSenderException exception)
throws RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
.thenReturn(
CompletableFuture.failedFuture(new CompletionException(exception)));
.thenThrow(exception);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1170,7 +1126,8 @@ class VerificationControllerTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void fraudError(boolean shadowFailure) {
void fraudError(boolean shadowFailure)
throws RegistrationServiceException, RegistrationServiceSenderException, RegistrationFraudException, VerificationSessionRateLimitExceededException {
if (shadowFailure) {
when(this.dynamicConfiguration.getRegistrationConfiguration())
.thenReturn(new DynamicRegistrationConfiguration(true));
@@ -1180,14 +1137,13 @@ class VerificationControllerTest {
false, null, null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new CompletionException(
new RegistrationFraudException(RegistrationServiceSenderException.rejected(true)))));
.thenThrow(new RegistrationFraudException(RegistrationServiceSenderException.rejected(true)));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1206,20 +1162,19 @@ class VerificationControllerTest {
@Test
void verifyCodeServerError() {
void verifyCodeServerError() throws RegistrationServiceException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new CompletionException(new RuntimeException())));
.thenThrow(new RuntimeException());
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1238,8 +1193,7 @@ class VerificationControllerTest {
true, null, null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
@@ -1265,15 +1219,14 @@ class VerificationControllerTest {
}
@Test
void verifyCodeNoCodeRequested() {
void verifyCodeNoCodeRequested() throws RegistrationServiceException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, 0L, null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
@@ -1281,9 +1234,7 @@ class VerificationControllerTest {
// There is no explicit indication in the exception that no code has been sent, but we treat all RegistrationServiceExceptions
// in which the response has a session object as conflicted state
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new CompletionException(
new RegistrationServiceException(new RegistrationServiceSession(SESSION_ID, NUMBER, false, 0L, null, null,
SESSION_EXPIRATION_SECONDS)))));
.thenThrow(new RegistrationServiceException(new RegistrationServiceSession(SESSION_ID, NUMBER, false, 0L, null, null, SESSION_EXPIRATION_SECONDS)));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1301,21 +1252,20 @@ class VerificationControllerTest {
}
@Test
void verifyCodeNoSession() {
void verifyCodeNoSession() throws RegistrationServiceException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new CompletionException(new RegistrationServiceException(null))));
.thenThrow(new RegistrationServiceException(null));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1327,21 +1277,19 @@ class VerificationControllerTest {
}
@Test
void verifyCodeRateLimitExceeded() {
void verifyCodeRateLimitExceeded()
throws RegistrationServiceException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(
new CompletionException(new VerificationSessionRateLimitExceededException(registrationServiceSession,
Duration.ofMinutes(1), true))));
.thenThrow(new VerificationSessionRateLimitExceededException(registrationServiceSession, Duration.ofMinutes(1), true));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -1359,13 +1307,12 @@ class VerificationControllerTest {
}
@Test
void verifyCodeSuccess() {
void verifyCodeSuccess() throws RegistrationServiceException, VerificationSessionRateLimitExceededException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null, 0L, SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.getSession(any(), any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(registrationServiceSession)));
.thenReturn(Optional.of(registrationServiceSession));
when(verificationSessionManager.findForId(any()))
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
@@ -1374,7 +1321,7 @@ class VerificationControllerTest {
null, 0L,
SESSION_EXPIRATION_SECONDS);
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(verifiedSession));
.thenReturn(verifiedSession);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session/" + encodedSessionId + "/code")
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -61,6 +60,8 @@ import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.AccountController;
@@ -707,15 +708,15 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@ParameterizedTest
@ValueSource(booleans = {true, false})
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) throws Exception {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final ZkCredentialPublicKey publicKey = ZkCredentialKeyPair.generate().getPublicKey();
final long rotationId = ThreadLocalRandom.current().nextLong(1, Long.MAX_VALUE);
final Account account = mock(Account.class);
if (matchesCurrentZkCredentialKey) {
when(account.getZkCredentialKey()).thenReturn(publicKey);
when(account.getZkCredentialKey()).thenReturn(Optional.of(publicKey));
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
}
@@ -724,7 +725,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final SetZkCredentialKeyResponse response = assertDoesNotThrow(() ->
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey))
.setPublicKey(ByteString.copyFrom(publicKey.serialize()))
.build()));
if (matchesCurrentZkCredentialKey) {
@@ -736,13 +737,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final int updateMethodCalls = matchesCurrentZkCredentialKey ? 0 : 1;
verify(accountsManager, times(updateMethodCalls)).update(eq(AUTHENTICATED_ACI), any());
verify(account, times(updateMethodCalls)).setZkCredentialKey(aryEq(publicKey));
verify(account, times(updateMethodCalls)).setZkCredentialKey(publicKey);
}
@Test
void setZkCredentialKeyRateLimited() throws Exception {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final byte[] publicKey = ZkCredentialKeyPair.generate().getPublicKey().serialize();
final Duration retryDuration = Duration.ofDays(1);
final Account account = mock(Account.class);
@@ -12,7 +12,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -34,7 +33,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeAll;
@@ -84,7 +82,6 @@ import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
public class CredentialsGrpcServiceTest
extends SimpleBaseGrpcTest<CredentialsGrpcService, CredentialsGrpc.CredentialsBlockingStub> {
@@ -199,8 +196,7 @@ public class CredentialsGrpcServiceTest
final ExternalServiceType externalServiceType,
final ExternalServiceCredentialsGenerator credentialsGenerator) {
final RateLimiter limiter = mock(RateLimiter.class);
doReturn(limiter).when(rateLimiters).forDescriptor(eq(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS));
doReturn(Mono.fromFuture(CompletableFuture.completedFuture(null))).when(limiter).validateReactive(eq(AUTHENTICATED_ACI));
when(rateLimiters.forDescriptor(eq(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS))).thenReturn(limiter);
final GetExternalServiceCredentialsResponse artResponse = authenticatedServiceStub().getExternalServiceCredentials(
GetExternalServiceCredentialsRequest.newBuilder()
.setExternalService(externalServiceType)
@@ -3,6 +3,7 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -11,27 +12,40 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
import org.signal.chat.donations.CreateDonationPermitRequest;
import org.signal.chat.donations.CreateDonationPermitResponse;
import org.signal.chat.donations.DonationsGrpc;
import org.signal.chat.donations.RedeemReceiptRequest;
import org.signal.chat.donations.RedeemReceiptResponse;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
@@ -61,7 +75,13 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
@Mock
private ReceiptSerial receiptSerial;
private final Clock clock = TestClock.pinned(Instant.ofEpochSecond(100));
private final ServerSecretParams donationsPermitSecretParams = ServerSecretParams.generate();
private RateLimiter createDonationPermitLimiter;
private DonationPermitsManager donationPermitsManager;
private final TestClock clock = TestClock.pinned(Instant.ofEpochSecond(100));
private static final long EXPIRATION_TIME_EPOCH_SECONDS = 200;
@@ -79,13 +99,22 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
when(badgesConfiguration.getReceiptLevels()).thenReturn(Map.of(1L, "testBadge"));
when(receiptCredentialPresentation.getReceiptExpirationTime()).thenReturn(EXPIRATION_TIME_EPOCH_SECONDS);
when(receiptCredentialPresentation.getReceiptSerial()).thenReturn(receiptSerial);
donationPermitsManager = new DonationPermitsManager(mock(DonationPermits.class), donationsPermitSecretParams,
clock);
final RateLimiters rateLimiters = mock(RateLimiters.class);
createDonationPermitLimiter = mock(RateLimiter.class);
when(rateLimiters.getCreateDonationPermitLimiter()).thenReturn(createDonationPermitLimiter);
return new DonationsGrpcService(
clock,
zkReceiptOperations,
redeemedReceiptsManager,
accountsManager,
badgesConfiguration,
receiptCredentialPresentationFactory
receiptCredentialPresentationFactory,
donationPermitsManager,
rateLimiters
);
}
@@ -146,4 +175,50 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
assertEquals(RedeemReceiptResponse.ResponseCase.FAILED_AUTHENTICATION, response.getResponseCase());
verifyNoInteractions(account);
}
@Test
void createDonationPermit() throws Exception {
final int permitCount = 10;
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount);
final CreateDonationPermitResponse response = authenticatedServiceStub().createDonationPermit(
CreateDonationPermitRequest.newBuilder()
.setDonationPermitRequest(ByteString.copyFrom(context.request().serialize()))
.build());
final DonationPermitResponse donationPermitResponse = new DonationPermitResponse(response.getDonationPermitResponse().toByteArray());
final List<DonationPermit> donationPermits = context.receive(donationPermitResponse,
donationsPermitSecretParams.getPublicParams(),
clock.instant());
assertEquals(permitCount, donationPermits.size());
}
@Test
void createDonationPermitInvalid() throws Exception {
final int permitCount = 10;
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount);
GrpcTestUtils.assertStatusInvalidArgument(() ->
authenticatedServiceStub().createDonationPermit(CreateDonationPermitRequest.newBuilder()
.setDonationPermitRequest(ByteString.copyFrom(new byte[]{1, 2, 3}))
.build()));
}
@Test
void createDonationPermitRateLimited() throws Exception{
final Duration retryDuration = Duration.ofHours(3);
doThrow(new RateLimitExceededException(retryDuration))
.when(createDonationPermitLimiter).validate(any(UUID.class), anyLong());
final int permitCount = 10;
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount);
GrpcTestUtils.assertRateLimitExceeded(retryDuration, () ->
authenticatedServiceStub().createDonationPermit(CreateDonationPermitRequest.newBuilder()
.setDonationPermitRequest(ByteString.copyFrom(context.request().serialize()))
.build()));
}
}
@@ -23,9 +23,9 @@ import org.signal.keytransparency.client.E164MonitorRequest;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.KeyTransparencyQueryServiceGrpc;
import org.signal.keytransparency.client.MonitorRequest;
import org.signal.keytransparency.client.MonitorResponse;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchRequest;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -56,7 +56,7 @@ import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimi
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
import static org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService.COMMITMENT_INDEX_LENGTH;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@SuppressWarnings({"OptionalUsedAsFieldOrParameterType", "ThrowableNotThrown", "ResultOfMethodCallIgnored"})
public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransparencyGrpcService, KeyTransparencyQueryServiceGrpc.KeyTransparencyQueryServiceBlockingStub>{
@Mock
private KeyTransparencyServiceClient keyTransparencyServiceClient;
@@ -80,7 +80,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
@Test
void searchSuccess() throws RateLimitExceededException {
when(keyTransparencyServiceClient.search(any())).thenReturn(SearchResponse.getDefaultInstance());
when(keyTransparencyServiceClient.search(any())).thenReturn(SearchResponseV2.getDefaultInstance());
Mockito.doNothing().when(rateLimiter).validate(any(String.class));
final SearchRequest request = SearchRequest.newBuilder()
.setAci(ByteString.copyFrom(ACI.toCompactByteArray()))
@@ -90,7 +90,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
.build())
.build();
assertDoesNotThrow(() -> unauthenticatedServiceStub().search(request));
assertDoesNotThrow(() -> unauthenticatedServiceStub().searchV2(request));
verify(keyTransparencyServiceClient, times(1)).search(eq(request));
}
@@ -121,7 +121,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
lastTreeHeadSize.ifPresent(consistencyBuilder::setLast);
requestBuilder.setConsistency(consistencyBuilder.build());
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().search(requestBuilder.build()));
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().searchV2(requestBuilder.build()));
verifyNoInteractions(keyTransparencyServiceClient);
}
@@ -152,13 +152,13 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
.setDistinguished(10)
.build())
.build();
assertRateLimitExceeded(retryAfterDuration, () -> unauthenticatedServiceStub().search(request));
assertRateLimitExceeded(retryAfterDuration, () -> unauthenticatedServiceStub().searchV2(request));
verifyNoInteractions(keyTransparencyServiceClient);
}
@Test
void monitorSuccess() {
when(keyTransparencyServiceClient.monitor(any())).thenReturn(MonitorResponse.getDefaultInstance());
when(keyTransparencyServiceClient.monitor(any())).thenReturn(MonitorResponseV2.getDefaultInstance());
when(rateLimiter.validateReactive(any(String.class)))
.thenReturn(Mono.empty());
final AciMonitorRequest aciMonitorRequest = AciMonitorRequest.newBuilder()
@@ -175,7 +175,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
.build())
.build();
assertDoesNotThrow(() -> unauthenticatedServiceStub().monitor(request));
assertDoesNotThrow(() -> unauthenticatedServiceStub().monitorV2(request));
verify(keyTransparencyServiceClient, times(1)).monitor(eq(request));
}
@@ -199,7 +199,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
requestBuilder.setConsistency(consistencyBuilder.build());
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().monitor(requestBuilder.build()));
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().monitorV2(requestBuilder.build()));
}
private static Stream<Arguments> monitorInvalidRequest() {
@@ -218,9 +218,9 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
Arguments.argumentSet("Invalid username hash length", validAciMonitorRequest, Optional.empty(), Optional.of(constructUsernameHashMonitorRequest(new byte[31], new byte[32], 10)), Optional.of(4L), Optional.of(4L)),
Arguments.argumentSet("Invalid commitment index on username hash monitor request", validAciMonitorRequest, Optional.empty(), Optional.of(constructUsernameHashMonitorRequest(USERNAME_HASH, new byte[31], 10)), Optional.of(4L), Optional.of(4L)),
Arguments.argumentSet("Invalid entry position on username hash monitor request", validAciMonitorRequest, Optional.empty(), Optional.of(constructUsernameHashMonitorRequest(USERNAME_HASH, new byte[32], 0)), Optional.of(4L), Optional.of(4L)),
Arguments.argumentSet("consistency.last must be provided", validAciMonitorRequest, Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(4L),
Arguments.argumentSet("consistency.last must be provided", validAciMonitorRequest, Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(4L)),
Arguments.argumentSet("consistency.last must be positive", validAciMonitorRequest, Optional.empty(), Optional.empty(), Optional.of(0L), Optional.of(4L)),
Arguments.argumentSet("consistency.distinguished must be provided", validAciMonitorRequest, Optional.empty(), Optional.empty(), Optional.of(4L)), Optional.empty()),
Arguments.argumentSet("consistency.distinguished must be provided", validAciMonitorRequest, Optional.empty(), Optional.empty(), Optional.of(4L), Optional.empty()),
Arguments.argumentSet("consistency.distinguished must be positive", validAciMonitorRequest, Optional.empty(), Optional.empty(), Optional.of(4L), Optional.of(0L))
);
}
@@ -243,7 +243,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
.setLast(10)
.build())
.build();
assertRateLimitExceeded(retryAfterDuration, () -> unauthenticatedServiceStub().monitor(request));
assertRateLimitExceeded(retryAfterDuration, () -> unauthenticatedServiceStub().monitorV2(request));
verifyNoInteractions(keyTransparencyServiceClient);
}
@@ -254,7 +254,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
.thenReturn(Mono.empty());
final DistinguishedRequest request = DistinguishedRequest.newBuilder().build();
assertDoesNotThrow(() -> unauthenticatedServiceStub().distinguished(request));
assertDoesNotThrow(() -> unauthenticatedServiceStub().distinguishedV2(request));
verify(keyTransparencyServiceClient, times(1)).distinguished(eq(request));
}
@@ -264,7 +264,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
.setLast(0)
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().distinguished(request));
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().distinguishedV2(request));
verifyNoInteractions(keyTransparencyServiceClient);
}
@@ -277,7 +277,7 @@ public class KeyTransparencyGrpcServiceTest extends SimpleBaseGrpcTest<KeyTransp
.setLast(10)
.build();
assertRateLimitExceeded(retryAfterDuration, () -> unauthenticatedServiceStub().distinguished(request));
assertRateLimitExceeded(retryAfterDuration, () -> unauthenticatedServiceStub().distinguishedV2(request));
verifyNoInteractions(keyTransparencyServiceClient);
}
@@ -0,0 +1,336 @@
/*
* Copyright 2026 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.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import com.stripe.model.PaymentIntent;
import jakarta.annotation.Nullable;
import java.time.Instant;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
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.mockito.Mock;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostRequest;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostResponse;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsRequest;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsResponse;
import org.signal.chat.one_time_donations.CreateBoostRequest;
import org.signal.chat.one_time_donations.CreateBoostResponse;
import org.signal.chat.one_time_donations.CreatePayPalBoostRequest;
import org.signal.chat.one_time_donations.CreatePayPalBoostResponse;
import org.signal.chat.one_time_donations.OneTimeDonationsGrpc;
import org.signal.chat.subscriptions.PaymentMethod;
import org.signal.chat.subscriptions.PaymentProvider;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
public class OneTimeDonationsGrpcServiceTest extends
SimpleBaseGrpcTest<OneTimeDonationsGrpcService, OneTimeDonationsGrpc.OneTimeDonationsBlockingStub> {
private final TestClock clock = TestClock.pinned(Instant.now());
private final OneTimeDonationConfiguration oneTimeDonationConfiguration =
SubscriptionConfigTestHelper.getOneTimeConfig();
@Mock
private DonationPermits donationPermits;
private static final ServerSecretParams DONATION_PERMITS_SECRET_PARAMS = ServerSecretParams.generate();
private DonationPermitsManager donationPermitsManager;
@Mock
private StripeManager stripeManager;
@Mock
private BraintreeManager braintreeManager;
@Mock
private PayPalDonationsTranslator payPalDonationsTranslator;
@Mock
private OneTimeDonationsManager oneTimeDonationsManager;
@Mock
private IssuedReceiptsManager issuedReceiptsManager;
@Mock
private ServerZkReceiptOperations zkReceiptOperations;
@Mock
private RateLimiters rateLimiters;
@Mock
private RateLimiter rateLimiter;
@Override
protected OneTimeDonationsGrpcService createServiceBeforeEachTest() {
getMockRequestAttributesInterceptor().setRequestAttributes(
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-us"));
donationPermitsManager = new DonationPermitsManager(donationPermits, DONATION_PERMITS_SECRET_PARAMS, clock);
// spendIds are spend-once
final Set<String> spent = new HashSet<>();
when(donationPermits.spend(any(byte[].class), any(Instant.class)))
.thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class))));
when(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION)).thenReturn(rateLimiter);
return new OneTimeDonationsGrpcService(
oneTimeDonationConfiguration,
stripeManager,
braintreeManager,
payPalDonationsTranslator,
oneTimeDonationsManager,
issuedReceiptsManager,
zkReceiptOperations,
clock,
rateLimiters,
donationPermitsManager);
}
@Test
void createBoost() {
final PaymentIntent paymentIntent = mock(PaymentIntent.class);
when(paymentIntent.getClientSecret()).thenReturn("test-client-secret");
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
.thenReturn(Set.of("usd"));
when(stripeManager.createPaymentIntent(any(), anyLong(), anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(paymentIntent));
final CreateBoostResponse response = unauthenticatedServiceStub().createBoost(
CreateBoostRequest.newBuilder()
.setCurrency("usd")
.setAmount(500)
.setLevel(1)
.setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD)
.setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize()))
.build());
assertEquals(CreateBoostResponse.ResponseCase.CLIENT_SECRET, response.getResponseCase());
assertEquals("test-client-secret", response.getClientSecret());
}
@Test
void createBoostPermitAlreadySpent() {
when(donationPermits.spend(any(byte[].class), any(Instant.class))).thenReturn(false);
final CreateBoostResponse response = unauthenticatedServiceStub().createBoost(
CreateBoostRequest.newBuilder()
.setCurrency("usd")
.setAmount(500)
.setLevel(1)
.setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD)
.setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize()))
.build());
assertEquals(CreateBoostResponse.ResponseCase.PERMIT_REJECTED, response.getResponseCase());
}
@ParameterizedTest
@MethodSource
void createBoostValidationErrors(
final String currency,
final long amount,
final PaymentMethod paymentMethod,
final CreateBoostResponse.ResponseCase expectedResponseCase) {
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
.thenReturn(Set.of("usd"));
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT))
.thenReturn(Set.of("eur"));
final CreateBoostResponse response = unauthenticatedServiceStub().createBoost(
CreateBoostRequest.newBuilder()
.setCurrency(currency)
.setAmount(amount)
.setLevel(1)
.setPaymentMethod(paymentMethod)
.setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize()))
.build());
assertEquals(expectedResponseCase, response.getResponseCase());
}
static Stream<Arguments> createBoostValidationErrors() {
return Stream.of(
Arguments.of("usd", 249L, PaymentMethod.PAYMENT_METHOD_CARD,
CreateBoostResponse.ResponseCase.AMOUNT_BELOW_MINIMUM),
Arguments.of("eur", 1000001L, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT,
CreateBoostResponse.ResponseCase.AMOUNT_ABOVE_SEPA_LIMIT),
// USD is not supported for SEPA_DEBIT
Arguments.of("usd", 3000L, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT,
CreateBoostResponse.ResponseCase.UNSUPPORTED_CURRENCY)
);
}
@Test
void createPayPalBoost() {
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
mock(BraintreeManager.PayPalOneTimePaymentApprovalDetails.class);
when(approvalDetails.approvalUrl()).thenReturn("test-approval-url");
when(approvalDetails.paymentId()).thenReturn("test-id");
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd"));
when(payPalDonationsTranslator.translate(any(), any()))
.thenReturn("Donation to Signal Technology Foundation");
when(braintreeManager.createOneTimePayment(anyString(), anyLong(), anyString(), anyString(), anyString(),
anyString()))
.thenReturn(CompletableFuture.completedFuture(approvalDetails));
final CreatePayPalBoostResponse response = unauthenticatedServiceStub().createPayPalBoost(
CreatePayPalBoostRequest.newBuilder()
.setCurrency("usd")
.setAmount(300)
.setLevel(1)
.setReturnUrl("returnUrl")
.setCancelUrl("cancelUrl")
.build());
assertEquals(CreatePayPalBoostResponse.ResponseCase.RESULT, response.getResponseCase());
assertEquals("test-approval-url", response.getResult().getApprovalUrl());
assertEquals("test-id", response.getResult().getPaymentId());
}
@Test
void confirmPayPalBoost() {
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd"));
when(braintreeManager.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(
new BraintreeManager.PayPalChargeSuccessDetails("test-id")));
final ConfirmPayPalBoostResponse response = unauthenticatedServiceStub().confirmPayPalBoost(
ConfirmPayPalBoostRequest.newBuilder()
.setCurrency("usd")
.setAmount(300)
.setLevel(1)
.setPayerId("test-payer-id")
.setPaymentId("test-payment-id")
.setPaymentToken("test-payment-token")
.build());
assertEquals(ConfirmPayPalBoostResponse.ResponseCase.RESULT, response.getResponseCase());
assertEquals("test-id", response.getResult().getPaymentId());
}
@ParameterizedTest
@MethodSource
void createBoostReceiptCredentialsPaymentRequired(
@Nullable final ChargeFailure chargeFailure,
final boolean expectChargeFailure) {
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.FAILED,
clock.instant(), chargeFailure))));
final CreateBoostReceiptCredentialsResponse response =
unauthenticatedServiceStub().createBoostReceiptCredentials(
CreateBoostReceiptCredentialsRequest.newBuilder()
.setPaymentIntentId("test-payment-intent-id")
.setReceiptCredentialRequest(ByteString.copyFromUtf8("abcd"))
.setProcessor(PaymentProvider.PAYMENT_PROVIDER_STRIPE)
.build());
assertEquals(CreateBoostReceiptCredentialsResponse.ResponseCase.PAYMENT_REQUIRED,
response.getResponseCase());
if (expectChargeFailure) {
assertEquals("generic_decline", response.getPaymentRequired().getChargeFailure().getCode());
} else {
assertFalse(response.getPaymentRequired().hasChargeFailure());
}
}
static Stream<Arguments> createBoostReceiptCredentialsPaymentRequired() {
return Stream.of(
Arguments.of(new ChargeFailure("generic_decline", "some failure message", null, null, null), true),
Arguments.of(null, false)
);
}
@Test
void createBoostReceiptCredentialsAlreadyRedeemed() throws Exception {
final ReceiptCredentialRequest receiptCredentialRequest = new ClientZkReceiptOperations(
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.SUCCEEDED,
clock.instant(), null))));
doThrow(WriteConflictException.class).when(issuedReceiptsManager)
.recordIssuance(any(), any(), any(), any());
final CreateBoostReceiptCredentialsResponse response =
unauthenticatedServiceStub().createBoostReceiptCredentials(
CreateBoostReceiptCredentialsRequest.newBuilder()
.setPaymentIntentId("test-payment-intent-id")
.setReceiptCredentialRequest(ByteString.copyFrom(receiptCredentialRequest.serialize()))
.setProcessor(PaymentProvider.PAYMENT_PROVIDER_STRIPE)
.build());
assertEquals(CreateBoostReceiptCredentialsResponse.ResponseCase.RECEIPT_ALREADY_ISSUED,
response.getResponseCase());
}
private DonationPermit getDonationPermit() {
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(1);
final DonationPermitRequest permitRequest = context.request();
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
try {
final List<DonationPermit> permits = context.receive(
permitResponse, DONATION_PERMITS_SECRET_PARAMS.getPublicParams(), clock.instant());
return permits.getFirst();
} catch (final VerificationFailedException e) {
throw new AssertionError("The permit was correctly requested and issued in this method", e);
}
}
}
@@ -13,6 +13,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -20,12 +22,15 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusInvalidArgument;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import io.grpc.ServerInterceptor;
import com.google.rpc.BadRequest;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
@@ -38,6 +43,7 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
@@ -50,6 +56,12 @@ import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.DeleteAvatarRequest;
import org.signal.chat.profile.DeleteAvatarResponse;
import org.signal.chat.profile.ExtendAvatarTTLRequest;
import org.signal.chat.profile.ExtendAvatarTTLResponse;
import org.signal.chat.profile.GetAvatarUploadFormRequest;
import org.signal.chat.profile.GetAvatarUploadFormResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
@@ -66,8 +78,13 @@ import org.signal.chat.profile.ProfileAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
@@ -78,9 +95,13 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
@@ -89,6 +110,8 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.MutableClock;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -108,8 +131,15 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@Mock
private ProfileBadgeConverter profileBadgeConverter;
@Mock
private RateLimiter profileAvatarBytesRateLimiter;
private ServerZkProfileOperations zkProfileOperations;
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
private MutableClock clock;
@Override
protected ProfileAnonymousGrpcService createServiceBeforeEachTest() {
getMockRequestAttributesInterceptor().setRequestAttributes(new RequestAttributes(InetAddresses.forString("127.0.0.1"),
@@ -118,12 +148,21 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
zkProfileOperations = spy(new ServerZkProfileOperations(SERVER_SECRET_PARAMS));
final RateLimiters rateLimiters = mock(RateLimiters.class);
when(rateLimiters.getProfileAvatarBytesLimiter()).thenReturn(profileAvatarBytesRateLimiter);
clock = new MutableClock();
return new ProfileAnonymousGrpcService(
accountsManager,
profilesManager,
profileBadgeConverter,
new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey", "accessSecret"),
genericServerSecretParams,
rateLimiters,
clock,
zkProfileOperations,
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, Clock.systemUTC())
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, clock)
);
}
@@ -788,12 +827,182 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
);
}
@Override
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
return serverInterceptors.stream()
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
// updated error model
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
.toList();
@Test
void getAvatarUploadForm() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(100)
.build();
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
assertTrue(response.hasAvatarUploadForm());
final String avatarPath = response.getAvatarUploadForm().getKey();
assertFalse(avatarPath.isEmpty());
verify(profilesManager).setAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()), eq(avatarPath));
}
@Test
void getAvatarUploadFormInvalidUploadLength() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(Math.toIntExact(ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES + 1))
.build();
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
() -> authenticatedServiceStub().getAvatarUploadForm(request));
final List<BadRequest.FieldViolation> fieldViolations = GrpcTestUtils.extractDetail(BadRequest.class, statusRuntimeException)
.getFieldViolationsList();
assertEquals(1, fieldViolations.size());
assertEquals("upload_length", fieldViolations.getFirst().getField());
}
@Test
void getAvatarUploadFormInvalidCredentialsPresentation() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(100)
.build();
// trigger a verification failure by advancing the clock beyond validity
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
assertTrue(response.hasInvalidCredentialsPresentation());
}
@Test
void getAvatarUploadFormRateLimited() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final Duration retryDuration = Duration.ofMinutes(20);
doThrow(new RateLimitExceededException(retryDuration))
.when(profileAvatarBytesRateLimiter).validate(anyString(), anyLong());
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(100)
.build();
assertRateLimitExceeded(retryDuration,
() -> authenticatedServiceStub().getAvatarUploadForm(request),
profilesManager);
}
@Test
void extendAvatarTtl() throws Exception {
final String path = "somePath";
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.of(path));
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
assertTrue(response.hasPath());
assertEquals(path, response.getPath());
}
@Test
void extendAvatarTtlNoActiveAvatar() throws Exception {
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.empty());
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
assertTrue(response.hasNotFound());
}
@Test
void extendAvatarTtlInvalidCredentialsPresentation() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
// trigger a verification failure by advancing the clock beyond validity
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
assertTrue(response.hasInvalidCredentialsPresentation());
}
@Test
void deleteAvatar() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
assertTrue(response.hasSuccess());
verify(profilesManager).deleteAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()));
}
@Test
void deleteAvatarInvalidCredentialsPresentation() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
// trigger a verification failure by advancing the clock beyond validity
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
assertTrue(response.hasInvalidCredentialsPresentation());
}
static AvatarUploadCredentialPresentation getAvatarUploadCredentialPresentation(final GenericServerSecretParams serverSecretParams, final Clock clock) throws VerificationFailedException {
final ServiceId.Aci aci = new ServiceId.Aci(UUID.randomUUID());
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
final long rotationId = ThreadLocalRandom.current().nextLong();
final AvatarUploadCredentialRequestContext context = AvatarUploadCredentialRequestContext.create(
aci,
zkCredentialKeyPair, rotationId);
final AvatarUploadCredentialResponse avatarUploadCredentialResponse = context.getRequest()
.issueCredential(aci, zkCredentialKeyPair.getPublicKey(), rotationId, clock.instant().truncatedTo(ChronoUnit.DAYS), serverSecretParams);
return context.receiveResponse(avatarUploadCredentialResponse, clock.instant(),
serverSecretParams.getPublicParams()).present(serverSecretParams.getPublicParams());
}
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.grpc;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -31,7 +32,6 @@ import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.protobuf.ByteString;
import com.google.rpc.BadRequest;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.time.Clock;
@@ -60,6 +60,8 @@ import org.mockito.Mock;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetAvatarCredentialsRequest;
import org.signal.chat.profile.GetAvatarCredentialsResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileResult;
@@ -77,7 +79,12 @@ import org.signal.chat.profile.test.PlaintextProfileData;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
@@ -106,6 +113,7 @@ import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.MutableClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -122,6 +130,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setPhoneNumberSharing(ByteString.copyFrom(TestRandomUtil.nextBytes(29)))
.build();
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
@Mock
private AccountsManager accountsManager;
@@ -143,11 +153,11 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@Mock
private ProfileBadgeConverter profileBadgeConverter;
private Clock clock;
private MutableClock clock;
@Override
protected ProfileGrpcService createServiceBeforeEachTest() {
clock = Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC"));
clock = new MutableClock(Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC")));
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
@@ -208,6 +218,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
dynamicConfigurationManager,
badgesConfiguration,
policyGenerator,
genericServerSecretParams,
profileBadgeConverter,
rateLimiters
);
@@ -893,13 +904,77 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
}
@Override
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
return serverInterceptors.stream()
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
// updated error model
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
.toList();
@Test
void getAvatarCredential() {
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
final long rotationId = 617L;
// this test needs a valid clock
clock.setTimeMillis(Instant.now().toEpochMilli());
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, rotationId);
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
GetAvatarCredentialsRequest.newBuilder()
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
.build());
assertTrue(response.hasAvatarCredentials());
assertDoesNotThrow(() -> avatarUploadCredentialRequestContext.receiveResponse(
new AvatarUploadCredentialResponse(response.getAvatarCredentials().toByteArray()),
genericServerSecretParams.getPublicParams()));
}
@Test
void getAvatarCredentialAccountNotFound() {
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.empty());
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
() -> authenticatedServiceStub().getAvatarCredentials(GetAvatarCredentialsRequest.getDefaultInstance()));
assertEquals("account not found", statusRuntimeException.getStatus().getDescription());
}
@Test
void getAvatarCredentialMissingZkCredentialKey() {
when(account.getZkCredentialKey()).thenReturn(Optional.empty());
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
GetAvatarCredentialsRequest.getDefaultInstance());
assertTrue(response.hasMissingZkCredentialKey());
assertEquals("account requires ZK credential key", response.getMissingZkCredentialKey().getDescription());
}
@Test
void getAvatarCredentialInvalidCredentialRequest() {
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
final long rotationId = 617L;
final long incorrectRotationId = rotationId + 1;
// this test needs a valid clock
clock.setTimeMillis(Instant.now().toEpochMilli());
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, incorrectRotationId);
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
() -> authenticatedServiceStub().getAvatarCredentials(
GetAvatarCredentialsRequest.newBuilder()
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
.build()));
assertEquals("invalid credential request", statusRuntimeException.getStatus().getDescription());
}
@ParameterizedTest
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -19,8 +20,9 @@ import static org.mockito.Mockito.when;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -33,10 +35,10 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.signal.chat.subscriptions.CreatePaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePaymentMethodResponse;
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse;
import org.signal.chat.subscriptions.CreatePaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePaymentMethodResponse;
import org.signal.chat.subscriptions.DeleteSubscriberRequest;
import org.signal.chat.subscriptions.DeleteSubscriberResponse;
import org.signal.chat.subscriptions.GetBankMandateRequest;
@@ -57,6 +59,12 @@ import org.signal.chat.subscriptions.SetSubscriptionLevelResponse;
import org.signal.chat.subscriptions.SubscriptionsGrpc;
import org.signal.chat.subscriptions.UpdateSubscriberRequest;
import org.signal.chat.subscriptions.UpdateSubscriberResponse;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
@@ -66,6 +74,8 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -78,6 +88,7 @@ import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
@@ -86,6 +97,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumen
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPrice;
@@ -101,7 +113,7 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
public class SubscriptionsGrpcServiceTest extends
SimpleBaseGrpcTest<SubscriptionsGrpcService, SubscriptionsGrpc.SubscriptionsBlockingStub> {
private final Clock clock = TestClock.pinned(Instant.ofEpochSecond(100));
private final TestClock clock = TestClock.pinned(Instant.now());
private final SubscriptionConfiguration subscriptionConfiguration =
SubscriptionConfigTestHelper.getSubscriptionConfig();
@@ -109,6 +121,12 @@ public class SubscriptionsGrpcServiceTest extends
private final OneTimeDonationConfiguration oneTimeDonationConfiguration =
SubscriptionConfigTestHelper.getOneTimeConfig();
@Mock
private DonationPermits donationPermits;
private static final ServerSecretParams DONATION_PERMITS_SECRET_PARAMS = ServerSecretParams.generate();
private DonationPermitsManager donationPermitsManager;
@Mock
private SubscriptionManager subscriptionManager;
@@ -141,9 +159,17 @@ public class SubscriptionsGrpcServiceTest extends
protected SubscriptionsGrpcService createServiceBeforeEachTest() {
getMockRequestAttributesInterceptor().setRequestAttributes(
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-us"));
donationPermitsManager = new DonationPermitsManager(donationPermits, DONATION_PERMITS_SECRET_PARAMS, clock);
// spendIds are spend-once
final Set<String> spent = new HashSet<>();
when(donationPermits.spend(any(byte[].class), any(Instant.class)))
.thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class))));
return new SubscriptionsGrpcService(clock, subscriptionConfiguration, oneTimeDonationConfiguration,
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
badgeTranslator, bankMandateTranslator, dynamicConfigurationManager);
subscriptionManager, donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager,
appleAppStoreManager, badgeTranslator, bankMandateTranslator, dynamicConfigurationManager);
}
@Test
@@ -156,9 +182,36 @@ public class SubscriptionsGrpcServiceTest extends
}
@Test
void updateSubscriberIdMismatch() throws SubscriptionForbiddenException {
void updateSubscriberCreationNotPermittedPermitRejected() throws SubscriptionException {
doThrow(new SubscriberIdCreationNotPermittedException())
.when(subscriptionManager).updateSubscriber(any(), eq(false));
final DonationPermit donationPermit = getDonationPermit();
clock.pin(clock.instant().plus(Duration.ofDays(14)));
final UpdateSubscriberResponse response = unauthenticatedServiceStub().updateSubscriber(
UpdateSubscriberRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
.setDonationPermit(ByteString.copyFrom(donationPermit.serialize()))
.build());
assertTrue(response.hasPermitRejected());
}
@Test
void updateSubscriberCreationNotPermittedMissingPermit() throws SubscriptionException {
doThrow(new SubscriberIdCreationNotPermittedException())
.when(subscriptionManager).updateSubscriber(any(), eq(false));
GrpcTestUtils.assertStatusInvalidArgument(() -> unauthenticatedServiceStub().updateSubscriber(
UpdateSubscriberRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
.build()));
}
@Test
void updateSubscriberIdMismatch() throws SubscriptionException {
doThrow(new SubscriptionForbiddenException("subscriberId mismatch"))
.when(subscriptionManager).updateSubscriber(any());
.when(subscriptionManager).updateSubscriber(any(), anyBoolean());
final UpdateSubscriberResponse response = unauthenticatedServiceStub().updateSubscriber(
UpdateSubscriberRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
@@ -206,8 +259,10 @@ public class SubscriptionsGrpcServiceTest extends
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any())).thenReturn("test-client-secret");
when(stripeManager.getProvider()).thenReturn(PaymentProvider.STRIPE);
final CreatePaymentMethodRequest.Builder builder = CreatePaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
.setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize()))
.setPaymentMethod(paymentMethod);
final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod(builder.build());
assertEquals(CreatePaymentMethodResponse.ResponseCase.RESULT, response.getResponseCase());
@@ -227,6 +282,34 @@ public class SubscriptionsGrpcServiceTest extends
.build()));
}
@Test
void createPaymentMethodInvalidDonationPermit() {
GrpcTestUtils.assertStatusInvalidArgument(
() -> unauthenticatedServiceStub().createPaymentMethod(
CreatePaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
.setDonationPermit(ByteString.copyFrom(new byte[]{1}))
.setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD)
.build()));
}
@Test
void createPaymentMethodExpiredDonationPermit() {
when(stripeManager.getProvider()).thenReturn(PaymentProvider.STRIPE);
final DonationPermit donationPermit = getDonationPermit();
clock.pin(clock.instant().plus(Duration.ofDays(30)));
final CreatePaymentMethodResponse createPaymentMethodResponse = unauthenticatedServiceStub().createPaymentMethod(
CreatePaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
.setDonationPermit(ByteString.copyFrom(donationPermit.serialize()))
.setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD)
.build());
assertTrue(createPaymentMethodResponse.hasPermitRejected());
}
@Test
void createPaymentMethodProcessorConflict()
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
@@ -235,6 +318,7 @@ public class SubscriptionsGrpcServiceTest extends
final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod(
CreatePaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
.setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize()))
.setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD)
.build());
assertEquals(CreatePaymentMethodResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT, response.getResponseCase());
@@ -511,7 +595,7 @@ public class SubscriptionsGrpcServiceTest extends
final byte[] responseBytes = TestRandomUtil.nextBytes(16);
when(receiptCredentialResponse.serialize()).thenReturn(responseBytes);
when(subscriptionManager.createReceiptCredentials(any(), any(), any()))
.thenReturn(new SubscriptionManager.ReceiptResult(receiptCredentialResponse, null, PaymentProvider.STRIPE));
.thenReturn(new SubscriptionManager.ReceiptResult(receiptCredentialResponse, new SubscriptionPaymentProcessor.ReceiptItem("test-item-id", null, 5), PaymentProvider.STRIPE));
final GetReceiptCredentialsResponse response = unauthenticatedServiceStub().getReceiptCredentials(
GetReceiptCredentialsRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
@@ -721,4 +805,20 @@ public class SubscriptionsGrpcServiceTest extends
assertEquals("test-mandate", response.getMandate());
}
private DonationPermit getDonationPermit() {
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(1);
final DonationPermitRequest permitRequest = context.request();
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
try {
final List<DonationPermit> donationPermits = context.receive(permitResponse,
DONATION_PERMITS_SECRET_PARAMS.getPublicParams(), clock.instant());
return donationPermits.getFirst();
} catch (final VerificationFailedException e) {
throw new AssertionError("The permit was correctly requested and issued in this method", e);
}
}
}
@@ -445,6 +445,79 @@ public class ValidatingInterceptorTest {
stub.validationsEndpoint(builderWithValidDefaults().build());
}
@Test
public void eachExactlySize() {
assertDoesNotThrow(() -> stub.validationsEndpoint(builderWithValidDefaults().build()));
assertDoesNotThrow(() -> stub.validationsEndpoint(builderWithValidDefaults()
.addEachExactlyBytes(ByteString.copyFrom(new byte[4]))
.addEachExactlyBytes(ByteString.copyFrom(new byte[4]))
.build()));
// second element is the wrong length
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.addEachExactlyBytes(ByteString.copyFrom(new byte[4]))
.addEachExactlyBytes(ByteString.copyFrom(new byte[3]))
.build()));
}
@Test
public void eachRange() {
assertDoesNotThrow(() -> stub.validationsEndpoint(builderWithValidDefaults()
.addEachRange(1)
.addEachRange(127)
.build()));
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.addEachRange(0)
.build()));
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.addEachRange(128)
.build()));
}
@Test
public void eachNonEmpty() {
assertDoesNotThrow(() -> stub.validationsEndpoint(builderWithValidDefaults()
.addEachNonEmpty("a")
.build()));
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.addEachNonEmpty("a")
.addEachNonEmpty("")
.build()));
}
@Test
public void eachCombinedWithCollectionConstraint() {
// empty list fails the collection-level `size {min:1}` constraint
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.clearEachCombined()
.build()));
// too many elements (collection-level `size {max:3}`)
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.clearEachCombined()
.addEachCombined(ByteString.copyFrom(new byte[4]))
.addEachCombined(ByteString.copyFrom(new byte[4]))
.addEachCombined(ByteString.copyFrom(new byte[4]))
.addEachCombined(ByteString.copyFrom(new byte[4]))
.build()));
// count is in range but an element is the wrong length
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
.clearEachCombined()
.addEachCombined(ByteString.copyFrom(new byte[3]))
.build()));
// both constraints satisfied
assertDoesNotThrow(() -> stub.validationsEndpoint(builderWithValidDefaults()
.clearEachCombined()
.addEachCombined(ByteString.copyFrom(new byte[4]))
.addEachCombined(ByteString.copyFrom(new byte[4]))
.build()));
}
@Test
public void testFailedValidationOnNestedMessage() {
assertStatusException(Status.INVALID_ARGUMENT, () ->
@@ -528,7 +601,8 @@ public class ValidatingInterceptorTest {
.setPniServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build());
.build())
.addEachCombined(ByteString.copyFrom(new byte[4]));
}
private static void assertStatusException(final Status expected, final Executable serviceCall) {
@@ -36,6 +36,7 @@ import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
@@ -51,6 +52,7 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.test.LeakPresenceExtension;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -69,10 +71,12 @@ import javax.annotation.Nullable;
import javax.net.ssl.SSLException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicOmnibusConfiguration;
@ExtendWith(LeakPresenceExtension.class)
class OmnibusH2ServerTest {
@@ -88,11 +92,13 @@ class OmnibusH2ServerTest {
private List<Channel> backendChannelsToShutDown;
private List<OmnibusH2Server> omnibusH2ServersToShutDown;
private AtomicReference<DynamicOmnibusConfiguration> dynamicConfiguration;
@BeforeEach
void setUp() {
backendChannelsToShutDown = new ArrayList<>();
omnibusH2ServersToShutDown = new ArrayList<>();
dynamicConfiguration = new AtomicReference<>(new DynamicOmnibusConfiguration(BigDecimal.ZERO));
}
@AfterEach
@@ -389,6 +395,41 @@ class OmnibusH2ServerTest {
timeoutServer.stop();
}
@Test
void loadShed() throws Exception {
dynamicConfiguration.set(new DynamicOmnibusConfiguration(BigDecimal.ONE));
final OmnibusH2Server server = startOmnibusServer(
Map.of(PREFIX, startBackendServer(true, PREFIX_BACKEND_IDENTITY)),
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
final CompletableFuture<Http2GoAwayFrame> goAwayFuture = new CompletableFuture<>();
final Bootstrap clientBootstrap = new Bootstrap()
.group(nioEventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel ch) {
final SslContext clientSsl = sslContext();
ch.pipeline().addLast(clientSsl.newHandler(ch.alloc(), server.getLocalAddress().getHostName(),
server.getLocalAddress().getPort()));
ch.pipeline()
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof Http2GoAwayFrame g) {
goAwayFuture.complete(g);
}
ctx.fireChannelRead(msg);
}
});
}
});
clientBootstrap.connect(server.getLocalAddress()).syncUninterruptibly().channel();
final Http2GoAwayFrame frame = goAwayFuture.get(1, TimeUnit.SECONDS);
assertEquals(OmnibusLoadShedHandler.LOAD_SHED_ERROR_CODE, frame.errorCode());
}
/// Start an OmnibusH2Server. The returned server and provided backends will be torn down in [#tearDown()]
///
/// @param routes A map of prefixes and the corresponding backend server channels the omnibus will target
@@ -409,6 +450,7 @@ class OmnibusH2ServerTest {
new OmnibusRouter(
routes.entrySet().stream().map(entry -> new OmnibusRouter.OmnibusRoute(entry.getKey(), entry.getValue().localAddress())).toList(),
defaultBackend.localAddress()),
dynamicConfiguration::get,
timeout);
server.start();
omnibusH2ServersToShutDown.add(server);
@@ -459,19 +501,7 @@ class OmnibusH2ServerTest {
/// Makes an H2 connection to the omnibus at [this#server] on which new H2 streams can be opened
private Channel connectToOmnibus(final OmnibusH2Server server, @Nullable final HAProxyMessage proxyHeader) {
final SslContext clientSsl;
try {
clientSsl = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
final SslContext clientSsl = sslContext();
final Bootstrap clientBootstrap = new Bootstrap()
.group(nioEventLoopGroup)
@@ -504,6 +534,21 @@ class OmnibusH2ServerTest {
return connectToOmnibus(server, null);
}
private static SslContext sslContext() {
try {
return SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
}
private String sendRequestThroughOmnibus(final Channel h2Connection, final String path) {
final CompletableFuture<String> responseFuture = new CompletableFuture<>();
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
@@ -23,6 +23,7 @@ import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil.assertFailsWithCause;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -49,7 +50,6 @@ import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
@@ -59,6 +59,7 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -471,7 +472,7 @@ class AccountsTest {
}
@Test
void testReclaimAccountPreservesFields() {
void testReclaimAccountPreservesFields() throws Exception {
final String e164 = "+14151112222";
final UUID existingUuid = UUID.randomUUID();
final Account existingAccount =
@@ -479,7 +480,7 @@ class AccountsTest {
// the backup credential request and share-set are always preserved across account reclaims
existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
createAccount(existingAccount);
final Account secondAccount =
generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
@@ -491,11 +492,11 @@ class AccountsTest {
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElseThrow());
assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow())
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow());
assertThat(reclaimed.getZkCredentialKey()).isEqualTo(existingAccount.getZkCredentialKey());
assertThat(reclaimed.getZkCredentialKey()).hasValue(existingAccount.getZkCredentialKey().orElseThrow());
}
@Test
void testReclaimAccount() throws UsernameHashNotAvailableException {
void testReclaimAccount() throws Exception {
final String e164 = "+14151112222";
final Device device = generateDevice(DEVICE_ID_1);
final UUID existingUuid = UUID.randomUUID();
@@ -506,7 +507,7 @@ class AccountsTest {
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
existingAccount.setBackupVoucher(bv);
// ZK credential keys should be carried over across re-registration
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
createAccount(existingAccount);
@@ -0,0 +1,146 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
class AcknowledgementMirroringMessageStreamTest {
private RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private FoundationDbMessageStream foundationDbMessageStream;
private AcknowledgementMirroringMessageStream mirroringMessageStream;
private static long serialMessageTimestamp = 0;
private enum UUIDVersion {
V4,
V8
}
@BeforeEach
void setUp() {
redisDynamoDbMessageStream = mock(RedisDynamoDbMessageStream.class);
when(redisDynamoDbMessageStream.acknowledgeMessage(any(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(null));
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
when(foundationDbMessageStream.acknowledgeMessage(any(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(null));
mirroringMessageStream = new AcknowledgementMirroringMessageStream(
redisDynamoDbMessageStream,
foundationDbMessageStream);
}
@ParameterizedTest
@EnumSource(UUIDVersion.class)
void acknowledgeMessages(final UUIDVersion uuidVersion) {
final List<MessageStreamEntry> entries = new ArrayList<>();
{
for (int i = 0; i < AcknowledgementMirroringMessageStream.FOUNDATIONDB_REQUEST_SIZE + 1; i++) {
entries.add(generateEnvelopeEntry(uuidVersion));
}
entries.add(new MessageStreamEntry.QueueEmpty());
}
when(redisDynamoDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
when(foundationDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(
uuidVersion == UUIDVersion.V8 ? entries : Collections.emptyList())));
JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
message.getServerTimestamp());
}
})
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
.then()
.block();
if (uuidVersion == UUIDVersion.V8) {
entries.stream()
.filter(streamEntry -> streamEntry instanceof MessageStreamEntry.Envelope)
.map(streamEntry -> ((MessageStreamEntry.Envelope) streamEntry).message())
.forEach(envelope -> verify(foundationDbMessageStream).acknowledgeMessage(
UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp()));
} else {
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
}
}
@Test
void acknowledgeMessagesOverflow() {
final List<MessageStreamEntry> entries = new ArrayList<>();
{
for (int i = 0; i < AcknowledgementMirroringMessageStream.MAX_PENDING_ACKNOWLEDGEMENTS + 1; i++) {
entries.add(generateEnvelopeEntry(UUIDVersion.V8));
}
entries.add(new MessageStreamEntry.QueueEmpty());
}
when(redisDynamoDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
when(foundationDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.empty()));
assertThrows(IllegalStateException.class,
() -> JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
message.getServerTimestamp());
}
})
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
.then()
.block());
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
}
private static MessageStreamEntry.Envelope generateEnvelopeEntry(final UUIDVersion uuidVersion) {
final UUID messageGuid = switch (uuidVersion) {
case V4 -> UUID.randomUUID();
case V8 -> MessageGuidUtil.generateRandomV8UUID();
};
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder()
.setServerGuid(UUIDUtil.toByteString(messageGuid))
.setServerTimestamp(serialMessageTimestamp++)
.build());
}
}
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more