Compare commits

...
Author SHA1 Message Date
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
Ravi Khadiwala ac720595e6 Add header to disable messages on authenticated websocket 2026-06-18 15:28:41 -05:00
Jonathan Klabunde Tomer 8deb5a803a foundationdb "versionstamp clock" 2026-06-18 13:27:59 -07:00
Jon Chambers 45f96cd702 Delete messages from FoundationDB asynchronously 2026-06-18 14:06:26 -04:00
Chris Eager 4a3275ad63 Add POST /v1/donation/permit 2026-06-18 13:06:18 -05:00
Ameya Lokare 911feceacb Handle "no sender available" error code from registration service 2026-06-18 09:03:02 -04:00
Jon Chambers fe0956c8f7 Don't add Dropwizard metrics to shared registries 2026-06-18 09:02:33 -04:00
Jon Chambers 60002a8a0f Port StickerController to gRPC 2026-06-18 08:51:00 -04:00
Ameya Lokare 1876b71d39 Port SubscriptionController to gRPC 2026-06-18 08:27:38 -04:00
Jon Chambers 3cfe8b9f6c Mirror message writes/deletions to FoundationDB 2026-06-18 08:27:03 -04:00
Jon Chambers 691a4162e1 Update to the latest version of the spam filter 2026-06-18 08:25:07 -04:00
Ravi Khadiwala 9505e7b1a1 Fix incorrect mockito matcher in BackupManagerTest 2026-06-17 12:43:34 -05:00
Jon Chambers 569f4f31e8 Update to the latest version of the spam filter 2026-06-17 08:46:11 -04:00
Ravi Khadiwala 06519ce9d1 Use uint64 for backups.proto object length 2026-06-17 08:45:43 -04:00
Jon Chambers 024fa9ce5f Move "active epoch" configuration from dynamic to static configuration 2026-06-17 08:35:07 -04:00
Jon Chambers 7c9e3d029b Remove an unused availableProcessors variable 2026-06-17 08:33:29 -04:00
Jon Chambers cc6ef53f91 Retire unused methods in MessagesManager 2026-06-17 08:33:29 -04:00
Ravi Khadiwala 4c0f454209 Add a generic STREAM_CLOSED status 2026-06-17 08:32:47 -04:00
Chris Eager 9c393972e9 Update to the latest version of the spam filter 2026-06-16 20:02:56 -05:00
Jon Chambers 31c1bb8940 Support multiple "configuration epochs" of the FoundationDB message store 2026-06-16 09:06:18 -04:00
Jon Chambers c3b2b43813 Port CallLinkController to gRPC 2026-06-16 09:02:24 -04:00
Jon Chambers 19f2574799 Update to the latest version of the spam filter 2026-06-16 09:02:03 -04:00
148 changed files with 7294 additions and 1952 deletions

No files matched your search

+7 -7
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:
@@ -61,7 +61,7 @@ jobs:
- name: Download and install FoundationDB client
run: |
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
cp service/target/jib-extra/usr/lib/libfdb_c.x86_64.so /usr/lib/libfdb_c.x86_64.so
cp service/target/jib-extra/usr/lib/libfdb_c.so /usr/lib/libfdb_c.x86_64.so
ldconfig
- name: Build with Maven
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
@@ -62,7 +62,7 @@ public class WebsocketClientSession implements Session.Listener.AutoDemanding {
log.info("received response message {}", response.getStatus());
final CompletableFuture<WebSocketResponseMessage> future = responseFutures.remove(response.getRequestId());
if (future == null) {
throw new IllegalArgumentException("Received response with no matching request: {}" + response.getRequestId());
throw new IllegalArgumentException("Received response with no matching request: " + response.getRequestId());
}
future.complete(response);
}
+6 -7
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>
@@ -287,7 +286,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.86.6</version>
<version>0.96.2</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
+2
View File
@@ -100,3 +100,5 @@ tlsKeyStore.password: unset
hlrLookup.apiKey: AAAAAAAAAAA
hlrLookup.apiSecret: AAAAAAAAAAA
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+27
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
@@ -538,3 +541,27 @@ callQualitySurvey:
hlrLookup:
apiKey: secret://hlrLookup.apiKey
apiSecret: secret://hlrLookup.apiSecret
foundationDbMessages:
maxWatchesPerClient: 10000
versionstampCipherKeys:
0: secret://foundationDbMessages.versionstampCipherKey.0
currentVersionstampCipherKey: 0
clusters:
"messages-0":
clusterFileUrl: http://clusterfiles.example.com/messages-0
"messages-1":
clusterFileUrl: http://clusterfiles.example.com/messages-1
"messages-2":
clusterFileUrl: http://clusterfiles.example.com/messages-2
"messages-3":
clusterFileUrl: http://clusterfiles.example.com/messages-3
epochs:
0:
- messages-0
- messages-1
1:
- messages-0
- messages-1
- messages-2
- messages-3
+2 -1
View File
@@ -617,7 +617,7 @@
<plugin>
<groupId>io.github.download-maven-plugin</groupId>
<artifactId>download-maven-plugin</artifactId>
<version>2.0.0</version>
<version>2.1.0</version>
<executions>
<execution>
@@ -632,6 +632,7 @@
<configuration>
<url>https://github.com/apple/foundationdb/releases/download/${foundationdb.version}/libfdb_c.x86_64.so</url>
<outputDirectory>${project.build.directory}/jib-extra/usr/lib</outputDirectory>
<outputFileName>libfdb_c.so</outputFileName>
<sha256>${foundationdb.client-library-sha256}</sha256>
</configuration>
</plugin>
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfi
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
import org.whispersystems.textsecuregcm.configuration.FoundationDbMessagesConfiguration;
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
@@ -361,6 +362,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private ChangeNumberConfiguration changeNumber = new ChangeNumberConfiguration(Duration.ofHours(1));
@Valid
@NotNull
@JsonProperty
private FoundationDbMessagesConfiguration foundationDbMessages;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -600,4 +606,8 @@ public class WhisperServerConfiguration extends Configuration {
public ChangeNumberConfiguration getChangeNumber() {
return changeNumber;
}
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
return foundationDbMessages;
}
}
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm;
import static java.util.Objects.requireNonNull;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.google.common.collect.Lists;
import com.webauthn4j.appattest.DeviceCheckManager;
import io.dropwizard.auth.AuthDynamicFeature;
@@ -44,6 +46,8 @@ import io.netty.resolver.dns.DnsNameResolverBuilder;
import io.netty.util.Mapping;
import jakarta.servlet.DispatcherType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.http.HttpClient;
@@ -53,6 +57,7 @@ import java.time.Duration;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
@@ -63,7 +68,9 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry;
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
@@ -173,9 +180,10 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
@@ -226,7 +234,6 @@ import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.s3.S3MonitoringSupplier;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -244,7 +251,10 @@ 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;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesCache;
@@ -275,6 +285,8 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
@@ -331,7 +343,6 @@ import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import javax.annotation.Nullable;
public class WhisperServerService extends Application<WhisperServerConfiguration> {
@@ -400,7 +411,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
@Override
public void run(WhisperServerConfiguration config, Environment environment) throws Exception {
final Clock clock = Clock.systemUTC();
final int availableProcessors = Runtime.getRuntime().availableProcessors();
final AwsCredentialsProvider awsCredentialsProvider = config.getAwsCredentialsConfiguration().build();
@@ -461,6 +471,39 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbSync"));
final FDB fdb = FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion());
// Jetty and the FoundationDB client both register shutdown hooks to begin shutdown/cleanup operations. There isn't
// a good way to coordinate or enforce ordering between shutdown hooks, and so the two processes will race.
// Generally, FoundationDB will shut down before Jetty does, meaning we'll still be trying to serve requests that
// require talking to FoundationDB even though FoundationDB has shut down. To avoid that scenario, we disabled
// FoundationDB's shutdown hook and let the JVM terminate its (daemon) threads at exit. This isn't as graceful as
// we'd like, but is the least bad option given current constraints.
fdb.disableShutdownHook();
final Map<Integer, List<Database>> messageDatabasesByEpoch;
{
final Map<String, Database> databasesByName =
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> {
try {
final Database database = entry.getValue().build(fdb);
database.options().setMaxWatches(config.getFoundationDbMessagesConfiguration().maxWatchesPerClient());
return database;
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}));
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(databasesByName::get)
.toList()));
}
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
final S3AsyncClient asyncCdnS3Client = S3AsyncClient.builder()
.credentialsProvider(cdnCredentialsProvider)
@@ -592,10 +635,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)
@@ -677,7 +716,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(),
@@ -704,6 +743,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock);
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
config.getFoundationDbMessagesConfiguration().activeEpoch(),
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
Clock.systemUTC());
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
@@ -712,8 +756,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getReportMessageConfiguration().getCounterTtl());
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
MessagesManager messagesManager =
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC(), experimentEnrollmentManager);
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
@@ -742,6 +787,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,
@@ -850,11 +897,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getGcpAttachmentsConfiguration().pathPrefix(),
config.getGcpAttachmentsConfiguration().rsaSigningKey().value());
PostPolicyGenerator profileCdnPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket(), config.getCdnConfiguration().credentials().accessKeyId().value());
PolicySigner profileCdnPolicySigner = new PolicySigner(
config.getCdnConfiguration().credentials().secretAccessKey().value(),
config.getCdnConfiguration().region());
final PostPolicyGenerator profileCdnPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket(),
config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value());
final PostPolicyGenerator stickerPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket(),
config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value());
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().value());
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
@@ -902,6 +953,13 @@ 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);
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -1005,15 +1063,16 @@ 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, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator,
tusAttachmentGenerator, stickerPolicyGenerator,
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!
@@ -1033,7 +1092,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
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 CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
new SubscriptionsGrpcService(clock, config.getSubscription(), config.getOneTimeDonations(), subscriptionManager,
donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager))
.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!
@@ -1074,6 +1136,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);
@@ -1163,14 +1226,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeviceCheck().backupRedemptionDuration()),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
phoneNumberIdentifiers, reportMessageManager, zkSecretParams, spamChecker, Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner,
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
@@ -1178,24 +1241,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig()),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket()),
new StickerController(rateLimiters, stickerPolicyGenerator, Clock.systemUTC()),
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
dynamicConfigurationManager, experimentEnrollmentManager, clock)
dynamicConfigurationManager, experimentEnrollmentManager, clock),
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, donationPermitsManager, dynamicConfigurationManager),
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
donationPermitsManager)
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
zkReceiptOperations, issuedReceiptsManager);
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager));
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
}
for (Object controller : commonControllers) {
environment.jersey().register(controller);
@@ -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);
}
@@ -86,7 +86,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
public CompletionStage<Void> copy(
final int sourceCdn,
final String sourceKey,
final int expectedSourceLength,
final long expectedSourceLength,
final MediaEncryptionParameters encryptionParameters,
final String destinationKey) {
final String sourceScheme = this.sourceSchemes.get(sourceCdn);
@@ -132,10 +132,10 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
*/
record Cdn3CopyRequest(
String encryptionKey, String hmacKey,
SourceDescriptor source, int expectedSourceLength,
SourceDescriptor source, long expectedSourceLength,
String dst) {
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, int expectedSourceLength,
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, long expectedSourceLength,
String dst) {
this(Base64.getEncoder().encodeToString(parameters.aesEncryptionKey().getEncoded()),
Base64.getEncoder().encodeToString(parameters.hmacSHA256Key().getEncoded()),
@@ -18,7 +18,7 @@ import com.google.common.annotations.VisibleForTesting;
public record CopyParameters(
int sourceCdn,
String sourceKey,
int sourceLength,
long sourceLength,
MediaEncryptionParameters encryptionParameters,
byte[] destinationMediaId) {
@@ -35,16 +35,17 @@ public record CopyParameters(
///
/// @return the size, in bytes, of the ciphertext of a media object with the given `inputSize`
@VisibleForTesting
static long destinationObjectSize(final int inputSize) {
static long destinationObjectSize(final long inputSize) {
if (inputSize < 0) {
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
}
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
final long numBlocks = ((long) inputSize + 16) / 16;
final long numBlocks = Math.addExact(inputSize, 16L) / 16;
final long cipherTextLength = Math.multiplyExact(numBlocks, 16);
// 16-byte IV will be generated and prepended to the ciphertext
// 16-byte IV will be generated and prepended to the ciphertext.
// IV + AES-256 encrypted data + HmacSHA256
return 16 + (numBlocks * 16) + 32;
return Math.addExact(cipherTextLength, 16L + 32);
}
}
@@ -35,7 +35,7 @@ public interface RemoteStorageManager {
CompletionStage<Void> copy(
int sourceCdn,
String sourceKey,
int expectedSourceLength,
long expectedSourceLength,
MediaEncryptionParameters encryptionParameters,
String dstKey);
@@ -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;
@@ -84,6 +85,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,
@@ -112,6 +114,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;
@@ -181,6 +184,12 @@ public class DynamoDbTables {
return deletedAccountsLock;
}
@NotNull
@Valid
public TableWithExpiration getDonationPermits() {
return donationPermits;
}
@NotNull
@Valid
public IssuedReceiptsTableConfiguration getIssuedReceipts() {
@@ -0,0 +1,65 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.annotation.JsonTypeName;
import jakarta.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
@JsonTypeName("default")
public record FoundationDbClusterConfiguration(@NotBlank String clusterFileUrl) implements FoundationDbDatabaseFactory {
@Override
public Database build(final FDB fdb) throws IOException {
final URI clusterFileUri = URI.create(clusterFileUrl());
final File clusterFile = switch (clusterFileUri.getScheme()) {
case "file" -> new File(clusterFileUri);
case "http", "https" -> {
try (final HttpClient clusterFileClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build()) {
final HttpResponse<String> response = clusterFileClient.send(HttpRequest.newBuilder()
.uri(URI.create(clusterFileUrl()))
.timeout(Duration.ofSeconds(10))
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("Could not load cluster file (status " + response.statusCode() + ")");
}
final File tempClusterFile = File.createTempFile("fdb.cluster-", "");
tempClusterFile.deleteOnExit();
try (final FileWriter fileWriter = new FileWriter(tempClusterFile)) {
fileWriter.write(response.body());
}
yield tempClusterFile;
} catch (final InterruptedException e) {
throw new IOException("Interrupted while waiting for cluster file response", e);
}
}
default -> throw new IllegalArgumentException("Unrecognized cluster file URI scheme: " + clusterFileUri.getScheme());
};
return fdb.open(clusterFile.getAbsolutePath());
}
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import java.io.IOException;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = FoundationDbClusterConfiguration.class)
public interface FoundationDbDatabaseFactory extends Discoverable {
Database build(final FDB fdb) throws IOException;
}
@@ -0,0 +1,62 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
@PositiveOrZero @Max(1_000_000) long maxWatchesPerClient) {
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
@AssertTrue
boolean isEveryEpochClusterConfigured() {
for (final List<String> clustersInEpoch : epochs().values()) {
for (final String cluster : clustersInEpoch) {
if (!clusters.containsKey(cluster)) {
return false;
}
}
}
return true;
}
@AssertTrue
boolean isEveryEpochFreeOfDuplicates() {
for (final List<String> clustersInEpoch : epochs().values()) {
if (new HashSet<>(clustersInEpoch).size() != clustersInEpoch.size()) {
return false;
}
}
return true;
}
@AssertTrue
boolean isActiveEpochConfigured() {
return epochs().containsKey(activeEpoch());
}
@AssertTrue
boolean isCurrentVersionstampCipherKeyConfigured() {
return versionstampCipherKeys().containsKey(currentVersionstampCipherKey());
}
}
@@ -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;
@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
@@ -21,18 +22,23 @@ import jakarta.ws.rs.core.Response.Status;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.glassfish.jersey.server.ManagedAsync;
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;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.entities.CreateDonationPermitResponse;
import org.whispersystems.textsecuregcm.entities.CreateDonationPermitsRequest;
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;
@@ -46,20 +52,26 @@ public class DonationController {
private final AccountsManager accountsManager;
private final BadgesConfiguration badgesConfiguration;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private final DonationPermitsManager donationPermitsManager;
private final RateLimiters rateLimiters;
public DonationController(
@Nonnull final Clock clock,
@Nonnull final ServerZkReceiptOperations serverZkReceiptOperations,
@Nonnull final RedeemedReceiptsManager redeemedReceiptsManager,
@Nonnull final AccountsManager accountsManager,
@Nonnull final BadgesConfiguration badgesConfiguration,
@Nonnull final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) {
final Clock clock,
final ServerZkReceiptOperations serverZkReceiptOperations,
final RedeemedReceiptsManager redeemedReceiptsManager,
final AccountsManager accountsManager,
final BadgesConfiguration badgesConfiguration,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
final DonationPermitsManager donationPermitsManager,
final RateLimiters rateLimiters) {
this.clock = Objects.requireNonNull(clock);
this.serverZkReceiptOperations = Objects.requireNonNull(serverZkReceiptOperations);
this.redeemedReceiptsManager = Objects.requireNonNull(redeemedReceiptsManager);
this.accountsManager = Objects.requireNonNull(accountsManager);
this.badgesConfiguration = Objects.requireNonNull(badgesConfiguration);
this.receiptCredentialPresentationFactory = Objects.requireNonNull(receiptCredentialPresentationFactory);
this.donationPermitsManager = Objects.requireNonNull(donationPermitsManager);
this.rateLimiters = Objects.requireNonNull(rateLimiters);
}
@POST
@@ -131,4 +143,34 @@ public class DonationController {
return Response.ok().build();
}
@POST
@Path("/permit")
@Produces({MediaType.APPLICATION_JSON})
@Operation(
summary = "Generate permits for anonymous donation endpoints",
description = """
Generate a set of anonymous, single-use, permits for use with /v1/subscription endpoints.
""")
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid credential request")
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@ApiResponse(responseCode = "429", description = "Rate-limited; reduce requested permit count and/or try again after the prescribed delay")
public CreateDonationPermitResponse createPermits(@Auth final AuthenticatedDevice auth,
@NotNull @Valid final CreateDonationPermitsRequest request) throws RateLimitExceededException {
final DonationPermitRequest permitRequest;
try {
permitRequest = new DonationPermitRequest(request.permitRequest());
} catch (InvalidInputException e) {
throw new BadRequestException();
}
rateLimiters.getCreateDonationPermitLimiter().validate(auth.accountIdentifier(), permitRequest.getPermitCount());
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
return new CreateDonationPermitResponse(permitResponse.serialize());
}
}
@@ -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;
@@ -42,8 +45,6 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
@@ -52,10 +53,13 @@ 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.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;
@@ -71,9 +75,6 @@ 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 org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
/**
@@ -99,16 +100,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) {
Clock clock,
OneTimeDonationConfiguration oneTimeDonationConfiguration,
StripeManager stripeManager,
BraintreeManager braintreeManager,
PayPalDonationsTranslator payPalDonationsTranslator,
ServerZkReceiptOperations zkReceiptOperations,
IssuedReceiptsManager issuedReceiptsManager,
OneTimeDonationsManager oneTimeDonationsManager,
DonationPermitsManager donationPermitsManager) {
this.clock = Objects.requireNonNull(clock);
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
this.stripeManager = Objects.requireNonNull(stripeManager);
@@ -117,6 +120,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 {
@@ -164,9 +168,15 @@ 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,
@Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit")
@HeaderParam(HeaderUtils.DONATION_PERMIT)
final Optional<DonationPermitHeader> donationPermitHeader,
@NotNull @Valid CreateBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@@ -174,6 +184,20 @@ public class OneTimeDonationController {
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 (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,
@@ -426,13 +450,4 @@ public class OneTimeDonationController {
.build();
});
}
@Nullable
private static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
try {
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
} catch (final UnrecognizedUserAgentException e) {
return null;
}
}
}
@@ -39,7 +39,6 @@ import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -88,7 +87,6 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
@@ -114,7 +112,6 @@ public class ProfileController {
private final ProfileBadgeConverter profileBadgeConverter;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
private final PolicySigner policySigner;
private final PostPolicyGenerator policyGenerator;
private final ServerSecretParams serverSecretParams;
private final ServerZkProfileOperations zkProfileOperations;
@@ -135,7 +132,6 @@ public class ProfileController {
ProfileBadgeConverter profileBadgeConverter,
BadgesConfiguration badgesConfiguration,
PostPolicyGenerator policyGenerator,
PolicySigner policySigner,
ServerSecretParams serverSecretParams,
ServerZkProfileOperations zkProfileOperations,
Executor batchIdentityCheckExecutor) {
@@ -150,7 +146,6 @@ public class ProfileController {
this.serverSecretParams = serverSecretParams;
this.zkProfileOperations = zkProfileOperations;
this.policyGenerator = policyGenerator;
this.policySigner = policySigner;
this.batchIdentityCheckExecutor = Preconditions.checkNotNull(batchIdentityCheckExecutor);
}
@@ -553,15 +548,13 @@ public class ProfileController {
return maybeTargetAccount.get();
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(
final String objectName) {
ZonedDateTime now = ZonedDateTime.now(clock);
Pair<String, String> policy = policyGenerator.createFor(now, objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES);
String signature = policySigner.getSignature(now, policy.second());
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
final PostPolicyGenerator.SignedPostPolicy signedPostPolicy =
policyGenerator.createFor(objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, clock.instant());
return new ProfileAvatarUploadAttributes(objectName, policy.first(),
"private", "AWS4-HMAC-SHA256",
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
return new ProfileAvatarUploadAttributes(objectName, signedPostPolicy.credential(),
PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
signedPostPolicy.formattedTimestamp(), signedPostPolicy.encodedPolicy(), signedPostPolicy.signature());
}
private static Map<String, Boolean> getAccountCapabilities(final Account account) {
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@@ -15,8 +16,8 @@ import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.security.SecureRandom;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.Clock;
import java.time.Instant;
import java.util.HexFormat;
import java.util.LinkedList;
import java.util.List;
@@ -24,23 +25,25 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes;
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes.StickerPackFormUploadItem;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.util.Constants;
import org.whispersystems.textsecuregcm.util.Pair;
@Path("/v1/sticker")
@Tag(name = "Stickers")
public class StickerController {
private final RateLimiters rateLimiters;
private final PolicySigner policySigner;
private final PostPolicyGenerator policyGenerator;
private final Clock clock;
public StickerController(RateLimiters rateLimiters, String accessKey, String accessSecret, String region, String bucket) {
public static final int MAXIMUM_STICKER_SIZE_BYTES = (int) DataSize.kibibytes(300 + 1).toBytes(); // add 1 kiB for encryption overhead
public static final int MAXIMUM_STICKER_MANIFEST_SIZE_BYTES = (int) DataSize.kibibytes(10).toBytes();
public StickerController(final RateLimiters rateLimiters,
final PostPolicyGenerator postPolicyGenerator,
final Clock clock) {
this.rateLimiters = rateLimiters;
this.policySigner = new PolicySigner(accessSecret, region);
this.policyGenerator = new PostPolicyGenerator(region, bucket, accessKey);
this.policyGenerator = postPolicyGenerator;
this.clock = clock;
}
@GET
@@ -51,33 +54,32 @@ public class StickerController {
throws RateLimitExceededException {
rateLimiters.getStickerPackLimiter().validate(auth.accountIdentifier());
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
String packId = generatePackId();
String packLocation = "stickers/" + packId;
String manifestKey = packLocation + "/manifest.proto";
Pair<String, String> manifestPolicy = policyGenerator.createFor(now, manifestKey,
Constants.MAXIMUM_STICKER_MANIFEST_SIZE_BYTES);
String manifestSignature = policySigner.getSignature(now, manifestPolicy.second());
StickerPackFormUploadItem manifest = new StickerPackFormUploadItem(-1, manifestKey, manifestPolicy.first(),
"private", "AWS4-HMAC-SHA256",
now.format(PostPolicyGenerator.AWS_DATE_TIME), manifestPolicy.second(), manifestSignature);
final Instant currentTime = clock.instant();
final String packId = generatePackId();
final String packLocation = "stickers/" + packId;
final String manifestKey = packLocation + "/manifest.proto";
final PostPolicyGenerator.SignedPostPolicy manifestPolicy =
policyGenerator.createFor(manifestKey, MAXIMUM_STICKER_MANIFEST_SIZE_BYTES, currentTime);
List<StickerPackFormUploadItem> stickers = new LinkedList<>();
final StickerPackFormUploadItem manifest = new StickerPackFormUploadItem(-1, manifestKey, manifestPolicy.credential(),
PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
manifestPolicy.formattedTimestamp(), manifestPolicy.encodedPolicy(), manifestPolicy.signature());
final List<StickerPackFormUploadItem> stickers = new LinkedList<>();
for (int i = 0; i < stickerCount; i++) {
String stickerKey = packLocation + "/full/" + i;
Pair<String, String> stickerPolicy = policyGenerator.createFor(now, stickerKey,
Constants.MAXIMUM_STICKER_SIZE_BYTES);
String stickerSignature = policySigner.getSignature(now, stickerPolicy.second());
stickers.add(new StickerPackFormUploadItem(i, stickerKey, stickerPolicy.first(), "private", "AWS4-HMAC-SHA256",
now.format(PostPolicyGenerator.AWS_DATE_TIME), stickerPolicy.second(), stickerSignature));
final String stickerKey = packLocation + "/full/" + i;
final PostPolicyGenerator.SignedPostPolicy stickerPolicy =
policyGenerator.createFor(stickerKey, MAXIMUM_STICKER_SIZE_BYTES, currentTime);
stickers.add(new StickerPackFormUploadItem(i, stickerKey, stickerPolicy.credential(), PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
manifestPolicy.formattedTimestamp(), stickerPolicy.encodedPolicy(), stickerPolicy.signature()));
}
return new StickerPackFormUploadAttributes(packId, manifest, stickers);
}
private String generatePackId() {
byte[] object = new byte[16];
final byte[] object = new byte[16];
new SecureRandom().nextBytes(object);
return HexFormat.of().formatHex(object);
@@ -5,6 +5,10 @@
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 com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.common.annotations.VisibleForTesting;
@@ -15,6 +19,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 +41,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;
@@ -44,36 +50,31 @@ import jakarta.ws.rs.core.Response.Status;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
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.OneTimeDonationCurrencyConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
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.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -82,8 +83,10 @@ 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.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
@@ -94,9 +97,6 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelEx
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@Path("/v1/subscription")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Subscriptions")
@@ -112,6 +112,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";
@@ -119,17 +120,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);
@@ -140,78 +142,14 @@ 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);
}
private Map<String, CurrencyConfiguration> buildCurrencyConfiguration() {
final List<CustomerAwareSubscriptionPaymentProcessor> subscriptionPaymentProcessors = List.of(stripeManager, braintreeManager);
return oneTimeDonationConfiguration.currencies()
.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, currencyAndConfig -> {
final String currency = currencyAndConfig.getKey();
final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue();
final Map<String, List<BigDecimal>> oneTimeLevelsToSuggestedAmounts = Map.of(
String.valueOf(oneTimeDonationConfiguration.boost().level()), currencyConfig.boosts(),
String.valueOf(oneTimeDonationConfiguration.gift().level()), List.of(currencyConfig.gift())
);
final Function<Map<Long, ? extends SubscriptionLevelConfiguration>, Map<String, BigDecimal>> extractSubscriptionAmounts = levels ->
levels.entrySet().stream()
.filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency))
.collect(Collectors.toMap(
levelIdAndConfig -> String.valueOf(levelIdAndConfig.getKey()),
levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount()));
final List<String> supportedPaymentMethods = Arrays.stream(PaymentMethod.values())
.filter(paymentMethod -> subscriptionPaymentProcessors.stream()
.anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod)
&& manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency)))
.map(PaymentMethod::name)
.collect(Collectors.toList());
if (supportedPaymentMethods.isEmpty()) {
throw new RuntimeException("Configuration has currency with no processor support: " + currency);
}
return new CurrencyConfiguration(
currencyConfig.minimum(),
oneTimeLevelsToSuggestedAmounts,
extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()),
extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()),
supportedPaymentMethods);
}));
}
@VisibleForTesting
GetSubscriptionConfigurationResponse buildGetSubscriptionConfigurationResponse(
final List<Locale> acceptableLanguages) {
final Map<String, LevelConfiguration> donationLevels = new HashMap<>();
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
final LevelConfiguration levelConfiguration = new LevelConfiguration(
"" /* deprecated and unused */,
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
donationLevels.put(String.valueOf(levelId), levelConfiguration);
});
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
oneTimeDonationConfiguration.boost().badge());
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.boost().level()),
new LevelConfiguration(
"" /* deprecated and unused */,
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
new PurchasableBadge(
boostBadge,
oneTimeDonationConfiguration.boost().expiration())));
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.gift().level()),
new LevelConfiguration(
"" /* deprecated and unused */,
new PurchasableBadge(
giftBadge,
oneTimeDonationConfiguration.gift().expiration())));
final long maxTotalBackupMediaBytes =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
@@ -224,7 +162,11 @@ public class SubscriptionController {
e.getValue().playProductId(),
e.getValue().mediaTtl().toDays())));
return new GetSubscriptionConfigurationResponse(buildCurrencyConfiguration(), donationLevels,
return new GetSubscriptionConfigurationResponse(
buildCurrencyConfiguration(List.of(stripeManager, braintreeManager), oneTimeDonationConfiguration,
subscriptionConfiguration),
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
acceptableLanguages),
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
oneTimeDonationConfiguration.sepaMaximumEuros());
}
@@ -267,15 +209,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")
@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();
}
@@ -291,6 +253,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 {
@@ -308,6 +275,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,
@@ -542,33 +524,12 @@ public class SubscriptionController {
@Schema(description = "A map of lower-cased ISO 3 currency codes to minimums and level-specific scalar amounts")
Map<String, CurrencyConfiguration> currencies,
@Schema(description = "A map of numeric donation level IDs to level-specific badge configuration")
Map<String, LevelConfiguration> levels,
Map<Long, LevelConfiguration> levels,
@Schema(description = "Backup specific configuration")
BackupConfiguration backup,
@Schema(description = "The maximum value of a one-time donation SEPA transaction")
BigDecimal sepaMaximumEuros) {}
@Schema(description = "Configuration for a currency - use to present appropriate client interfaces")
public record CurrencyConfiguration(
@Schema(description = "The minimum amount that may be submitted for a one-time donation in the currency")
BigDecimal minimum,
@Schema(description = "A map of numeric one-time donation level IDs to the list of default amounts to be presented")
Map<String, List<BigDecimal>> oneTime,
@Schema(description = "A map of numeric subscription level IDs to the amount charged for that level")
Map<String, BigDecimal> subscription,
@Schema(description = "A map of numeric backup level IDs to the amount charged for that level")
Map<String, BigDecimal> backupSubscription,
@Schema(description = "The payment methods that support the given currency")
List<String> supportedPaymentMethods) {}
@Schema(description = "Configuration for a donation level - use to present appropriate client interfaces")
public record LevelConfiguration(
@Deprecated(forRemoval = true) // may be removed after 2025-01-28
@Schema(description = "The localized name for the level")
String name,
@Schema(description = "The displayable badge associated with the level")
Badge badge) {}
public record BackupConfiguration(
@Schema(description = "A map of numeric backup level IDs to level-specific backup configuration")
Map<String, BackupLevelConfiguration> levels,
@@ -768,7 +729,8 @@ public class SubscriptionController {
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
try {
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
subscriberCredentials, request, this::receiptExpirationWithGracePeriod);
subscriberCredentials, request.receiptCredentialRequest(),
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
@@ -823,19 +785,6 @@ public class SubscriptionController {
}
}
private Instant receiptExpirationWithGracePeriod(CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) {
final PaymentTime paymentTime = receiptItem.paymentTime();
return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) {
case DONATION -> paymentTime.receiptExpiration(
subscriptionConfiguration.getBadgeExpiration(),
subscriptionConfiguration.getBadgeGracePeriod());
case BACKUP -> paymentTime.receiptExpiration(
subscriptionConfiguration.getBackupExpiration(),
subscriptionConfiguration.getBackupGracePeriod());
};
}
private String getSubscriptionTemplateId(long level, String currency, PaymentProvider processor) {
final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(level);
if (config == null) {
@@ -854,13 +803,4 @@ public class SubscriptionController {
SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_CURRENCY, null))))
.build()));
}
@Nullable
private static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
try {
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
} catch (final UnrecognizedUserAgentException e) {
return null;
}
}
}
@@ -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);
}
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
public record CreateDonationPermitResponse(
@Schema(description = "A serialized DonationPermitResponse")
@NotEmpty
@NotNull
@Valid
byte[] permitResponse) {
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
public record CreateDonationPermitsRequest(
@Schema(description = "A serialized DonationPermitRequest")
@NotEmpty
@NotNull
byte[] permitRequest) {
}
@@ -71,6 +71,10 @@ public class Experiment {
this.experimentNullMismatchTimer = experimentNullMismatchTimer;
}
public <T> void compareResult(final T expected, final T experimentResult) {
recordResult(expected, experimentResult, Timer.start());
}
public <T> void compareMonoResult(final T expected, final Mono<T> experimentMono) {
final Timer.Sample sample = Timer.start();
@@ -48,7 +48,6 @@ 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 +135,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());
}
@@ -6,10 +6,21 @@
package org.whispersystems.textsecuregcm.grpc;
import java.security.SecureRandom;
import java.time.Clock;
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;
import org.signal.chat.attachments.GetUploadFormResponse;
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.common.UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
@@ -18,30 +29,51 @@ 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 {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter countRateLimiter;
private final RateLimiter bytesRateLimiter;
private final RateLimiter stickerPackLimiter;
private final long maxUploadLength;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private final PostPolicyGenerator stickerPolicyGenerator;
private final Clock clock;
private final SecureRandom secureRandom;
private static final S3UploadForm PROTOTYPE_STICKER_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
private static final String ATTACHMENT_SIZE_NAME =
MetricsUtil.name(AttachmentsGrpcService.class, "attachmentSize");
public AttachmentsGrpcService(
final ExperimentEnrollmentManager experimentEnrollmentManager,
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator,
final long maxUploadLength) {
final PostPolicyGenerator stickerPolicyGenerator,
final long maxUploadLength,
final Clock clock) {
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
this.stickerPackLimiter = rateLimiters.getStickerPackLimiter();
this.stickerPolicyGenerator = stickerPolicyGenerator;
this.maxUploadLength = maxUploadLength;
this.clock = clock;
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
@@ -67,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);
@@ -80,4 +117,59 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
.setSignedUploadLocation(descriptor.signedUploadLocation()))
.build();
}
@Override
public GetStickerUploadFormResponse getStickerUploadForm(final GetStickerUploadFormRequest request)
throws RateLimitExceededException {
stickerPackLimiter.validate(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
final Instant currentTime = clock.instant();
final String packId;
{
final byte[] packIdBytes = new byte[16];
secureRandom.nextBytes(packIdBytes);
packId = HexFormat.of().formatHex(packIdBytes);
}
final String packLocation = "stickers/" + packId;
final GetStickerUploadFormResponse.Builder responseBuilder = GetStickerUploadFormResponse.newBuilder()
.setPackId(packId);
{
final String manifestKey = packLocation + "/manifest.proto";
final PostPolicyGenerator.SignedPostPolicy manifestPolicy =
stickerPolicyGenerator.createFor(manifestKey, StickerController.MAXIMUM_STICKER_MANIFEST_SIZE_BYTES, currentTime);
responseBuilder
.setManifestUploadForm(PROTOTYPE_STICKER_UPLOAD_FORM.toBuilder()
.setKey(manifestKey)
.setCredential(manifestPolicy.credential())
.setDate(manifestPolicy.formattedTimestamp())
.setPolicy(manifestPolicy.encodedPolicy())
.setSignature(manifestPolicy.signature())
.build());
}
IntStream.range(0, request.getStickerCount())
.mapToObj(i -> {
final String stickerKey = packLocation + "/full/" + i;
final PostPolicyGenerator.SignedPostPolicy stickerPolicy =
stickerPolicyGenerator.createFor(stickerKey, StickerController.MAXIMUM_STICKER_SIZE_BYTES, currentTime);
return PROTOTYPE_STICKER_UPLOAD_FORM.toBuilder()
.setKey(stickerKey)
.setCredential(stickerPolicy.credential())
.setDate(stickerPolicy.formattedTimestamp())
.setPolicy(stickerPolicy.encodedPolicy())
.setSignature(stickerPolicy.signature())
.build();
})
.forEach(responseBuilder::addStickerUploadForms);
return responseBuilder.build();
}
}
@@ -8,6 +8,7 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.util.Optional;
import java.util.concurrent.Flow;
import org.signal.chat.backup.BackupStreamClosed;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
import org.signal.chat.backup.DeleteAllRequest;
@@ -223,15 +224,16 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
copyQuota = backupManager.getCopyQuota(backupUser,
request.getItemsList().stream().map(item -> new CopyParameters(
item.getSourceAttachmentCdn(), item.getSourceKey(),
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
item.getObjectLength(),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
return JdkFlowAdapter.publisherToFlowPublisher(
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription(e.getMessage())
.build())
.build())));
}
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(
@@ -308,10 +310,12 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
.toList());
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(DeleteMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
return JdkFlowAdapter.publisherToFlowPublisher(
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription(e.getMessage())
.build())
.build())));
}
return JdkFlowAdapter.publisherToFlowPublisher(deleteItems
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
@@ -346,17 +350,6 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
}
/**
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
*/
private static int fromUnsignedExact(final int i) {
if (i < 0) {
throw GrpcExceptions.invalidArguments("integer length too large");
}
return i;
}
private interface Deserializer<T> {
T deserialize(byte[] bytes) throws InvalidInputException, InvalidKeyException;
@@ -8,8 +8,12 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.UUID;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
@@ -19,8 +23,10 @@ import org.signal.chat.credentials.GetGroupCredentialsResponse;
import org.signal.chat.credentials.SimpleCredentialsGrpc;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
@@ -133,4 +139,30 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
return responseBuilder.build();
}
@Override
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
throws RateLimitExceededException {
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
rateLimiters.getCreateCallLinkLimiter().validate(accountIdentifier);
final Instant truncatedDayTimestamp = clock.instant().truncatedTo(ChronoUnit.DAYS);
try {
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
return GetCreateCallLinkCredentialsResponse.newBuilder()
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
new ServiceId.Aci(accountIdentifier),
truncatedDayTimestamp,
serverSecretParams)
.serialize()))
.build();
} catch (final InvalidInputException e) {
throw GrpcExceptions.invalidArguments("Invalid 'create call link credential' request");
}
}
}
@@ -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();
}
}
@@ -39,7 +39,7 @@ public class ErrorConformanceInterceptor implements ServerInterceptor {
}
switch (status.getCode()) {
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED -> {
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED, ABORTED -> {
}
default -> {
log.error("Intercepted call {} returned illegal application status {}: {}",
@@ -39,6 +39,11 @@ public class GrpcExceptions {
.setReason("BAD_AUTHENTICATION")
.build());
private static final Any ERROR_INFO_STREAM_CLOSED = Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("STREAM_CLOSED")
.build());
private static final com.google.rpc.Status UPGRADE_REQUIRED = com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage("Upgrade required")
@@ -144,6 +149,20 @@ public class GrpcExceptions {
return StatusProto.toStatusRuntimeException(builder.build());
}
/// The server terminated the stream non-successfully for a reason specific to the RPC. The server must provide
/// additional information about the stream closure reason via the `streamClosedMessage`.
///
/// @param streamClosedMessage The additional domain-specific proto message that indicates the closure reason
/// @return A [StatusRuntimeException] encoding the error
public static <T extends com.google.protobuf.Message> StatusRuntimeException streamClosed(
final T streamClosedMessage) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.ABORTED.value())
.addDetails(ERROR_INFO_STREAM_CLOSED)
.addDetails(Any.pack(streamClosedMessage))
.build());
}
public static StatusRuntimeException unavailable() {
return unavailable(null);
}
@@ -6,11 +6,13 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.Metrics;
import java.time.Duration;
import java.util.UUID;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.GetMessagesStreamClosed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
@@ -54,14 +56,10 @@ public class MessageDispatcher {
public static final GetMessagesResponse QUEUE_EMPTY_RESPONSE =
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
private static final GetMessagesResponse CONFLICTING_STREAM_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setConflictingStream(Empty.getDefaultInstance()))
.build();
private static final GetMessagesResponse REAUTHENTICATION_REQUIRED_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setReauthenticationRequired(Empty.getDefaultInstance()))
.build();
private static final StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
.setConflictingStream(Empty.getDefaultInstance())
.build());
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(MessageDispatcher.class, "sendMessages");
@@ -99,8 +97,8 @@ public class MessageDispatcher {
/// terminates for any reason. The error from the client will be propagated to the returned flux. The stream may also
/// terminate with any other error encountered retrieving messages or processing acknowledgements.
///
/// The returned flux will emit a [GetMessagesResponse.Terminated] and then complete if
/// - A disconnection request (typically indicating a change in authorization credentials) is received.
/// The returned flux will error with a [GrpcExceptions#streamClosed] non-ok status exception if:
/// - A disconnection request (typically indicating a change in authorization credentials) is received
/// - A client requests messages for the same account/device while this stream is still active
///
/// When the stream terminates for any reason and the client has messages remaining in their queue, a push
@@ -167,7 +165,11 @@ public class MessageDispatcher {
pendingAcknowledgementTracker.markEndOfQueue();
yield Mono.empty();
}
}, MAX_UNACKED_MESSAGES);
}, MAX_UNACKED_MESSAGES)
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
return CONFLICTING_STREAM_EXCEPTION;
});
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
// after that a permit is emitted every time we receive an ack.
@@ -204,18 +206,8 @@ public class MessageDispatcher {
ackCompletions,
// Emits a queue empty once all messages prior to the queueEmpty signal have been acked
pendingAcknowledgementTracker.queueDrained(),
// Emit a Terminated response if we receive a disconnection request
disconnectionSignal(account, device))
.onErrorResume(ConflictingMessageConsumerException.class, _ -> Mono.just(CONFLICTING_STREAM_RESPONSE))
.takeUntil(response -> switch (response.getResponseCase()) {
case ENVELOPE, QUEUE_EMPTY -> false;
case TERMINATED -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent,
response.getTerminated().hasConflictingStream());
yield true;
}
case RESPONSE_NOT_SET -> throw new IllegalStateException("tried to return an invalid GetMessagesResponse");
})
// Emit an invalid credentials error if we receive a disconnection request
disconnectionSignal(account, device, userAgent))
.doFinally(_ -> maybeSchedulePush(account, device));
}
@@ -232,11 +224,14 @@ public class MessageDispatcher {
/// Watch for a disconnection signal from the [DisconnectionRequestManager]
///
/// @return Mono that completes with a [org.signal.chat.messages.GetMessagesResponse.Terminated] response if the
/// @return Mono that completes with an `InvalidCredentials` status if the
/// device receives a disconnection request
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device) {
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device, final UserAgent userAgent) {
return Mono.create(sink -> {
final DisconnectionRequestListener listener = () -> sink.success(REAUTHENTICATION_REQUIRED_RESPONSE);
final DisconnectionRequestListener listener = () -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
};
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
});
@@ -15,8 +15,8 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.profile.Badge;
import org.signal.chat.profile.BadgeSvg;
import org.signal.chat.common.Badge;
import org.signal.chat.common.BadgeSvg;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
@@ -5,9 +5,7 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
@@ -16,6 +14,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
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.GetUnversionedProfileRequest;
@@ -23,7 +22,6 @@ import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.PaymentsForbiddenInRegion;
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileResponse;
@@ -40,7 +38,6 @@ 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.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
@@ -51,7 +48,6 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
@@ -62,13 +58,17 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
private final PostPolicyGenerator policyGenerator;
private final PolicySigner policySigner;
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<ProfileAvatarUploadAttributes> uploadAttributes) {}
Optional<S3UploadForm> uploadAttributes) {}
public ProfileGrpcService(
final Clock clock,
@@ -77,7 +77,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
final PolicySigner policySigner,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters) {
this.clock = clock;
@@ -87,7 +86,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
BadgeConfiguration::getId, Function.identity()));
this.policyGenerator = policyGenerator;
this.policySigner = policySigner;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
}
@@ -266,19 +264,16 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
final ZonedDateTime now = ZonedDateTime.now(clock);
final Pair<String, String> policy = policyGenerator.createFor(now, objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES);
final String signature = policySigner.getSignature(now, policy.second());
private S3UploadForm generateAvatarUploadForm(final String objectName) {
final PostPolicyGenerator.SignedPostPolicy policy =
policyGenerator.createFor(objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, clock.instant());
return ProfileAvatarUploadAttributes.newBuilder()
.setPath(objectName)
.setCredential(policy.first())
.setAcl("private")
.setAlgorithm("AWS4-HMAC-SHA256")
.setDate(now.format(PostPolicyGenerator.AWS_DATE_TIME))
.setPolicy(policy.second())
.setSignature(ByteString.copyFrom(signature.getBytes()))
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
.setKey(objectName)
.setCredential(policy.credential())
.setDate(policy.formattedTimestamp())
.setPolicy(policy.encodedPolicy())
.setSignature(policy.signature())
.build();
}
}
@@ -0,0 +1,608 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.math.BigDecimal;
import java.time.Clock;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
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;
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;
import org.signal.chat.subscriptions.GetBankMandateResponse;
import org.signal.chat.subscriptions.GetConfigurationRequest;
import org.signal.chat.subscriptions.GetConfigurationResponse;
import org.signal.chat.subscriptions.GetReceiptCredentialsRequest;
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.SetDefaultPaymentMethodRequest;
import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse;
import org.signal.chat.subscriptions.SetIapSubscriptionRequest;
import org.signal.chat.subscriptions.SetIapSubscriptionResponse;
import org.signal.chat.subscriptions.SetSubscriptionLevelRequest;
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;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
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;
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.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.subscriptions.SubscriptionStatus;
public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.SubscriptionsImplBase {
private final Clock clock;
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;
private final AppleAppStoreManager appleAppStoreManager;
private final BadgeTranslator badgeTranslator;
private final BankMandateTranslator bankMandateTranslator;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public SubscriptionsGrpcService(final Clock clock, final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration, final SubscriptionManager subscriptionManager,
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;
this.appleAppStoreManager = appleAppStoreManager;
this.badgeTranslator = badgeTranslator;
this.bankMandateTranslator = bankMandateTranslator;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@Override
public UpdateSubscriberResponse updateSubscriber(final UpdateSubscriberRequest request) {
try {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
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();
}
}
@Override
public DeleteSubscriberResponse deleteSubscriber(final DeleteSubscriberRequest request)
throws RateLimitExceededException {
try {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
subscriptionManager.deleteSubscriber(subscriberCredentials);
return DeleteSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionNotFoundException e) {
return DeleteSubscriberResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
return DeleteSubscriberResponse.newBuilder().setCannotCancelSubscription(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
public CreatePaymentMethodResponse createPaymentMethod(final CreatePaymentMethodRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
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,
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken);
return CreatePaymentMethodResponse.newBuilder().setResult(
CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token)
.setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build();
} catch (final SubscriptionNotFoundException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
} catch (final SubscriptionForbiddenException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
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);
try {
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
locale.toLanguageTag())).join();
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
} catch (final SubscriptionNotFoundException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
.build();
} catch (final SubscriptionForbiddenException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final CustomerAwareSubscriptionPaymentProcessor manager;
final String paymentMethodId = switch (request.getRequestCase()) {
case STRIPE -> {
manager = stripeManager;
yield request.getStripe().getPaymentMethodToken();
}
case BRAINTREE -> {
manager = braintreeManager;
yield request.getBraintree().getPaymentMethodToken();
}
case SEPA -> {
manager = stripeManager;
yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId()).join();
}
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
};
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
return record.getProcessorCustomer().map(
processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId,
record.subscriptionId)).orElseGet(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
SetDefaultPaymentMethodResponse.newBuilder().setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
.build());
} catch (final SubscriptionNotFoundException e) {
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private static SetDefaultPaymentMethodResponse setDefaultPaymentMethodForCustomer(
final CustomerAwareSubscriptionPaymentProcessor processor, final ProcessorCustomer processorCustomer,
final String paymentMethodId, final String subscriptionId) {
try {
processor.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, subscriptionId);
return SetDefaultPaymentMethodResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
// setting up the paymentMethod first
return SetDefaultPaymentMethodResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
}
}
@Override
public SetSubscriptionLevelResponse setSubscriptionLevel(final SetSubscriptionLevelRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
return record.getProcessorCustomer().map(
processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record,
request)).orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()).build());
} catch (final SubscriptionNotFoundException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private SetSubscriptionLevelResponse setSubscriptionLevelForCustomer(final ProcessorCustomer processorCustomer,
final SubscriberCredentials subscriberCredentials, final Subscriptions.Record subscriptionRecord,
final SetSubscriptionLevelRequest request) {
final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(request.getLevel());
if (config == null) {
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedLevel(FailedPrecondition.newBuilder().build())
.build();
}
final Optional<String> templateId = Optional.ofNullable(
config.prices().get(request.getCurrency().toLowerCase(Locale.ROOT)))
.map(priceConfiguration -> priceConfiguration.processorIds().get(processorCustomer.processor()));
if (templateId.isEmpty()) {
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedCurrency(FailedPrecondition.newBuilder().build())
.build();
}
final CustomerAwareSubscriptionPaymentProcessor manager;
switch (processorCustomer.processor()) {
case STRIPE -> manager = stripeManager;
case BRAINTREE -> manager = braintreeManager;
default -> {
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedOperation(FailedPrecondition.newBuilder()
.setDescription(
"Operation cannot be performed with the '" + processorCustomer.processor() + "' payment provider")
.build()).build();
}
}
try {
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, subscriptionRecord, manager,
request.getLevel(), request.getCurrency(), request.getIdempotencyKey(), templateId.get(),
(l1, l2) -> SubscriptionsUtil.subscriptionsAreSameType(subscriptionConfiguration, l1, l2));
return SetSubscriptionLevelResponse.newBuilder().setSuccess(
SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build())
.build();
} catch (final SubscriptionInvalidIdempotencyKeyException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
} catch (final SubscriptionProcessorException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setChargeFailure(toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
} catch (final SubscriptionPaymentRequiresActionException e) {
return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionInvalidLevelException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
public SetIapSubscriptionResponse setIapSubscription(final SetIapSubscriptionRequest request)
throws RateLimitExceededException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
final long level = switch (request.getRequestCase()) {
case APP_STORE -> subscriptionManager.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager,
request.getAppStore().getOriginalTransactionId());
case PLAY_BILLING ->
subscriptionManager.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager,
request.getPlayBilling().getPurchaseToken());
default -> throw GrpcExceptions.fieldViolation("request", "must set request type");
};
return SetIapSubscriptionResponse.newBuilder()
.setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build();
} catch (final SubscriptionNotFoundException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionPaymentRequiredException e) {
return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionInvalidArgumentsException e) {
return SetIapSubscriptionResponse.newBuilder()
.setInvalidTransaction(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
}
}
@Override
public GetSubscriptionInformationResponse getSubscriptionInformation(final GetSubscriptionInformationRequest request)
throws RateLimitExceededException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
return subscriptionManager.getSubscriptionInformation(subscriberCredentials)
.map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet(
() -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance())
.build());
} catch (final SubscriptionNotFoundException e) {
return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
.build();
} catch (final SubscriptionForbiddenException e) {
return GetSubscriptionInformationResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private static GetSubscriptionInformationResponse buildSubscriptionInformationResponse(
final SubscriptionInformation info) {
final GetSubscriptionInformationResponse.Subscription.Builder subscription = GetSubscriptionInformationResponse.Subscription.newBuilder()
.setLevel(info.level()).setEndOfCurrentPeriod(info.endOfCurrentPeriod().getEpochSecond())
.setActive(info.active()).setCancelAtPeriodEnd(info.cancelAtPeriodEnd()).setCurrency(info.price().currency())
.setAmount(info.price().amount().longValue()).setStatus(toProtoSubscriptionStatus(info.status()))
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(toProtoPaymentMethod(info.paymentMethod()))
.setPaymentProcessing(info.paymentProcessing());
if (info.billingCycleAnchor() != null) {
subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond());
}
if (info.chargeFailure() != null) {
subscription.setChargeFailure(toChargeFailure(info.paymentProvider(), info.chargeFailure()));
}
return GetSubscriptionInformationResponse.newBuilder().setSuccess(subscription.build()).build();
}
@Override
public GetReceiptCredentialsResponse getReceiptCredentials(final GetReceiptCredentialsRequest request)
throws RateLimitExceededException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
final SubscriptionManager.ReceiptResult result = subscriptionManager.createReceiptCredentials(
subscriberCredentials, request.getReceiptCredentialRequest().toByteArray(),
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
return GetReceiptCredentialsResponse.newBuilder().setSuccess(
GetReceiptCredentialsResponse.GetReceiptCredentialsResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize()))
.build()).build();
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
return GetReceiptCredentialsResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder().setPaymentRequired(
GetReceiptCredentialsResponse.PaymentRequired.newBuilder()
.setChargeFailure(toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build();
} catch (final SubscriptionPaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder()
.setPaymentRequired(GetReceiptCredentialsResponse.PaymentRequired.newBuilder().build()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
return GetReceiptCredentialsResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionNotFoundException e) {
return GetReceiptCredentialsResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return GetReceiptCredentialsResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private static org.signal.chat.subscriptions.SubscriptionStatus toProtoSubscriptionStatus(
final SubscriptionStatus status) {
return switch (status) {
case ACTIVE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE;
case INCOMPLETE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE;
case PAST_DUE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE;
case CANCELED -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED;
case UNPAID -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID;
case UNKNOWN -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN;
};
}
private static PaymentMethod toProtoPaymentMethod(
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod) {
if (paymentMethod == null) {
return PaymentMethod.PAYMENT_METHOD_UNKNOWN;
}
return switch (paymentMethod) {
case CARD -> PaymentMethod.PAYMENT_METHOD_CARD;
case SEPA_DEBIT -> PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT;
case IDEAL -> PaymentMethod.PAYMENT_METHOD_IDEAL;
case PAYPAL -> PaymentMethod.PAYMENT_METHOD_PAYPAL;
case GOOGLE_PLAY_BILLING -> PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING;
case APPLE_APP_STORE -> PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE;
case UNKNOWN -> PaymentMethod.PAYMENT_METHOD_UNKNOWN;
};
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
final long maxBackupBytes = dynamicConfigurationManager.getConfiguration().getBackupConfiguration()
.maxTotalMediaSize();
final Map<Long, GetConfigurationResponse.BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
e -> GetConfigurationResponse.BackupLevelConfiguration.newBuilder().setStorageAllowanceBytes(maxBackupBytes)
.setPlayProductId(e.getValue().playProductId()).setMediaTtlDays(e.getValue().mediaTtl().toDays())
.build()));
return GetConfigurationResponse.newBuilder().putAllCurrencies(buildCurrencyConfigurations())
.putAllLevels(buildLevelConfigurations()).setBackup(
GetConfigurationResponse.BackupConfiguration.newBuilder().putAllLevels(backupLevels)
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()).build())
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
}
private Map<String, GetConfigurationResponse.CurrencyConfiguration> buildCurrencyConfigurations() {
return SubscriptionsUtil.buildCurrencyConfiguration(List.of(stripeManager, braintreeManager),
oneTimeDonationConfiguration, subscriptionConfiguration).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
}
private Map<Long, GetConfigurationResponse.LevelConfiguration> buildLevelConfigurations() {
return SubscriptionsUtil.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration,
badgeTranslator, RequestAttributesUtil.getAvailableAcceptedLocales()).entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey, entry -> GetConfigurationResponse.LevelConfiguration.newBuilder()
.setBadge(toProtoBadge(entry.getValue().badge())).build()));
}
private static GetConfigurationResponse.CurrencyConfiguration toProtoCurrencyConfiguration(final String currency,
final CurrencyConfiguration config) {
final GetConfigurationResponse.CurrencyConfiguration.Builder builder = GetConfigurationResponse.CurrencyConfiguration.newBuilder()
.setMinimum(config.minimum().toString())
.addAllSupportedPaymentMethods(
config.supportedPaymentMethods().stream().map(SubscriptionsGrpcService::toProtoPaymentMethod).toList());
config.oneTime().forEach((levelId, amounts) -> builder.putOneTime(levelId,
GetConfigurationResponse.AmountList.newBuilder()
.addAllAmounts(
amounts.stream().map(BigDecimal::toString).toList())
.build()));
config.subscription()
.forEach((levelId, amount) -> builder.putSubscription(levelId,
amount.toString()));
config.backupSubscription()
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId,
amount.toString()));
return builder.build();
}
private static GetConfigurationResponse.Badge toProtoBadge(final Badge badge) {
final org.signal.chat.common.Badge commonBadge = org.signal.chat.common.Badge.newBuilder().setId(badge.getId())
.setCategory(badge.getCategory()).setName(badge.getName()).setDescription(badge.getDescription())
.addAllSprites6(badge.getSprites6()).setSvg(badge.getSvg()).addAllSvgs(badge.getSvgs().stream()
.map(s -> org.signal.chat.common.BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
.toList()).build();
final GetConfigurationResponse.Badge.Builder builder = GetConfigurationResponse.Badge.newBuilder()
.setBadge(commonBadge);
if (badge instanceof final PurchasableBadge purchasableBadge) {
builder.setDurationSeconds(purchasableBadge.getDuration().toSeconds());
}
return builder.build();
}
@Override
public GetBankMandateResponse getBankMandate(final GetBankMandateRequest request) {
final BankTransferType bankTransferType = switch (request.getBankTransferType()) {
case BANK_TRANSFER_TYPE_SEPA_DEBIT -> BankTransferType.SEPA_DEBIT;
default -> throw GrpcExceptions.fieldViolation("bank_transfer_type", "Unsupported bank transfer type");
};
final String mandate = bankMandateTranslator.translate(RequestAttributesUtil.getAvailableAcceptedLocales(),
bankTransferType);
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();
}
}
@@ -0,0 +1,163 @@
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.HashMap;
import java.util.List;
import java.util.Locale;
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;
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.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
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 {
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
} catch (final UnrecognizedUserAgentException e) {
return null;
}
}
public static boolean subscriptionsAreSameType(final SubscriptionConfiguration subscriptionConfiguration, final long level1, final long level2) {
return subscriptionConfiguration.getSubscriptionLevel(level1).type()
== subscriptionConfiguration.getSubscriptionLevel(level2).type();
}
public static Instant receiptExpirationWithGracePeriod(
final SubscriptionConfiguration subscriptionConfiguration,
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) {
return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) {
case DONATION -> receiptItem.paymentTime().receiptExpiration(
subscriptionConfiguration.getBadgeExpiration(),
subscriptionConfiguration.getBadgeGracePeriod());
case BACKUP -> receiptItem.paymentTime().receiptExpiration(
subscriptionConfiguration.getBackupExpiration(),
subscriptionConfiguration.getBackupGracePeriod());
};
}
public static Map<String, CurrencyConfiguration> buildCurrencyConfiguration(final List<CustomerAwareSubscriptionPaymentProcessor> subscriptionPaymentProcessors,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final SubscriptionConfiguration subscriptionConfiguration) {
return oneTimeDonationConfiguration.currencies()
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, currencyAndConfig -> {
final String currency = currencyAndConfig.getKey();
final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue();
final Map<Long, List<BigDecimal>> oneTimeLevelsToSuggestedAmounts = Map.of(
oneTimeDonationConfiguration.boost().level(), currencyConfig.boosts(),
oneTimeDonationConfiguration.gift().level(), List.of(currencyConfig.gift())
);
final Function<Map<Long, ? extends SubscriptionLevelConfiguration>, Map<Long, BigDecimal>> extractSubscriptionAmounts = levels ->
levels.entrySet().stream()
.filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency))
.collect(Collectors.toMap(
Map.Entry::getKey,
levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount()));
final List<PaymentMethod> supportedPaymentMethods = Arrays.stream(PaymentMethod.values())
.filter(paymentMethod -> subscriptionPaymentProcessors.stream()
.anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod)
&& manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency)))
.collect(Collectors.toList());
if (supportedPaymentMethods.isEmpty()) {
throw new RuntimeException("Configuration has currency with no processor support: " + currency);
}
return new CurrencyConfiguration(
currencyConfig.minimum(),
oneTimeLevelsToSuggestedAmounts,
extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()),
extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()),
supportedPaymentMethods);
}));
}
public static Map<Long, LevelConfiguration> buildDonationLevelsConfiguration(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final BadgeTranslator badgeTranslator,
final List<Locale> acceptableLanguages) {
final Map<Long, LevelConfiguration> donationLevels = new HashMap<>();
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
final LevelConfiguration levelConfiguration = new LevelConfiguration(
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
donationLevels.put(levelId, levelConfiguration);
});
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
oneTimeDonationConfiguration.boost().badge());
donationLevels.put(oneTimeDonationConfiguration.boost().level(),
new LevelConfiguration(
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
new PurchasableBadge(
boostBadge,
oneTimeDonationConfiguration.boost().expiration())));
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
donationLevels.put(oneTimeDonationConfiguration.gift().level(),
new LevelConfiguration(
new PurchasableBadge(
giftBadge,
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();
}
}
@@ -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()));
@@ -61,6 +61,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
BATCH_IDENTITY_CHECK("batchIdentityCheck", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
CREATE_DONATION_PERMIT("createDonationCredential", new RateLimiterConfig(30, Duration.ofHours(4), true)),
ONE_TIME_DONATION("oneTimeDonation", new RateLimiterConfig(5, Duration.ofMinutes(1), true)),
ADD_SUBSCRIPTION_PAYMENT_METHOD("addSubscriptionPaymentMethod", new RateLimiterConfig(10, Duration.ofMinutes(1), true)),
;
@@ -241,7 +242,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVEY);
}
public RateLimiter getBatchIdentityCheckLimiter() {
return forDescriptor(For.BATCH_IDENTITY_CHECK);
public RateLimiter getCreateDonationPermitLimiter() {
return forDescriptor(For.CREATE_DONATION_PERMIT);
}
}
@@ -35,6 +35,7 @@ public final class MessageMetrics {
public static String GRPC_CHANNEL = "grpc";
public static String WEBSOCKET_CHANNEL = "websocket";
public static String MESSAGELESS_WEBSOCKET_CHANNEL = "messageless-websocket";
@VisibleForTesting
static final String MISMATCHED_ACCOUNT_ENVELOPE_UUID_COUNTER_NAME = name(MessageMetrics.class,
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.metrics;
import com.codahale.metrics.SharedMetricRegistries;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.core.setup.Environment;
import io.micrometer.core.instrument.Meter;
@@ -36,7 +35,6 @@ import org.eclipse.jetty.util.component.LifeCycle;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.Constants;
public class MetricsUtil {
@@ -69,8 +67,6 @@ public class MetricsUtil {
registeredMetrics = true;
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
Duration shutdownWaitDuration = Duration.ZERO;
if (config.getOpenTelemetryConfiguration().enabled()) {
@@ -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,100 +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_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(
@@ -286,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));
@@ -301,7 +295,6 @@ public class RegistrationServiceClient implements Managed {
}
}
private static Mac getInitializedMac(byte[] key) throws InvalidKeyException {
try {
final Mac hmacSha256 = Mac.getInstance("HmacSHA256");
@@ -28,6 +28,10 @@ public class RegistrationServiceSenderException extends Exception {
return new RegistrationServiceSenderException(Reason.PROVIDER_UNAVAILABLE, permanent);
}
public static RegistrationServiceSenderException unavailable(final boolean permanent) {
return new RegistrationServiceSenderException(Reason.PROVIDER_UNAVAILABLE, permanent);
}
private RegistrationServiceSenderException(final Reason reason, final boolean permanent) {
super(null, null, true, false);
this.reason = reason;
@@ -1,64 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.s3;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class PolicySigner {
private final String awsAccessSecret;
private final String region;
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
public PolicySigner(final String awsAccessSecret, final String region) {
this.awsAccessSecret = awsAccessSecret;
this.region = region;
}
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
public String getSignature(final ZonedDateTime now, final String policy) {
final Mac mac;
try {
mac = Mac.getInstance("HmacSHA256");
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError("Every implementation of the Java platform is required to support HmacSHA256", e);
}
try {
mac.init(toHmacKey(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8)));
final byte[] dateKey = mac.doFinal(now.format(DATE_FORMAT).getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateKey));
final byte[] dateRegionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateRegionKey));
final byte[] dateRegionServiceKey = mac.doFinal("s3".getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateRegionServiceKey));
final byte[] signingKey = mac.doFinal("aws4_request".getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(signingKey));
return HexFormat.of().formatHex(mac.doFinal(policy.getBytes(StandardCharsets.UTF_8)));
} catch (final InvalidKeyException e) {
throw new AssertionError(e);
}
}
private static Key toHmacKey(final byte[] bytes) {
return new SecretKeySpec(bytes, "HmacSHA256");
}
}
@@ -5,31 +5,52 @@
package org.whispersystems.textsecuregcm.s3;
import com.google.common.annotations.VisibleForTesting;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import org.whispersystems.textsecuregcm.util.Pair;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class PostPolicyGenerator {
public static final DateTimeFormatter AWS_DATE_TIME = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
private static final DateTimeFormatter CREDENTIAL_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
public static final String ALGORITHM = "AWS4-HMAC-SHA256";
public static final String ACL = "private";
private static final DateTimeFormatter AWS_TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
private static final DateTimeFormatter AWS_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
private final String region;
private final String bucket;
private final String awsAccessId;
private final String awsAccessSecret;
public record SignedPostPolicy(String formattedTimestamp, String credential, String encodedPolicy, String signature) {
}
public PostPolicyGenerator(final String region,
final String bucket,
final String awsAccessId,
final String awsAccessSecret) {
public PostPolicyGenerator(final String region, final String bucket, final String awsAccessId) {
this.region = region;
this.bucket = bucket;
this.awsAccessId = awsAccessId;
this.awsAccessSecret = awsAccessSecret;
}
public Pair<String, String> createFor(final ZonedDateTime now, final String object, final int maxSizeInBytes) {
public SignedPostPolicy createFor(final String object, final int maxSizeInBytes, final Instant currentTime) {
final ZonedDateTime now = ZonedDateTime.ofInstant(currentTime, ZoneOffset.UTC);
final String expiration = now.plusMinutes(30).format(DateTimeFormatter.ISO_INSTANT);
final String credentialDate = now.format(CREDENTIAL_DATE);
final String requestDate = now.format(AWS_DATE_TIME);
final String credentialDate = now.format(AWS_DATE_FORMATTER);
final String requestTimestamp = now.format(AWS_TIMESTAMP_FORMATTER);
final String credential = String.format("%s/%s/%s/s3/aws4_request", awsAccessId, credentialDate, region);
final String policy = String.format("""
@@ -38,17 +59,55 @@ public class PostPolicyGenerator {
"conditions": [
{"bucket": "%s"},
{"key": "%s"},
{"acl": "private"},
{"acl": "%s"},
["starts-with", "$Content-Type", ""],
["content-length-range", 1, %d],
{"x-amz-credential": "%s"},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{"x-amz-algorithm": "%s"},
{"x-amz-date": "%s" }
]
}
""", expiration, bucket, object, maxSizeInBytes, credential, requestDate);
""", expiration, bucket, object, ACL, maxSizeInBytes, credential, ALGORITHM, requestTimestamp);
return new Pair<>(credential, Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8)));
final String encodedPolicy = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));
return new SignedPostPolicy(requestTimestamp, credential, encodedPolicy, getSignature(now, encodedPolicy));
}
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
@VisibleForTesting
String getSignature(final ZonedDateTime now, final String policy) {
final Mac mac;
try {
mac = Mac.getInstance("HmacSHA256");
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError("Every implementation of the Java platform is required to support HmacSHA256", e);
}
try {
mac.init(toHmacKey(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8)));
final byte[] dateKey = mac.doFinal(now.format(AWS_DATE_FORMATTER).getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateKey));
final byte[] dateRegionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateRegionKey));
final byte[] dateRegionServiceKey = mac.doFinal("s3".getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(dateRegionServiceKey));
final byte[] signingKey = mac.doFinal("aws4_request".getBytes(StandardCharsets.UTF_8));
mac.init(toHmacKey(signingKey));
return HexFormat.of().formatHex(mac.doFinal(policy.getBytes(StandardCharsets.UTF_8)));
} catch (final InvalidKeyException e) {
throw new AssertionError(e);
}
}
private static Key toHmacKey(final byte[] bytes) {
return new SecretKeySpec(bytes, "HmacSHA256");
}
}
@@ -0,0 +1,66 @@
/*
* 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,51 @@
/*
* 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}
///
/// @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);
}
}
@@ -350,7 +350,7 @@ public class MessagePersister implements Managed {
cachedMessageBytes.set(estimatedPersistedQueueSize);
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
return Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
return Flux.from(messagesManager.getMessagesForDevice(aci, device))
.concatMap(envelope -> {
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
return Mono.just(Optional.<MessageProtos.Envelope>empty());
@@ -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.
@@ -6,11 +6,14 @@ package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -23,17 +26,18 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
@@ -41,7 +45,6 @@ import reactor.core.publisher.Mono;
public class MessagesManager {
private static final int RESULT_SET_CHUNK_SIZE = 100;
final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = name(MessagesManager.class, "getMessagesForDevice");
private static final Logger logger = LoggerFactory.getLogger(MessagesManager.class);
@@ -55,27 +58,44 @@ public class MessagesManager {
private static final String MAY_HAVE_MESSAGES_COUNTER_NAME =
MetricsUtil.name(MessagesManager.class, "mayHaveMessages");
private static final String PRESENCE_MATCH_COUNTER_NAME =
MetricsUtil.name(MessagesManager.class, "presenceMatch");
@VisibleForTesting
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
@VisibleForTesting
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
private static final long FOUNDATIONDB_INSERT_TIMEOUT_MILLIS = Duration.ofSeconds(2).toMillis();
private final MessagesDynamoDb messagesDynamoDb;
private final MessagesCache messagesCache;
private final FoundationDbMessageStore foundationDbMessageStore;
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
private final ReportMessageManager reportMessageManager;
private final ExecutorService messageDeletionExecutor;
private final Clock clock;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
public MessagesManager(
final MessagesDynamoDb messagesDynamoDb,
final MessagesCache messagesCache,
final FoundationDbMessageStore foundationDbMessageStore,
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
final ReportMessageManager reportMessageManager,
final ExecutorService messageDeletionExecutor,
final Clock clock) {
final Clock clock,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.messagesDynamoDb = messagesDynamoDb;
this.messagesCache = messagesCache;
this.foundationDbMessageStore = foundationDbMessageStore;
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
this.reportMessageManager = reportMessageManager;
this.messageDeletionExecutor = messageDeletionExecutor;
this.clock = clock;
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
/**
@@ -95,28 +115,68 @@ public class MessagesManager {
private CompletableFuture<Map<Byte, Boolean>> insertAsync(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
final Map<Byte, Boolean> devicePresenceById = new ConcurrentHashMap<>();
return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
.map(deviceIdAndMessage -> {
final byte deviceId = deviceIdAndMessage.getKey();
final Envelope message = deviceIdAndMessage.getValue();
final UUID messageGuid = UUID.randomUUID();
final CompletableFuture<Map<Byte, FoundationDbMessageStore.InsertResult>> foundationDbInsertFuture;
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
.thenAccept(present -> {
if (message.hasSourceServiceId()) {
final ServiceIdentifier sourceServiceIdentifier =
ServiceIdentifier.fromByteString(message.getSourceServiceId());
if (experimentEnrollmentManager.isEnrolled(accountIdentifier, MIRROR_INSERTS_EXPERIMENT_NAME)) {
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only need/want the
// latter for FoundationDB
final Map<Byte, Envelope> minimizedMessagesByDeviceId = messagesByDeviceId.entrySet().stream()
.collect(Collectors.toUnmodifiableMap(
Map.Entry::getKey,
entry -> entry.getValue().toBuilder().clearSharedMrmKey().build()));
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
// Note that this is an asynchronous, best-effort, fire-and-forget operation
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
}
}
foundationDbInsertFuture =
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
.orTimeout(FOUNDATIONDB_INSERT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.exceptionally(e -> {
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
minimizedMessagesByDeviceId.size(),
accountIdentifier,
e);
devicePresenceById.put(deviceId, present);
});
})
.toArray(CompletableFuture[]::new))
return Collections.emptyMap();
});
} else {
foundationDbInsertFuture = CompletableFuture.completedFuture(Collections.emptyMap());
}
return foundationDbInsertFuture.thenCompose(foundationDbInsertResults ->
CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
.map(deviceIdAndMessage -> {
final byte deviceId = deviceIdAndMessage.getKey();
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only
// need/want the former for Redis
final Envelope message = deviceIdAndMessage.getValue().hasSharedMrmKey()
? deviceIdAndMessage.getValue().toBuilder().clearContent().build()
: deviceIdAndMessage.getValue();
final UUID messageGuid = Optional.ofNullable(foundationDbInsertResults.get(deviceId))
.flatMap(FoundationDbMessageStore.InsertResult::messageGuid)
.orElseGet(UUID::randomUUID);
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
.thenAccept(present -> {
if (message.hasSourceServiceId()) {
final ServiceIdentifier sourceServiceIdentifier =
ServiceIdentifier.fromByteString(message.getSourceServiceId());
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
// Note that this is an asynchronous, best-effort, fire-and-forget operation
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
}
}
devicePresenceById.put(deviceId, present);
if (foundationDbInsertResults.containsKey(deviceId)) {
Metrics.counter(PRESENCE_MATCH_COUNTER_NAME,
"match", String.valueOf(present == foundationDbInsertResults.get(deviceId).present()))
.increment();
}
});
})
.toArray(CompletableFuture[]::new)))
.thenApply(ignored -> devicePresenceById);
}
@@ -176,6 +236,7 @@ public class MessagesManager {
return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI),
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
.collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder()
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(serviceIdAndRecipient.getValue())))
.setDestinationServiceId(serviceIdentifier.toCompactByteString())
.build())))
.thenAccept(clientPresenceByDeviceId ->
@@ -217,43 +278,48 @@ public class MessagesManager {
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
}
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
boolean cachedMessagesOnly) {
return Flux.from(
getMessagesForDevice(destinationUuid, destinationDevice, RESULT_SET_CHUNK_SIZE, cachedMessagesOnly))
.take(RESULT_SET_CHUNK_SIZE)
.collectList()
.map(envelopes -> new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE));
}
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, Device destinationDevice,
final boolean cachedMessagesOnly) {
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
}
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
return new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice);
return new DeletionMirroringRedisDynamoDbMessageStream(
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice),
foundationDbMessageStore,
experimentEnrollmentManager,
destinationUuid,
destinationDevice.getId());
}
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
@Nullable Integer limit, final boolean cachedMessagesOnly) {
final Publisher<Envelope> dynamoPublisher =
cachedMessagesOnly ? Flux.empty() : messagesDynamoDb.load(destinationUuid, destinationDevice, limit);
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice.getId());
return Flux.concat(dynamoPublisher, cachePublisher)
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
return Flux.concat(
messagesDynamoDb.load(destinationUuid, destinationDevice, null),
messagesCache.get(destinationUuid, destinationDevice.getId()))
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry));
}
public CompletableFuture<Void> clear(UUID destinationUuid) {
public CompletableFuture<Void> clear(final UUID destinationUuid) {
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
messageDeletionExecutor.execute(() -> {
try {
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
} catch (final Exception e) {
logger.warn("Failed to clear messages for {}", destinationUuid, e);
}
});
}
return messagesCache.clear(destinationUuid);
}
public CompletableFuture<Void> clear(UUID destinationUuid, byte deviceId) {
public CompletableFuture<Void> clear(final UUID destinationUuid, final byte deviceId) {
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
messageDeletionExecutor.execute(() -> {
try {
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
} catch (final Exception e) {
logger.warn("Failed to clear messages for {}:{}", destinationUuid, deviceId, e);
}
});
}
return messagesCache.clear(destinationUuid, deviceId);
}
@@ -26,17 +26,23 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
@Nonnull Instant now) {
public static SubscriberCredentials process(
Optional<AuthenticatedDevice> authenticatedAccount,
String subscriberId,
Clock clock) throws SubscriptionException {
Instant now = clock.instant();
final Optional<AuthenticatedDevice> authenticatedAccount,
final String subscriberId,
final Clock clock) throws SubscriptionException {
if (authenticatedAccount.isPresent()) {
throw new SubscriptionForbiddenException("must not use authenticated connection for subscriber operations");
}
byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId);
byte[] subscriberUser = getUser(subscriberBytes);
byte[] subscriberKey = getKey(subscriberBytes);
byte[] hmac = computeHmac(subscriberUser, subscriberKey);
final byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId);
return process(subscriberBytes, clock);
}
public static SubscriberCredentials process(
final byte[] subscriberBytes,
final Clock clock) {
final Instant now = clock.instant();
final byte[] subscriberUser = getUser(subscriberBytes);
final byte[] subscriberKey = getKey(subscriberBytes);
final byte[] hmac = computeHmac(subscriberUser, subscriberKey);
return new SubscriberCredentials(subscriberBytes, subscriberUser, subscriberKey, hmac, now);
}
@@ -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,24 +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.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;
/**
@@ -103,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(),
@@ -165,10 +172,11 @@ public class SubscriptionManager {
/**
* Create a ZK receipt credential for a subscription that can be used to obtain the user entitlement
*
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
* @param request The ZK Receipt credential request
* @param expiration A function that takes a {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem}
* and returns the expiration time of the receipt
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
* @param receiptCredentialRequestBytes The raw bytes of the ZK Receipt credential request
* @param expiration A function that takes a
* {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem} and returns the
* expiration time of the receipt
* @return the requested ZK receipt credential
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a
@@ -178,12 +186,13 @@ public class SubscriptionManager {
* user an entitlement
* @throws SubscriptionReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction
* was still open
* @throws SubscriptionReceiptAlreadyRedeemedException if the receipt was already redeemed by a different request
* @throws SubscriptionReceiptAlreadyRedeemedException if the receipt was already redeemed by a different
* request
* @throws RateLimitExceededException if rate-limited
*/
public ReceiptResult createReceiptCredentials(
final SubscriberCredentials subscriberCredentials,
final SubscriptionController.GetReceiptCredentialsRequest request,
final byte[] receiptCredentialRequestBytes,
final Function<CustomerAwareSubscriptionPaymentProcessor.ReceiptItem, Instant> expiration)
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionReceiptAlreadyRedeemedException {
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
@@ -193,7 +202,7 @@ public class SubscriptionManager {
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest());
receiptCredentialRequest = new ReceiptCredentialRequest(receiptCredentialRequestBytes);
} catch (final InvalidInputException e) {
throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e);
}
@@ -239,7 +248,7 @@ public class SubscriptionManager {
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
* attached
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
* the subscriberId
*/
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> R addPaymentMethodToCustomer(
@@ -313,7 +322,7 @@ public class SubscriptionManager {
final String idempotencyKey,
final String subscriptionTemplateId,
final LevelTransitionValidator transitionValidator)
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException, SubscriptionProcessorException {
throws SubscriptionInvalidLevelException, SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException, SubscriptionProcessorConflictException, SubscriptionProcessorException {
if (record.subscriptionId != null) {
// we already have a subscription in our records so let's check the level and currency,
@@ -364,7 +373,7 @@ public class SubscriptionManager {
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
* attached
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
* the subscriberId
* @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an
* entitlement
@@ -416,7 +425,7 @@ public class SubscriptionManager {
* @return the subscription level for the accepted subscription
* @throws SubscriptionForbiddenException if the subscriber credentials are incorrect
* @throws SubscriptionNotFoundException if the originalTransactionId does not exist
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
* the subscriber
* @throws SubscriptionInvalidArgumentsException if the originalTransactionId is malformed or does not represent a
* valid subscription
@@ -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,19 +10,27 @@ 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.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
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.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
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;
@@ -40,7 +49,10 @@ import org.whispersystems.textsecuregcm.util.Util;
/// * {versionstamp_2} => envelope_2
public class FoundationDbMessageStore {
private final Database[] databases;
private final Database[][] databasesByEpoch;
private final Map<Database, VersionstampClock> versionstampClocks;
private final int[] liveEpochs;
private final int activeEpoch;
private final VersionstampUUIDCipher versionstampUUIDCipher;
private final Clock clock;
@@ -53,20 +65,57 @@ public class FoundationDbMessageStore {
/// suggest a limit of 1MB to avoid performance issues, although the hard limit is 10MB
private static final long MAX_MESSAGE_CHUNK_SIZE = DataSize.megabytes(1).toBytes();
// We pack the current configuration epoch and shard ID into a single byte of "user data" in each message
// versionstamp. We use two bits for the epoch and six for the shard ID.
public static final int MAX_EPOCHS = 4;
public static final int MAX_SHARDS = 64;
private static final Counter INSERT_MESSAGE_COUNTER =
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessage"));
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
/// otherwise
/// @param messageGuid the versionstamp encrypted/encoded as a version 8 UUID
/// @param present whether the device is online
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
public record InsertResult(Optional<Versionstamp> versionstamp,
Optional<UUID> messageGuid,
boolean present) {
}
public FoundationDbMessageStore(final Database[] databases,
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
final int activeEpoch,
final VersionstampUUIDCipher versionstampUUIDCipher,
final Clock clock) {
this.databases = databases;
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
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.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;
}
@@ -79,7 +128,15 @@ public class FoundationDbMessageStore {
public CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId))
return insert(aciServiceIdentifier, messagesByDeviceId, activeEpoch);
}
@VisibleForTesting
CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final int epoch) {
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId), epoch)
.thenApply(resultsByServiceIdentifier -> {
assert resultsByServiceIdentifier.size() == 1;
@@ -101,6 +158,16 @@ public class FoundationDbMessageStore {
public CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier) {
return insert(messagesByServiceIdentifier, activeEpoch);
}
@VisibleForTesting
CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier,
final int epoch) {
final Timer.Sample sample = Timer.start();
if (messagesByServiceIdentifier.entrySet()
.stream()
.anyMatch(entry -> entry.getValue().isEmpty())) {
@@ -117,7 +184,7 @@ public class FoundationDbMessageStore {
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
messagesByServiceIdentifier.entrySet().stream()
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey(), epoch)));
final List<CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>>> chunkFutures =
new ArrayList<>();
@@ -133,7 +200,7 @@ public class FoundationDbMessageStore {
.sum();
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, current)));
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, current)));
start = current;
estimatedTransactionSize = 0;
@@ -143,7 +210,7 @@ public class FoundationDbMessageStore {
}
assert start < messagesForShard.size();
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, messagesForShard.size())));
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, messagesForShard.size())));
});
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
@@ -152,11 +219,18 @@ public class FoundationDbMessageStore {
.reduce(new HashMap<>(), (a, b) -> {
a.putAll(b);
return a;
}));
}))
.whenComplete((_, throwable) -> {
if (throwable == null) {
sample.stop(INSERT_MESSAGE_BATCH_TIMER);
INSERT_MESSAGE_COUNTER.increment(messagesByServiceIdentifier.values().stream().mapToInt(Map::size).sum());
}
});
}
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
final int shardId,
final int epoch,
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
@@ -168,9 +242,9 @@ public class FoundationDbMessageStore {
.map(MessageProtos.Envelope::getEphemeral)
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
return databases[shardId].runAsync(transaction -> {
return getDatabases(epoch)[shardId].runAsync(transaction -> {
messagesByAccountIdentifier.forEach(entry ->
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), epoch, shardId, transaction)));
return CompletableFuture.allOf(insertFuturesByAci.values().toArray(CompletableFuture[]::new))
.thenApply(_ -> {
@@ -181,7 +255,8 @@ public class FoundationDbMessageStore {
.anyMatch(isPresent -> isPresent);
if (anyClientPresent || !ephemeral) {
return transaction.getVersionstamp()
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes, shardId)));
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes,
packUserData(epoch, shardId))));
}
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
});
@@ -201,7 +276,11 @@ public class FoundationDbMessageStore {
} else {
insertResultVersionstamp = Optional.empty();
}
return new InsertResult(insertResultVersionstamp, presenceEntry.getValue());
return new InsertResult(insertResultVersionstamp,
insertResultVersionstamp.map(versionstamp ->
versionstampUUIDCipher.encryptVersionstamp(versionstamp, entry.getKey().uuid(), presenceEntry.getKey())),
presenceEntry.getValue());
}));
})));
}
@@ -217,6 +296,8 @@ public class FoundationDbMessageStore {
/// @return a future that yields the presence state of each destination device
private CompletableFuture<Map<Byte, Boolean>> insert(final AciServiceIdentifier aci,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final int epoch,
final int shardId,
final Transaction transaction) {
final Map<Byte, CompletableFuture<Boolean>> messageInsertFuturesByDeviceId = messagesByDeviceId.entrySet()
@@ -232,7 +313,7 @@ public class FoundationDbMessageStore {
if (isPresent || !message.getEphemeral()) {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
getDeviceQueueSubspace(aci, deviceId)
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci)))), message.toByteArray());
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId)))), message.toByteArray());
}
return isPresent;
@@ -251,43 +332,183 @@ public class FoundationDbMessageStore {
if (anyClientPresent) {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci))).packWithVersionstamp());
Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId))).packWithVersionstamp());
}
return presenceByDeviceId;
});
}
// 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());
return null;
}));
}
public void clearAll(final AciServiceIdentifier aci, final byte deviceId) {
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
transaction.clear(getDeviceSubspace(aci, deviceId).range());
return null;
}));
}
private void doForAllDatabasesWithMessages(final AciServiceIdentifier aci, final Consumer<Database> action) {
IntStream.range(0, databasesByEpoch.length)
.filter(epoch -> databasesByEpoch[epoch] != null)
.mapToObj(epoch -> databasesByEpoch[epoch][hashAciToShardNumber(aci, epoch)])
.distinct()
.forEach(action);
}
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
}
@VisibleForTesting
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice,
final int maxMessagesPerScan, final int maxUnacknowledgedMessages, final Runnable doAfterCleanup) {
MessageStream getMessages(final AciServiceIdentifier aci,
final Device destinationDevice,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
// 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 (final int epoch : liveEpochs) {
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
}
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
getMessagesAvailableWatchKey(aci),
getShardForAci(aci),
databasesForQueueByEpoch,
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
maxMessagesPerScan,
maxUnacknowledgedMessages,
doAfterCleanup);
}
/// 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) {
return Tuple.fromBytes(messageKey).getVersionstamp(4);
}
@VisibleForTesting
Database getShardForAci(final AciServiceIdentifier aci) {
return databases[hashAciToShardNumber(aci)];
Database getShardForAci(final AciServiceIdentifier aci, final int epoch) {
return getDatabases(epoch)[hashAciToShardNumber(aci, epoch)];
}
private Database[] getDatabases(final int epoch) {
if (databasesByEpoch[epoch] == null) {
throw new IllegalStateException("Epoch (%d) not in static configuration".formatted(epoch));
}
return databasesByEpoch[epoch];
}
@VisibleForTesting
int hashAciToShardNumber(final AciServiceIdentifier aci) {
int hashAciToShardNumber(final AciServiceIdentifier aci, final int epoch) {
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), getDatabases(epoch).length);
}
@VisibleForTesting
static int packUserData(final int epoch, final int shardId) {
if (epoch < 0 || epoch >= MAX_EPOCHS) {
throw new IllegalArgumentException("Epoch (%d) outside of allowable range (0 to %d, exclusive)".formatted(
epoch, MAX_EPOCHS));
}
if (shardId < 0 || shardId >= MAX_SHARDS) {
throw new IllegalArgumentException("Shard ID (%d) outside of allowable range (0 to %d, exclusive)".formatted(
epoch, MAX_SHARDS));
}
return epoch << 6 | shardId;
}
static int getConfigurationEpoch(final Versionstamp versionstamp) {
return versionstamp.getUserVersion() >> 6 & 0x03;
}
@VisibleForTesting
static int getShardId(final Versionstamp versionstamp) {
return versionstamp.getUserVersion() & 0x3f;
}
@VisibleForTesting
@@ -13,12 +13,18 @@ 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.util.Arrays;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.MessageStream;
@@ -27,43 +33,62 @@ import org.whispersystems.textsecuregcm.util.Pair;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
/// A [MessageStream] implementation that fetches messages from FoundationDB
public class FoundationDbMessageStream implements MessageStream {
private final Subspace deviceQueueSubspace;
private final byte[] messagesAvailableWatchKey;
private final Database database;
private final Database[] databasesByEpoch;
private final MessageGuidCodec messageGuidCodec;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
private final AcknowledgedMessageBuffer acknowledgedMessageBuffer;
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;
@VisibleForTesting
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
final byte[] messagesAvailableWatchKey,
final Database database,
final Database[] databasesByEpoch,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.database = database;
this.databasesByEpoch = databasesByEpoch;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
this.acknowledgedMessageBuffer = new AcknowledgedMessageBuffer(maxUnacknowledgedMessages);
// 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
// buffer per distinct shard, so find the distinct shards for this queue and create a buffer for each.
this.acknowledgedMessageBuffersByDatabase = Arrays.stream(databasesByEpoch)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toMap(database -> database,
_ -> new AcknowledgedMessageBuffer(maxUnacknowledgedMessages),
(_, _) -> {
throw new AssertionError("Duplicate database in distinct stream");
},
IdentityHashMap::new));
}
@Override
@@ -81,7 +106,7 @@ public class FoundationDbMessageStream implements MessageStream {
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
try {
acknowledgedMessageBuffer.addUnacknowledgedMessage(message.versionstamp());
getAcknowledgedMessageBuffer(message.versionstamp()).addUnacknowledgedMessage(message.versionstamp());
} catch (final TooManyUnacknowledgedMessagesException e) {
sink.error(e);
return;
@@ -107,34 +132,75 @@ public class FoundationDbMessageStream implements MessageStream {
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
/// See [FoundationDbMessageStore] for more details on the message insert process.
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
.flatMapMany(maybeEndOfQueueKeyExclusive -> {
final Flux<FoundationDbMessageStreamEntry.Message> finitePublisher = maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive, database, maxMessagesPerScan, this::clearAcknowledgedMessages).getMessages())
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
// Ephemeral messages from the finite stream are considered stale and automatically discarded
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
acknowledgedMessageBuffer.acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
staleEphemeralMessagesCounter.increment();
return;
}
sink.next(fdbMessageStreamEntry);
});
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
final Flux<FoundationDbMessageStreamEntry.Message> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
infinitePublisherBeginKey, KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
database, maxMessagesPerScan, messagesAvailableWatchKey, this::clearAcknowledgedMessages).getMessages();
return Flux.concat(
finitePublisher,
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()),
infinitePublisher
);
});
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
// `Flux#fromArray` cannot handle `null` elements
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
return Flux.fromIterable(databases)
.flatMap(database -> Mono.fromFuture(getEndOfQueueKeyExclusive(database))
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
.collectMap(Tuple2::getT1, Tuple2::getT2)
.flatMapMany(endOfQueueKeysByDatabase -> {
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
endOfQueueKeysByDatabase.entrySet().stream()
.map(entry -> {
final Database database = entry.getKey();
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
return maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive,
database,
maxMessagesPerScan,
() -> this.clearAcknowledgedMessages(database))
.getMessages())
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
// Ephemeral messages from the finite stream are considered stale and automatically discarded
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
acknowledgedMessageBuffersByDatabase.get(database).acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
staleEphemeralMessagesCounter.increment();
return;
}
sink.next(fdbMessageStreamEntry);
});
})
.toArray(Flux[]::new);
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] infinitePublishers =
endOfQueueKeysByDatabase.entrySet().stream()
.map(entry -> {
final Database database = entry.getKey();
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive
.orElseGet(() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
return FoundationDbMessagePublisher.createInfinitePublisher(
infinitePublisherBeginKey,
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
database,
maxMessagesPerScan,
messagesAvailableWatchKey,
() -> clearAcknowledgedMessages(database)).getMessages();
})
.toArray(Flux[]::new);
return Flux.concat(
Flux.mergeComparing(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers),
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()),
// Note that we use `mergePriority` instead of `mergeComparing` for the "live"/non-terminating publishers
// because `mergePriority` sorts messages _as they arrive._ If we used `mergeComparing` for the live
// streams and one of the streams had no new messages (which will be true most of the time), then the
// merged publisher would never emit any signals because it'd be waiting to have something to compare
// against. This does mean that we risk some slightly out-of-order messages in the exceedingly rare cases
// where messages arrive at different servers while somebody is connected and a migration is in progress,
// but that should be (again) exceedingly rare and also minimally-disruptive (i.e. it would self-correct
// so quickly that end users would likely never even notice).
Flux.mergePriority(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, infinitePublishers));
});
}
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows us
@@ -142,7 +208,7 @@ public class FoundationDbMessageStream implements MessageStream {
/// subsequent scan.
///
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final Database database) {
return database.runAsync(
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
.thenApply(items -> {
@@ -156,7 +222,8 @@ public class FoundationDbMessageStream implements MessageStream {
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
acknowledgedMessageBuffer.acknowledgeMessage(messageGuidCodec.decodeMessageGuid(messageGuid));
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
return CompletableFuture.completedFuture(null);
}
@@ -174,20 +241,39 @@ public class FoundationDbMessageStream implements MessageStream {
/// Clear all outstanding acknowledged messages. Called when the stream ends
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages();
return database.runAsync(transaction -> {
clearAllAcknowlegedMessagedConsumer.accept(transaction);
return CompletableFuture.completedFuture((Void) null);
return CompletableFuture.allOf(Arrays.stream(databasesByEpoch)
.filter(Objects::nonNull)
.distinct()
.map(database -> {
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages(database);
return database.runAsync(transaction -> {
clearAllAcknowlegedMessagedConsumer.accept(transaction);
return CompletableFuture.completedFuture((Void) null);
})
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear acknowledged messages", throwable);
}
});
})
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear acknowledged messages", throwable);
}
});
.toArray(CompletableFuture[]::new));
}
private synchronized Consumer<Transaction> clearAcknowledgedMessages() {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = acknowledgedMessageBuffer.takeFlushableRanges();
private AcknowledgedMessageBuffer getAcknowledgedMessageBuffer(final Versionstamp versionstamp) {
final int epoch = FoundationDbMessageStore.getConfigurationEpoch(versionstamp);
final Database database = databasesByEpoch[epoch];
if (database == null) {
throw new IllegalStateException("Read message for unrecognized epoch");
}
return acknowledgedMessageBuffersByDatabase.get(database);
}
private synchronized Consumer<Transaction> clearAcknowledgedMessages(final Database database) {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges =
acknowledgedMessageBuffersByDatabase.get(database).takeFlushableRanges();
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
}
@@ -0,0 +1,96 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeyValue;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.subspace.Subspace;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Instant;
import java.util.Iterator;
import java.util.Optional;
/// A "versionstamp clock" records versionstamp/time pairs in a FoundationDB database. The purpose of the "clock" is to
/// allow callers to get the versionstamp of a FoundationDB database at a specific real-world time to facilitate
/// time-related range queries (e.g. "clear all keys with a versionstamp less than or equal to the versionstamp from
/// seven days ago, since those keys are now expired").
///
/// Some external component should call [#recordVersionstampAndTime()] at regular, application-appropriate
/// intervals to maintain a running mapping of real-world timestamps to FoundationDB versionstamps.
public class VersionstampClock {
@VisibleForTesting
static final Subspace SUBSPACE = new Subspace(Tuple.from("V"));
private final Database database;
private final Clock clock;
public VersionstampClock(final Database database) {
this(database, Clock.systemUTC());
}
@VisibleForTesting
public VersionstampClock(final Database database, final Clock clock) {
this.database = database;
this.clock = clock;
}
/// Make a recording in the database of the current time and associated versionstamp.
///
/// @return the versionstamp for the newly-recorded entry
public Versionstamp recordVersionstampAndTime() {
final Instant currentTime = clock.instant();
return database.run(transaction -> {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE,
getTimestampKey(currentTime),
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
return transaction.getVersionstamp();
})
.thenApply(Versionstamp::complete)
.join();
}
/// Returns the highest versionstamp recorded at or before the given instant.
///
/// @param timestamp the time for which to retrieve a versionstamp
///
/// @return the highest versionstamp recorded at or before the given instant, or empty if no versionstamps have been recorded before the given instant
public Optional<Versionstamp> getVersionstamp(final Instant timestamp) {
return database.read(transaction -> {
final byte[] rangeStart = SUBSPACE.getKey();
final byte[] rangeEnd = getTimestampKey(timestamp.plusMillis(1));
final Iterator<KeyValue> keyValueIterator = transaction.getRange(rangeStart, rangeEnd, 1, true).iterator();
if (keyValueIterator.hasNext()) {
return Optional.of(Tuple.fromBytes(keyValueIterator.next().getValue()).getVersionstamp(0));
}
return Optional.empty();
});
}
/// Remove any entries from the versionstamp-clock namespace that are strictly older than the given timestamp
///
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
public void clearExpiredEntries(final Instant oldestRetainedEntryTimestamp) {
database.run(transaction -> {
transaction.clear(SUBSPACE.getKey(), getTimestampKey(oldestRetainedEntryTimestamp));
return null;
});
}
private byte[] getTimestampKey(final Instant timestamp) {
return SUBSPACE.pack(timestamp.toEpochMilli());
}
}
@@ -0,0 +1,40 @@
/// These classes manage message storage in a set of FoundationDB databases.
///
/// # Schema
///
/// ## Sharding
/// The messages database is expected to be larger than a single FoundationDB cluster
/// can handle, and is therefore sharded by recipient ACI. The shard for a
/// given recipient is identified by a [consistent
/// hash][com.google.common.hash.Hashing#consistentHash()] applied to the low
/// 64 bits of the ACI.
///
/// ## Messages
/// * Root subspace `M`
/// * Managed by [FoundationDbMessageStore]
/// * Sharded by ACI: database `i` of `n` will only contain account subspaces for
/// UUIDs where `consistentHash(u.getLeastSignificantBits(), n) == i`
/// * Contains mailboxes and associated bookkeeping information for each user
/// * Schema:
/// ```
/// + "M" (messages subspace)
/// | + {aci (UUID)} (account subspace)
/// | | * "l" => messages-available watch key, versionstamp of last message inserted when any recipient
/// | | device was present
/// | | + {device ID (byte)} (device subspace)
/// | | | * "p" => presence: server-id || last-seen-time
/// | | | + "Q" (device message queue subspace)
/// | | | | * versionstamp => serialized envelope
/// ```
///
/// ## Versionstamp Clock
/// * Root subspace `V`
/// * Managed by [VersionstampClock]
/// * Exists in every messages database; (necessarily) independent for each
/// * Global metadata tracking a mapping from time to versionstamp for the expired-message cleaner
/// * Schema:
/// ```
/// + "V" (versionstamp-clock subspace)
/// | + unix time => versionstamp
/// ```
package org.whispersystems.textsecuregcm.storage.foundationdb;
@@ -0,0 +1,20 @@
package org.whispersystems.textsecuregcm.subscriptions;
import io.swagger.v3.oas.annotations.media.Schema;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@Schema(description = "Configuration for a currency - use to present appropriate client interfaces")
public record CurrencyConfiguration(
@Schema(description = "The minimum amount that may be submitted for a one-time donation in the currency")
BigDecimal minimum,
@Schema(description = "A map of numeric one-time donation level IDs to the list of default amounts to be presented")
Map<Long, List<BigDecimal>> oneTime,
@Schema(description = "A map of numeric subscription level IDs to the amount charged for that level")
Map<Long, BigDecimal> subscription,
@Schema(description = "A map of numeric backup level IDs to the amount charged for that level")
Map<Long, BigDecimal> backupSubscription,
@Schema(description = "The payment methods that support the given currency")
List<PaymentMethod> supportedPaymentMethods) {}
@@ -56,14 +56,13 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
* @param level The level of the subscription
* @param lastSubscriptionCreatedAt The timestamp of the last successfully created subscription
* @return A subscription identifier
* @throws SubscriptionProcessorException If there was a failure processing the charge
* @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a
* modified request, or if the payment requires additional steps
* before charging
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
* @throws SubscriptionProcessorException If there was a failure processing the charge
* @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging
* @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
*/
SubscriptionId createSubscription(String customerId, String templateId, long level, long lastSubscriptionCreatedAt)
throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException;
throws SubscriptionProcessorException, SubscriptionPaymentRequiresActionException, SubscriptionInvalidIdempotencyKeyException, SubscriptionProcessorConflictException;
/**
* Update an existing subscription on a customer
@@ -73,14 +72,15 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
* @param level The target level of the subscription
* @param idempotencyKey An idempotency key to prevent retries of successful requests
* @return A subscription identifier
* @throws SubscriptionProcessorException If there was a failure processing the charge
* @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a
* modified request, or if the payment requires additional steps
* before charging
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
* @throws SubscriptionProcessorException If there was a failure processing the charge
* @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
* @throws SubscriptionInvalidLevelException If the level transition is not permitted
* @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
*/
SubscriptionId updateSubscription(Object subscription, String templateId, long level, String idempotencyKey)
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException, SubscriptionProcessorConflictException;
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionInvalidLevelException,
SubscriptionPaymentRequiresActionException, SubscriptionProcessorException, SubscriptionProcessorConflictException;
/**
* @param subscription
@@ -0,0 +1,9 @@
package org.whispersystems.textsecuregcm.subscriptions;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.entities.Badge;
@Schema(description = "Configuration for a donation level - use to present appropriate client interfaces")
public record LevelConfiguration(
@Schema(description = "The displayable badge associated with the level")
Badge badge) {}
@@ -47,4 +47,13 @@ public enum PaymentProvider {
public byte getId() {
return id;
}
public org.signal.chat.subscriptions.PaymentProvider toProto() {
return switch (this) {
case STRIPE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE;
case BRAINTREE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE;
case GOOGLE_PLAY_BILLING -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING;
case APPLE_APP_STORE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE;
};
}
}
@@ -285,7 +285,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
@Override
public SubscriptionId createSubscription(String customerId, String priceId, long level,
long lastSubscriptionCreatedAt)
throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException {
throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException,
SubscriptionPaymentRequiresActionException {
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
// retries this request
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
@@ -307,7 +308,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
return new SubscriptionId(subscription.getId());
} catch (IdempotencyException e) {
throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage());
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
} catch (CardException e) {
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
} catch (StripeException e) {
@@ -320,7 +321,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
@Override
public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey)
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException {
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException,
SubscriptionProcessorException {
final Subscription subscription = getSubscription(subscriptionObj);
@@ -359,7 +361,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
return new SubscriptionId(subscription1.getId());
} catch (IdempotencyException e) {
throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage());
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
} catch (CardException e) {
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
} catch (StripeException 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);
}
}
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
public class SubscriptionInvalidIdempotencyKeyException extends SubscriptionInvalidArgumentsException {
public SubscriptionInvalidIdempotencyKeyException(final String message) {
super(message);
}
}
@@ -1,14 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import io.dropwizard.util.DataSize;
public class Constants {
public static final String METRICS_NAME = "textsecure";
public static final int MAXIMUM_STICKER_SIZE_BYTES = (int) DataSize.kibibytes(300 + 1).toBytes(); // add 1 kiB for encryption overhead
public static final int MAXIMUM_STICKER_MANIFEST_SIZE_BYTES = (int) DataSize.kibibytes(10).toBytes();
}
@@ -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");
@@ -38,6 +38,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
private final AccountsManager accountsManager;
private final DisconnectionRequestManager disconnectionRequestManager;
private final WebSocketConnectionBuilder webSocketConnectionBuilder;
private final MessageMetrics messageMetrics;
private final OpenWebSocketCounter openAuthenticatedWebSocketCounter;
private final OpenWebSocketCounter openUnauthenticatedWebSocketCounter;
@@ -66,6 +67,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
disconnectionRequestManager,
asnInfoProviderSupplier,
clientReleaseManager,
messageMetrics,
(account, device, client) -> new WebSocketConnection(receiptSender,
messagesManager,
messageMetrics,
@@ -86,11 +88,13 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
final DisconnectionRequestManager disconnectionRequestManager,
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final ClientReleaseManager clientReleaseManager,
final MessageMetrics messageMetrics,
final WebSocketConnectionBuilder webSocketConnectionBuilder) {
this.accountsManager = accountsManager;
this.disconnectionRequestManager = disconnectionRequestManager;
this.webSocketConnectionBuilder = webSocketConnectionBuilder;
this.messageMetrics = messageMetrics;
this.openAuthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-authenticated", asnInfoProviderSupplier, clientReleaseManager);
this.openUnauthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-unauthenticated", asnInfoProviderSupplier, clientReleaseManager);
@@ -102,46 +106,52 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
final boolean authenticated = (context.getAuthenticated() != null);
(authenticated ? openAuthenticatedWebSocketCounter : openUnauthenticatedWebSocketCounter).countOpenWebSocket(context);
if (!authenticated) {
return;
}
if (authenticated) {
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
final Optional<Account> maybeAuthenticatedAccount =
accountsManager.getByAccountIdentifier(auth.accountIdentifier());
final Optional<Account> maybeAuthenticatedAccount =
accountsManager.getByAccountIdentifier(auth.accountIdentifier());
final Optional<Device> maybeAuthenticatedDevice =
maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
final Optional<Device> maybeAuthenticatedDevice =
maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
if (maybeAuthenticatedAccount.isEmpty() || maybeAuthenticatedDevice.isEmpty()) {
log.warn("{}:{} not found when opening authenticated WebSocket", auth.accountIdentifier(), auth.deviceId());
if (maybeAuthenticatedAccount.isEmpty() || maybeAuthenticatedDevice.isEmpty()) {
log.warn("{}:{} not found when opening authenticated WebSocket", auth.accountIdentifier(), auth.deviceId());
context.getClient().close(1011, "Unexpected error initializing connection");
return;
}
context.getClient().close(1011, "Unexpected error initializing connection");
return;
}
final WebSocketConnection connection =
webSocketConnectionBuilder.buildWebSocketConnection(maybeAuthenticatedAccount.get(),
maybeAuthenticatedDevice.get(),
context.getClient());
final Account account = maybeAuthenticatedAccount.get();
final Device device = maybeAuthenticatedDevice.get();
disconnectionRequestManager.addListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
maybeAuthenticatedDevice.get().getId(),
connection);
final boolean disableMessages = context.getClient().shouldDisableMessages();
context.addWebsocketClosedListener((_, _, _) -> {
disconnectionRequestManager.removeListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
maybeAuthenticatedDevice.get().getId(),
connection);
final Optional<WebSocketConnection> maybeWebSocketConnection = disableMessages
? Optional.empty()
: Optional.of(webSocketConnectionBuilder.buildWebSocketConnection(account, device, context.getClient()));
connection.stop();
});
final WebSocketDisconnectionRequestListener disconnectionListener =
new WebSocketDisconnectionRequestListener(messageMetrics, context.getClient(), disableMessages);
try {
connection.start();
} catch (final Exception e) {
log.warn("Failed to initialize websocket", e);
context.getClient().close(1011, "Unexpected error initializing connection");
}
disconnectionRequestManager
.addListener(account.getIdentifier(IdentityType.ACI), device.getId(), disconnectionListener);
context.addWebsocketClosedListener((_, _, _) -> {
disconnectionRequestManager
.removeListener(account.getIdentifier(IdentityType.ACI), device.getId(), disconnectionListener);
maybeWebSocketConnection.ifPresent(WebSocketConnection::stop);
});
try {
maybeWebSocketConnection.ifPresent(WebSocketConnection::start);
} catch (final Exception e) {
log.warn("Failed to initialize websocket", e);
context.getClient().close(1011, "Unexpected error initializing connection");
}
}
}
@@ -15,7 +15,6 @@ import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.time.Duration;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -29,7 +28,6 @@ import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StaticException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
@@ -62,7 +60,7 @@ import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
public class WebSocketConnection implements DisconnectionRequestListener {
public class WebSocketConnection {
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
@@ -333,10 +331,4 @@ public class WebSocketConnection implements DisconnectionRequestListener {
throwable instanceof org.eclipse.jetty.io.EofException ||
(throwable instanceof StaticException staticException && "Closed".equals(staticException.getMessage()));
}
@Override
public void handleDisconnectionRequest() {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, false);
client.close(4401, "Reauthentication required");
}
}
@@ -0,0 +1,33 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.websocket;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.WebSocketClient;
class WebSocketDisconnectionRequestListener implements DisconnectionRequestListener {
private final MessageMetrics messageMetrics;
private final String metricChannel;
private final WebSocketClient client;
WebSocketDisconnectionRequestListener(final MessageMetrics messageMetrics, final WebSocketClient client, final boolean disableMessages) {
this.messageMetrics = messageMetrics;
this.client = client;
this.metricChannel = disableMessages
? MessageMetrics.MESSAGELESS_WEBSOCKET_CHANNEL
: MessageMetrics.WEBSOCKET_CHANNEL;
}
@Override
public void handleDisconnectionRequest() {
final UserAgent userAgent = UserAgentUtil.maybeParseUserAgentString(client.getUserAgent());
messageMetrics.measureMessageStreamDisplaced(metricChannel, userAgent, false);
client.close(4401, "Reauthentication required");
}
}
@@ -5,18 +5,23 @@
package org.whispersystems.textsecuregcm.workers;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.core.setup.Environment;
import io.lettuce.core.resource.ClientResources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.stream.Collectors;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
@@ -56,6 +61,7 @@ import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriodManager
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.DynamoDbRecoveryManager;
import org.whispersystems.textsecuregcm.storage.FoundationDbVersion;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesCache;
@@ -75,6 +81,8 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
@@ -127,6 +135,39 @@ public record CommandDependencies(
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final FDB fdb = FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion());
// Jetty and the FoundationDB client both register shutdown hooks to begin shutdown/cleanup operations. There isn't
// a good way to coordinate or enforce ordering between shutdown hooks, and so the two processes will race.
// Generally, FoundationDB will shut down before Jetty does, meaning we'll still be trying to serve requests that
// require talking to FoundationDB even though FoundationDB has shut down. To avoid that scenario, we disabled
// FoundationDB's shutdown hook and let the JVM terminate its (daemon) threads at exit. This isn't as graceful as
// we'd like, but is the least bad option given current constraints.
fdb.disableShutdownHook();
final Map<Integer, List<Database>> messageDatabasesByEpoch;
{
final Map<String, Database> databasesByName =
configuration.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> {
try {
final Database database = entry.getValue().build(fdb);
database.options().setMaxWatches(configuration.getFoundationDbMessagesConfiguration().maxWatchesPerClient());
return database;
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}));
messageDatabasesByEpoch = configuration.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(databasesByName::get)
.toList()));
}
final AwsCredentialsProvider awsCredentialsProvider = configuration.getAwsCredentialsConfiguration().build();
ScheduledExecutorService dynamicConfigurationExecutor = ScheduledExecutorServiceBuilder.of(environment, "dynamicConfiguration")
@@ -268,6 +309,11 @@ public record CommandDependencies(
disconnectionRequestListenerExecutor, retryExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC());
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
configuration.getFoundationDbMessagesConfiguration().activeEpoch(),
new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
configuration.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
Clock.systemUTC());
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
@@ -277,8 +323,9 @@ public record CommandDependencies(
configuration.getReportMessageConfiguration().getCounterTtl());
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionExecutor, Clock.systemUTC());
final MessagesManager messagesManager =
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionExecutor, Clock.systemUTC(), experimentEnrollmentManager);
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
@@ -345,6 +345,11 @@ enum SendVerificationCodeErrorType {
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD = 7;
/**
* No senders are available for the requested region/transport
*/
SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE = 8;
}
message CheckVerificationCodeRequest {
@@ -34,17 +34,23 @@ The server may set the `reason` to match the enum string for the `Status.Code` i
The chat server may return the following errors from any RPC
| Status Code | Reason | Description |
| :---- | :---- |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `INVALID_ARGUMENT` | `UPGRADE_REQUIRED` | The client version provided in the `User-Agent` is no longer supported. The client must upgrade to use the service. |
| `INVALID_ARGUMENT` | `CONSTRAINT_VIOLATED` | The RPC argument violated a constraint that was annotated or documented in the service definition. It is always possible to check this constraint without communicating with the chat server. This always represents a client bug or out of date client. <br><br> The `details` may include a [`BadRequest` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L236) that indicates additional information about the invalid field. |
| `INVALID_ARGUMENT` | `BAD_AUTHENTICATION` | The request has incorrectly set authentication credentials for the RPC. This represents a client bug where the authorization mode is not correct for the RPC. For example, <br><br> The RPC was for an anonymous service, but included an Authentication header in the RPC metadata. <br><br>The RPC should only be made by the primary device, but the request had linked device credentials. |
| `UNAUTHENTICATED` | `INVALID_CREDENTIALS` | The account credentials provided in the authorization header are not valid. |
| `RESOURCE_EXHAUSTED` | `RESOURCE_EXHAUSTED` | A server-side resource was exhausted. The `details` field may include a [`RetryInfo` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L92) that includes the amount of time in seconds the client should wait before retrying the request. <br><br> If a `RetryInfo` is present, the client must wait the indicated time before retrying the request. If absent, the client should retry with an exponential backoff. |
| `UNAVAILABLE` | `UNAVAILABLE` | There was an internal error processing the RPC. The client should retry the request with exponential backoff. |
| Status Code | Reason | Description |
|:---------------------|:----------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `INVALID_ARGUMENT` | `UPGRADE_REQUIRED` | The client version provided in the `User-Agent` is no longer supported. The client must upgrade to use the service. |
| `INVALID_ARGUMENT` | `CONSTRAINT_VIOLATED` | The RPC argument violated a constraint that was annotated or documented in the service definition. It is always possible to check this constraint without communicating with the chat server. This always represents a client bug or out of date client. <br><br> The `details` may include a [`BadRequest` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L236) that indicates additional information about the invalid field. |
| `INVALID_ARGUMENT` | `BAD_AUTHENTICATION` | The request has incorrectly set authentication credentials for the RPC. This represents a client bug where the authorization mode is not correct for the RPC. For example, <br><br> The RPC was for an anonymous service, but included an Authentication header in the RPC metadata. <br><br>The RPC should only be made by the primary device, but the request had linked device credentials. |
| `UNAUTHENTICATED` | `INVALID_CREDENTIALS` | The account credentials provided in the authorization header are not valid. |
| `RESOURCE_EXHAUSTED` | `RESOURCE_EXHAUSTED` | A server-side resource was exhausted. The `details` field may include a [`RetryInfo` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L92) that includes the amount of time in seconds the client should wait before retrying the request. <br><br> If a `RetryInfo` is present, the client must wait the indicated time before retrying the request. If absent, the client should retry with an exponential backoff. |
| `ABORTED` | `STREAM_CLOSED` | The server terminated a streaming RPC for some domain specific reason. The `details` field must include a message with additional information about why the stream was closed. This message must be defined in the corresponding service proto for the streaming RPC. This status must only be returned from server-side streaming RPCs. Clients must handle a STREAM_CLOSED status even if no corresponding message is defined in the version of the proto they are targeting. Unless otherwise noted, if a stream termination message is defined, clients must handle the error at any point in the message stream. |
| `UNAVAILABLE` | `UNAVAILABLE` | There was an internal error processing the RPC. The client should retry the request with exponential backoff. |
### Logging Errors
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 {}
@@ -19,6 +19,9 @@ service Attachments {
// Retrieve an upload form that can be used to perform a resumable upload
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
// Retrieve an upload form that can be used to upload a sticker pack
rpc GetStickerUploadForm(GetStickerUploadFormRequest) returns (GetStickerUploadFormResponse) {}
}
message GetUploadFormRequest {
@@ -37,3 +40,19 @@ message GetUploadFormResponse {
errors.FailedPrecondition exceeds_max_upload_length = 2 [(tag.reason) = "oversize_upload"];
}
}
message GetStickerUploadFormRequest {
// The number of stickers in the sticker pack to upload
uint32 sticker_count = 1 [(require.range) = {min: 1, max: 201}];
}
message GetStickerUploadFormResponse {
// A randomly-generated ID for the new sticker pack
string pack_id = 1;
// An upload form clients must use to upload a manifest for the sticker pack
common.S3UploadForm manifest_upload_form = 2;
// Upload forms for individual stickers within the sticker pack
repeated common.S3UploadForm sticker_upload_forms = 3;
}
@@ -183,6 +183,9 @@ service BackupsAnonymous {
//
// On retries, a particular destination media id must not be reused with a
// different source media id or different encryption parameters.
//
// The response stream may be closed with STREAM_CLOSED error reason. In this
// case, a BackupStreamClosed message will be present in the error details.
rpc CopyMedia(CopyMediaRequest) returns (stream CopyMediaResponse) {}
// Retrieve a page of media objects stored for this backup-id. A client may
@@ -194,6 +197,9 @@ service BackupsAnonymous {
// Delete media objects stored with this backup-id. Streams the locations of
// media items back when the item has successfully been removed.
//
// The response stream may be closed with STREAM_CLOSED error reason. In this
// case, a BackupStreamClosed message will be present in the error details.
rpc DeleteMedia(DeleteMediaRequest) returns (stream DeleteMediaResponse) {}
// Delete all backup metadata, objects, and stored public key. To use
@@ -404,7 +410,7 @@ message CopyMediaItem {
// The length of the source attachment before the encryption applied by the
// copy operation
uint32 object_length = 3;
uint64 object_length = 3;
// media_id to copy on to the backup CDN
bytes media_id = 4 [(require.exactlySize) = 15];
@@ -439,20 +445,25 @@ message CopyMediaResponse {
// The media item was successfully copied into the backup
CopySuccess success = 2;
// The source object was not found
SourceNotFound source_not_found = 3 [(tag.reason) = "source_not_found"];
// The provided object length was incorrect
WrongSourceLength wrong_source_length = 4 [(tag.reason) = "wrong_source_length"];
// All media capacity has been consumed. Free some space to continue.
OutOfSpace out_of_space = 5 [(tag.reason) = "out_of_space"];
}
}
// The reason why a media stream RPC is being prematurely closed by the server.
message BackupStreamClosed {
oneof reason {
// The provided backup auth credential presentation could not be
// authenticated. Either, the presentation could not be verified, or
// the public key signature was invalid, or there is no backup associated
// with the backup-id in the presentation.
errors.FailedZkAuthentication failed_authentication = 3 [(tag.reason) = "failed_authentication"];
// The source object was not found
SourceNotFound source_not_found = 4 [(tag.reason) = "source_not_found"];
// The provided object length was incorrect
WrongSourceLength wrong_source_length = 5 [(tag.reason) = "wrong_source_length"];
// All media capacity has been consumed. Free some space to continue.
OutOfSpace out_of_space = 6 [(tag.reason) = "out_of_space"];
errors.FailedZkAuthentication failed_authentication = 1 [(tag.reason) = "failed_authentication"];
}
}
@@ -537,13 +548,5 @@ message DeleteMediaRequest {
}
message DeleteMediaResponse {
oneof response {
DeleteMediaItem deleted_item = 1;
// The provided backup auth credential presentation could not be
// authenticated. Either, the presentation could not be verified, or
// the public key signature was invalid, or there is no backup associated
// with the backup-id in the presentation.
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
}
DeleteMediaItem deleted_item = 1;
}
@@ -115,3 +115,54 @@ message UploadForm {
// The URL to upload to with the appropriate protocol
string signed_upload_location = 4;
}
// An upload location, credentials, and metadata which may be used to upload an
// object to AWS S3
message S3UploadForm {
// The S3 key (i.e. path and filename) for the uploaded file.
string key = 1;
// A scoped credential. Includes the AWS access key, date, region targeted,
// and AWS service.
string credential = 2;
// The type of access control for the uploaded file.
string acl = 3;
// The algorithm used to calculate a signature on the S3 policy.
string algorithm = 4;
// The timestamp (formatted as "yyyyMMdd'T'HHmmssX") at which the S3 policy
// and signature were generated.
string date = 5;
// The S3 policy (as a base64-encoded JSON string) used to upload the file.
string policy = 6;
// A digital signature (formatted as a hex string) on the S3 policy.
string signature = 7;
}
message BadgeSvg {
// File name of the scalable vector graphic for light mode.
string light = 1;
// File name of the scalable vector graphic for dark mode.
string dark = 2;
}
message Badge {
// An ID that uniquely identifies the badge.
string id = 1;
// The category the badge falls in ("donor" or "other").
string category = 2;
// The badge name.
string name = 3;
// The badge description.
string description = 4;
// Different size badge SVG files.
repeated string sprites6 = 5;
// File name of the scalable vector graphic representing this badge.
string svg = 6;
// Pairs of light/dark SVG files designed for display at different sizes.
repeated BadgeSvg svgs = 7;
}
@@ -30,6 +30,10 @@ service Credentials {
// actions.
rpc GetGroupCredentials(GetGroupCredentialsRequest)
returns (GetGroupCredentialsResponse) {}
// Generates zero-knowledge credentials for creating call links.
rpc GetCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest)
returns (GetCreateCallLinkCredentialsResponse) {}
}
// Provides methods for working with previously-generated credentials without
@@ -142,3 +146,18 @@ message GetGroupCredentialsResponse {
// generated
bytes pni = 3;
}
message GetCreateCallLinkCredentialsRequest {
// A zero-knowledge credential request
bytes credential_request = 1;
}
message GetCreateCallLinkCredentialsResponse {
// A zero-knowledge credential that may be redeemed at or up to one day after
// the given redemption time
bytes credential = 1;
// The earliest time, in seconds since the epoch, at which the associated
// credential may be redeemed
uint64 redemption_time_seconds = 2;
}
@@ -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;
}
@@ -43,8 +43,11 @@ service Messages {
// Only the first GetMessagesRequest may contain request parameters that
// configure the stream. The first request must not contain an ack.
//
// The server will keep the stream open until the client disconnects or the
// connection is displaced as indicated by a Terminated response.
// The server will keep the stream open until the client disconnects. Only
// one GetMessages stream may be open per device. If a second GetMessages
// stream is opened, the server may terminate any of the streams with
// a STREAM_CLOSED error reason. A GetMessagesStreamClosed message will be
// present in the error details.
rpc GetMessages(stream GetMessagesRequest) returns (stream GetMessagesResponse) {}
}
@@ -68,19 +71,15 @@ message GetMessagesRequest {
}
}
message GetMessagesResponse {
// The reason why a GetMessages RPC is being closed by the server.
message Terminated {
oneof reason {
// The account's credentials have been updated and the caller must reauthenticate.
google.protobuf.Empty reauthentication_required = 1;
// Another caller has opened a GetMessages stream for the same device.
google.protobuf.Empty conflicting_stream = 2;
}
// The reason why a GetMessages RPC is being closed by the server.
message GetMessagesStreamClosed {
oneof reason {
// Another caller has opened a GetMessages stream for the same device.
google.protobuf.Empty conflicting_stream = 1;
}
}
message GetMessagesResponse {
oneof response {
// A message. On successful receipt of an envelope the caller should ack
// the envelope by sending a GetMessagesRequest with the envelope's server
@@ -92,9 +91,6 @@ message GetMessagesResponse {
// drained and acked by the client. The stream will remain open and continue
// to deliver newly arrived messages.
google.protobuf.Empty queue_empty = 2;
// Indicates that the stream is about to be closed.
Terminated terminated = 3;
}
}
@@ -389,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 {
@@ -122,7 +122,7 @@ message SetProfileResult {
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
optional ProfileAvatarUploadAttributes v1_avatar_upload_form = 15;
optional common.S3UploadForm v1_avatar_upload_form = 15;
// next: 1
}
@@ -268,7 +268,7 @@ message GetUnversionedProfileResult {
// A list of capabilities enabled on the account.
repeated common.DeviceCapability capabilities = 4;
// A list of badges associated with the account.
repeated Badge badges = 5;
repeated common.Badge badges = 5;
}
message GetUnversionedProfileResponse {
@@ -321,47 +321,6 @@ message GetExpiringProfileKeyCredentialAnonymousResponse {
}
}
message ProfileAvatarUploadAttributes {
// The S3 upload path for the profile's avatar.
string path = 1;
// A scoped credential. Includes the AWS access key, date, region targeted, and AWS service.
string credential = 2;
// The type of access control for the avatar object.
string acl = 3;
// The algorithm used to calculate a signature on the S3 policy.
string algorithm = 4;
// The timestamp at which the S3 policy and signature were generated.
string date = 5;
// The S3 policy used to upload the avatar object.
string policy = 6;
// A digital signature on the S3 policy.
bytes signature = 7;
}
message Badge {
// An ID that uniquely identifies the badge.
string id = 1;
// The category the badge falls in ("donor" or "other").
string category = 2;
// The badge name.
string name = 3;
// The badge description.
string description = 4;
// Different size badge SVG files.
repeated string sprites6 = 5;
// File name of the scalable vector graphic representing this badge.
string svg = 6;
// Pairs of light/dark SVG files designed for display at different sizes.
repeated BadgeSvg svgs = 7;
}
message BadgeSvg {
// File name of the scalable vector graphic for light mode.
string light = 1;
// File name of the scalable vector graphic for dark mode.
string dark = 2;
}
enum CredentialType {
CREDENTIAL_TYPE_UNSPECIFIED = 0;
CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY = 1;
@@ -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 {
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more