Compare commits

..
Author SHA1 Message Date
Chris Eager b9a24fedea Move handleAccountCreated() call to outside re-registration 2026-05-19 13:07:44 -05:00
Ravi Khadiwala 9d3b6ebb4a Update to the latest version of the spam filter 2026-05-19 11:30:51 -05:00
Chris Eager 2cf91af5d9 Remove obsolete client public keys table from config 2026-05-19 11:19:19 -05:00
Chris Eager d0e022c23b Remove unused ClosableEpoch 2026-05-19 11:19:19 -05:00
Chris Eager 460e5cb499 Use DynamoDB for change number waiting periods
DynamoDB is even simpler for integration tests.
2026-05-19 11:18:10 -05:00
Jonathan Klabunde Tomer 23305e4460 add a counter for profile version format 2026-05-19 09:15:20 -07:00
Jonathan Klabunde Tomer 06d96a04df store account profile current version as byte array, not hex 2026-05-19 09:15:20 -07:00
Jon Chambers 022f2b874d Bypass circuit breakers, timeouts when clearing Redis instances before test runs 2026-05-19 11:32:09 -04:00
Ravi Khadiwala b09a9b8f39 Add netty dependencies from omnibus 2026-05-18 11:55:59 -05:00
Chris Eager 4e72422cfd Add netty dependencies to POM 2026-05-18 11:53:21 -05:00
Chris Eager d41c73917f Update integration test with post-registration change number waiting period 2026-05-18 11:49:56 -05:00
Chris Eager dd29ee1f27 Refactor Change Number waiting period to dedicated manager
This simplifies integration testing.
2026-05-18 11:49:56 -05:00
Chris Eager 9dc6e049f4 Remove obsolete remote config response 2026-05-18 11:31:20 -05:00
Jon Chambers 7fe3d4a30f Retire oversized message warning metrics 2026-05-18 11:29:54 -05:00
Jon Chambers 88a308fac0 Reduce max message size to 96 KiB 2026-05-18 11:29:54 -05:00
Ravi Khadiwala 34f5351a4c Update to the latest version of the spam filter 2026-05-18 11:29:15 -05:00
Ravi Khadiwala 59f704b6cc Add omnibus H2 server and update to dropwizard 5.0.1 2026-05-18 11:27:17 -05:00
Ravi Khadiwala 0f7d5d7fa4 normalize header combination, special-case user-agent header 2026-05-18 11:25:48 -05:00
Ravi Khadiwala 1ae361b15f Update to the latest version of the spam filter 2026-05-15 12:14:42 -05:00
Ravi Khadiwala 2c9676a1ef Revert omnibus H2 server and dropwizard 5.0.1 2026-05-15 12:13:54 -05:00
Ravi Khadiwala 2ae5c92df2 Update to the latest version of the spam filter 2026-05-15 10:15:23 -05:00
Ravi Khadiwala 3c02f8c3e1 Add documentation to BackupInfo responses 2026-05-15 09:49:40 -05:00
Ravi Khadiwala 4c4282162f Update to dropwizard 5.0.1 2026-05-15 09:44:38 -05:00
Ravi Khadiwala 0beeb8a935 Add h2 omnibus server 2026-05-15 09:44:38 -05:00
Ravi Khadiwala 8d0ad7b085 h2 websocket support 2026-05-15 09:44:38 -05:00
Chris Eager 12e265fb71 Refine Profiles gRPC errors and documentation 2026-05-14 10:55:44 -05:00
Chris Eager 90c27f6969 Add post-registration change number waiting period 2026-05-14 10:55:02 -05:00
Jon Chambers f045e3ee0f Introduce an emergency "read only" mode for messages 2026-05-11 11:43:41 -04:00
Ravi Khadiwala 4485e26562 rename maxUploadSizeInBytes to maxAttachmentUploadSizeInBytes 2026-05-08 13:39:36 -05:00
Ravi Khadiwala 05b7a140fc Add a configuration field for max message backup upload size 2026-05-08 13:18:17 -05:00
Ameya Lokare bde52d775e Update to the latest version of the spam filter 2026-05-07 12:36:51 -07:00
Ravi Khadiwala 59f2f04b7c Handle BackupFailedZkAuthenticationException in grpc SetPublicKey 2026-05-07 11:43:24 -05:00
Chris Eager 305b015784 Update to the latest version of the spam filter 2026-05-06 12:53:24 -05:00
Chris Eager f6ebde8185 Add Profile gRPC services to server 2026-05-06 12:48:58 -05:00
dependabot[bot] 58d4a3b687 Bump aws-actions/configure-aws-credentials
Bumps the minor-actions-dependencies group with 1 update: [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


Updates `aws-actions/configure-aws-credentials` from 6.0.0 to 6.1.0
- [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
- [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/8df5847569e6427dd6c4fb1cf565c83acfa8afa7...ec61189d14ec14c8efccab744f656cffd0e33f37)

---
updated-dependencies:
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 6.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-06 12:48:47 -05:00
Chris Eager 9c6ec78a4e Match profiles V2 test table name in Java and configuration 2026-04-29 19:57:20 -05:00
Chris Eager 1e3b2c8ce8 Profiles gRPC: initial v2 implementation 2026-04-29 10:32:18 -05:00
Katherine Yen 1b11c3efc2 Log when DynamoDB/JSON phone numbers differ 2026-04-29 10:28:27 -05:00
Ravi Khadiwala b441fde213 Enforce key-ids fit in a positive signed 32-bit int 2026-04-29 10:28:15 -05:00
156 changed files with 7614 additions and 2382 deletions

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@8df5847569e6427dd6c4fb1cf565c83acfa8afa7 # v6.0.0
- uses: aws-actions/configure-aws-credentials@ec61189d14ec14c8efccab744f656cffd0e33f37 # v6.1.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
@@ -8,11 +8,11 @@ package org.signal.integration;
import java.time.Clock;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.signal.integration.config.Config;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class IntegrationTools {
@@ -31,6 +32,7 @@ public class IntegrationTools {
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final ChangeNumberWaitingPeriods changeNumberWaitingPeriods;
public static IntegrationTools create(final Config config) {
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
@@ -38,6 +40,9 @@ public class IntegrationTools {
final DynamoDbAsyncClient dynamoDbAsyncClient =
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbAsyncClient, Clock.systemUTC());
@@ -47,17 +52,20 @@ public class IntegrationTools {
return new IntegrationTools(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
new VerificationSessionManager(verificationSessions),
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers())
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers()),
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient)
);
}
private IntegrationTools(
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final VerificationSessionManager verificationSessionManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers) {
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods) {
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.verificationSessionManager = verificationSessionManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
}
public CompletableFuture<Void> populateRecoveryPassword(final String phoneNumber, final byte[] password) {
@@ -71,4 +79,8 @@ public class IntegrationTools {
return verificationSessionManager.findForId(sessionId)
.thenApply(maybeSession -> maybeSession.map(VerificationSession::pushChallenge));
}
public void clearChangeNumberWaitingPeriod(TestUser user) {
changeNumberWaitingPeriods.delete(user.aciUuid());
}
}
@@ -128,6 +128,10 @@ public final class Operations {
return recoveryPassword;
}
public static void clearChangeNumberWaitingPeriod(final TestUser user) {
INTEGRATION_TOOLS.clearChangeNumberWaitingPeriod(user);
}
public static <T> T sendEmptyRequestAuthenticated(
final String endpoint,
final String method,
@@ -9,5 +9,6 @@ import jakarta.validation.constraints.NotBlank;
public record DynamoDbTables(@NotBlank String registrationRecovery,
@NotBlank String verificationSessions,
@NotBlank String phoneNumberIdentifiers) {
@NotBlank String phoneNumberIdentifiers,
@NotBlank String changeNumberWaitingPeriods) {
}
@@ -62,14 +62,20 @@ public class AccountTest {
Map.of(Device.PRIMARY_ID, Operations.generateSignedKEMPreKey(2, pniIdentityKeyPair)),
Map.of(Device.PRIMARY_ID, 17));
final AccountIdentityResponse accountIdentityResponse =
Operations.apiPut("/v2/accounts/number", changeNumberRequest)
.authorized(user)
.executeExpectSuccess(AccountIdentityResponse.class);
try {
Operations.clearChangeNumberWaitingPeriod(user);
assertEquals(user.aciUuid(), accountIdentityResponse.uuid());
assertNotEquals(user.pniUuid(), accountIdentityResponse.pni());
assertEquals(targetNumber, accountIdentityResponse.number());
final AccountIdentityResponse accountIdentityResponse =
Operations.apiPut("/v2/accounts/number", changeNumberRequest)
.authorized(user)
.executeExpectSuccess(AccountIdentityResponse.class);
assertEquals(user.aciUuid(), accountIdentityResponse.uuid());
assertNotEquals(user.pniUuid(), accountIdentityResponse.pni());
assertEquals(targetNumber, accountIdentityResponse.number());
} finally {
Operations.deleteUser(user);
}
}
@Test
+4 -10
View File
@@ -49,7 +49,7 @@
<braintree.version>3.48.0</braintree.version>
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.21.0</commons-io.version>
<dropwizard.version>4.0.16</dropwizard.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
@@ -70,13 +70,13 @@
<kotlin.version>2.3.20</kotlin.version>
<logback.version>1.5.32</logback.version>
<logback-access-common.version>2.0.12</logback-access-common.version>
<lettuce.version>6.8.2.RELEASE</lettuce.version>
<lettuce.version>7.5.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.21</libphonenumber.version>
<logstash.logback.version>8.1</logstash.logback.version>
<log4j-bom.version>2.25.4</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.16.4</micrometer.version>
<netty.version>4.1.127.Final</netty.version>
<netty.version>4.2.13.Final</netty.version>
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
<protoc.version>4.33.2</protoc.version>
@@ -253,12 +253,6 @@
<artifactId>commons-logging</artifactId>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
@@ -361,7 +355,7 @@
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
<artifactId>wiremock-jetty12</artifactId>
<version>3.13.1</version>
<scope>test</scope>
</dependency>
+7 -3
View File
@@ -92,6 +92,8 @@ dynamoDbTables:
tableName: Example_AppleDeviceCheckPublicKeys
backups:
tableName: Example_Backups
changeNumberWaitingPeriods:
tableName: Example_ChangeNumberWaitingPeriods
clientReleases:
tableName: Example_ClientReleases
deletedAccounts:
@@ -125,6 +127,8 @@ dynamoDbTables:
tableName: Example_PhoneNumberIdentifiers
profiles:
tableName: Example_Profiles
profilesV2:
tableName: Example_ProfilesV2
pushChallenge:
tableName: Example_PushChallenge
pushNotificationExperimentSamples:
@@ -144,8 +148,6 @@ dynamoDbTables:
expiration: P7D
subscriptions:
tableName: Example_Subscriptions
clientPublicKeys:
tableName: Example_ClientPublicKeys
verificationSessions:
tableName: Example_VerificationSessions
@@ -232,7 +234,8 @@ messageCache: # Redis server configuration for message store cache
configurationUri: redis://redis.example.com:6379/
attachments:
maxUploadSizeInBytes: 1024
maxAttachmentUploadSizeInBytes: 1024
maxMessageBackupUploadSizeInBytes: 1024
gcpAttachments: # GCP Storage configuration
domain: example.com
@@ -514,6 +517,7 @@ idlePrimaryDeviceReminder:
grpc:
port: 50051
websocketPort: 8080
asnTable:
s3Region: a-region
+46 -4
View File
@@ -23,6 +23,7 @@
<opentelemetry-logback-appender-1.0.version>2.22.0-alpha</opentelemetry-logback-appender-1.0.version>
<storekit.version>4.0.0</storekit.version>
<webauthn4j.version>0.30.2.RELEASE</webauthn4j.version>
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
</properties>
<dependencies>
@@ -137,6 +138,12 @@
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
<scope>test</scope>
<version>${jetty.http2-client.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-validation</artifactId>
@@ -242,15 +249,15 @@
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-jetty-api</artifactId>
<artifactId>jetty-websocket-jetty-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<groupId>org.eclipse.jetty.ee10</groupId>
<artifactId>jetty-ee10-servlets</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-jetty-client</artifactId>
<artifactId>jetty-websocket-jetty-client</artifactId>
<scope>test</scope>
</dependency>
@@ -439,11 +446,46 @@
<artifactId>argparse4j</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-buffer</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-haproxy</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http2</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-common</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-resolver</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-resolver-dns</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ChangeNumberConfiguration;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
@@ -355,6 +356,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private CallQualitySurveyConfiguration callQualitySurvey;
@Valid
@NotNull
@JsonProperty
private ChangeNumberConfiguration changeNumber = new ChangeNumberConfiguration(Duration.ofHours(1));
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -591,4 +597,7 @@ public class WhisperServerConfiguration extends Configuration {
return hlrLookup;
}
public ChangeNumberConfiguration getChangeNumber() {
return changeNumber;
}
}
@@ -31,21 +31,25 @@ import io.lettuce.core.metrics.MicrometerOptions;
import io.lettuce.core.resource.ClientResources;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.resolver.ResolvedAddressTypes;
import io.netty.resolver.dns.DnsNameResolver;
import io.netty.resolver.dns.DnsNameResolverBuilder;
import io.netty.util.Mapping;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletRegistration;
import java.io.ByteArrayInputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
@@ -60,9 +64,9 @@ import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Stream;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry;
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.glassfish.jersey.server.ServerProperties;
import org.signal.i18n.HeaderControlledResourceBundleLookup;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
@@ -135,10 +139,12 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
import org.whispersystems.textsecuregcm.currency.FixerClient;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.filters.ExternalRequestFilter;
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.StripContentLengthOnConnectFilter;
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
@@ -159,10 +165,15 @@ import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
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.ValidatingInterceptor;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.ManagedNioEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
@@ -191,7 +202,7 @@ import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
import org.whispersystems.textsecuregcm.metrics.MetricsHttpEventHandler;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
@@ -224,6 +235,8 @@ import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
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.DynamicConfigurationManager;
@@ -238,6 +251,7 @@ import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
@@ -311,6 +325,7 @@ 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> {
@@ -469,8 +484,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getClientReleases().getTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
config.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfiles().getTableName());
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
@@ -613,10 +629,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ScheduledExecutorService cloudflareTurnRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "cloudflareTurnRetry").threads(1).build();
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
ScheduledExecutorService jmxDumper = ScheduledExecutorServiceBuilder.of(environment, "jmxDumper").threads(1).build();
final ManagedNioEventLoopGroup dnsResolutionEventLoopGroup = new ManagedNioEventLoopGroup();
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.next())
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.getEventLoopGroup().next())
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
.completeOncePreferredResolved(false)
.channelType(NioDatagramChannel.class)
@@ -678,7 +693,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
disconnectionRequestListenerExecutor, retryExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock, experimentEnrollmentManager);
@@ -692,11 +707,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
@@ -739,7 +758,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager, dynamicConfigurationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
config.getTurnConfiguration().cloudflare().apiToken().value(),
@@ -968,11 +987,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxUploadSizeInBytes()))
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()))
.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!
@@ -989,9 +1009,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new PaymentsGrpcService(currencyManager),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
@@ -1007,24 +1028,38 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
prohibitAuthenticationInterceptor))
.toList();
final ServerBuilder<?> serverBuilder =
NettyServerBuilder.forAddress(new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()));
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
final LocalAddress grpcLocalAddress = new LocalAddress("grpc");
final ServerBuilder<?> serverBuilder = NettyServerBuilder
.forAddress(grpcLocalAddress)
.channelType(LocalServerChannel.class)
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup());
authenticatedServices.forEach(serverBuilder::addService);
unauthenticatedServices.forEach(serverBuilder::addService);
final ManagedGrpcServer exposedGrpcServer = new ManagedGrpcServer(serverBuilder.build());
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
environment.lifecycle().manage(exposedGrpcServer);
final SocketAddress websocketAddress =
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
final OmnibusRouter omnibusRouter = new OmnibusRouter(List.of(
new OmnibusRouter.OmnibusRoute("/v1/websocket", websocketAddress),
new OmnibusRouter.OmnibusRoute("/v1/provisioning", websocketAddress)),
grpcLocalAddress);
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
? null
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(), config.getTlsKeyStoreConfiguration().password().value());
final OmnibusH2Server omnibusH2Server = new OmnibusH2Server(
sniMapping,
omnibusNioEventLoopGroup.getEventLoopGroup(),
omnibusLocalEventLoopGroup.getEventLoopGroup(),
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
config.getGrpc().idleTimeout());
final List<Filter> filters = new ArrayList<>();
filters.add(remoteDeprecationFilter);
filters.add(new RemoteAddressFilter());
filters.add(new TimestampResponseFilter());
for (Filter filter : filters) {
environment.servlets()
.addFilter(filter.getClass().getSimpleName(), filter)
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
environment.lifecycle().manage(omnibusLocalEventLoopGroup);
environment.lifecycle().manage(omnibusNioEventLoopGroup);
environment.lifecycle().manage(localGrpcServer);
environment.lifecycle().manage(omnibusH2Server);
if (!config.getExternalRequestFilterConfiguration().paths().isEmpty()) {
environment.servlets().addFilter(ExternalRequestFilter.class.getSimpleName(),
@@ -1042,9 +1077,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final String websocketServletPath = "/v1/websocket/";
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
final MetricsHttpChannelListener metricsHttpChannelListener = new MetricsHttpChannelListener(clientReleaseManager,
Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
metricsHttpChannelListener.configure(environment);
MetricsHttpEventHandler.configure(environment, Metrics.globalRegistry, clientReleaseManager, Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
final MessageMetrics messageMetrics = new MessageMetrics();
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
@@ -1090,15 +1123,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters, Clock.systemUTC());
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
changeNumberWaitingPeriodManager, Clock.systemUTC());
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
usernameHashZkProofVerifier),
new AccountControllerV2(accountsManager, changeNumberManager),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager, config.getAttachments().maxUploadSizeInBytes()),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
experimentEnrollmentManager, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CallQualitySurveyController(callQualitySurveyManager),
@@ -1127,7 +1161,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters, registrationFraudChecker),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig()),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
@@ -1167,36 +1201,36 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
webSocketEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
provisioningEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (context, container) -> {
final WebSocketExtensionRegistry extensionRegistry = WebSocketServerComponents
.getWebSocketComponents(environment.getApplicationContext().getServletContext())
.getExtensionRegistry();
if (config.getWebSocketConfiguration().isDisablePerMessageDeflate()) {
extensionRegistry.unregister("permessage-deflate");
} else if (config.getWebSocketConfiguration().isDisableCrossMessageOutgoingCompression()) {
extensionRegistry.unregister("permessage-deflate");
extensionRegistry.register("permessage-deflate", NoContextTakeoverPerMessageDeflateExtension.class);
}
});
WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet = new WebSocketResourceProviderFactory<>(
webSocketEnvironment, AuthenticatedDevice.class, config.getWebSocketConfiguration(),
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
webSocketEnvironment, AuthenticatedDevice.class, RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
WebSocketResourceProviderFactory<AuthenticatedDevice> provisioningServlet = new WebSocketResourceProviderFactory<>(
provisioningEnvironment, AuthenticatedDevice.class, config.getWebSocketConfiguration(),
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
provisioningEnvironment, AuthenticatedDevice.class, RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
ServletRegistration.Dynamic websocket = environment.servlets().addServlet("WebSocket", webSocketServlet);
ServletRegistration.Dynamic provisioning = environment.servlets().addServlet("Provisioning", provisioningServlet);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(),
(servletContext, container) -> {
container.addMapping(websocketServletPath, webSocketServlet);
container.addMapping(provisioningWebsocketServletPath, provisioningServlet);
websocket.addMapping(websocketServletPath);
websocket.setAsyncSupported(true);
PriorityFilter.ensureFilter(servletContext, new StripContentLengthOnConnectFilter());
PriorityFilter.ensureFilter(servletContext, new TimestampResponseFilter());
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
PriorityFilter.ensureFilter(servletContext, remoteDeprecationFilter);
provisioning.addMapping(provisioningWebsocketServletPath);
provisioning.setAsyncSupported(true);
container.setMaxBinaryMessageSize(config.getWebSocketConfiguration().getMaxBinaryMessageSize());
container.setMaxTextMessageSize(config.getWebSocketConfiguration().getMaxTextMessageSize());
final WebSocketExtensionRegistry extensionRegistry = WebSocketServerComponents
.getWebSocketComponents(environment.getApplicationContext())
.getExtensionRegistry();
if (config.getWebSocketConfiguration().isDisablePerMessageDeflate()) {
extensionRegistry.unregister("permessage-deflate");
} else if (config.getWebSocketConfiguration().isDisableCrossMessageOutgoingCompression()) {
extensionRegistry.unregister("permessage-deflate");
extensionRegistry.register("permessage-deflate", NoContextTakeoverPerMessageDeflateExtension.class);
}
});
environment.admin().addTask(new SetRequestLoggingEnabledTask());
}
private void registerExceptionMappers(Environment environment,
@@ -10,10 +10,9 @@ 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.Optional;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
import org.eclipse.jetty.ee10.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.ee10.websocket.server.JettyServerUpgradeResponse;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
@@ -6,5 +6,7 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.Positive;
public record AttachmentsConfiguration(@Positive long maxUploadSizeInBytes) {
public record AttachmentsConfiguration(
@Positive long maxAttachmentUploadSizeInBytes,
@Positive long maxMessageBackupUploadSizeInBytes) {
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.time.Duration;
public record ChangeNumberConfiguration(Duration postRegistrationWaitingPeriod) {
}
@@ -49,9 +49,9 @@ public class DynamoDbTables {
private final AccountsTableConfiguration accounts;
private final Table appleDeviceChecks;
private final Table changeNumberWaitingPeriods;
private final Table appleDeviceCheckPublicKeys;
private final Table backups;
private final Table clientPublicKeys;
private final Table clientReleases;
private final Table deletedAccounts;
private final Table deletedAccountsLock;
@@ -64,6 +64,7 @@ public class DynamoDbTables {
private final TableWithExpiration onetimeDonations;
private final Table phoneNumberIdentifiers;
private final Table profiles;
private final Table profilesV2;
private final Table pushChallenge;
private final Table pushNotificationExperimentSamples;
private final TableWithExpiration redeemedReceipts;
@@ -77,9 +78,9 @@ public class DynamoDbTables {
public DynamoDbTables(
@JsonProperty("accounts") final AccountsTableConfiguration accounts,
@JsonProperty("appleDeviceChecks") final Table appleDeviceChecks,
@JsonProperty("changeNumberWaitingPeriods") final Table changeNumberWaitingPeriods,
@JsonProperty("appleDeviceCheckPublicKeys") final Table appleDeviceCheckPublicKeys,
@JsonProperty("backups") final Table backups,
@JsonProperty("clientPublicKeys") final Table clientPublicKeys,
@JsonProperty("clientReleases") final Table clientReleases,
@JsonProperty("deletedAccounts") final Table deletedAccounts,
@JsonProperty("deletedAccountsLock") final Table deletedAccountsLock,
@@ -92,6 +93,7 @@ public class DynamoDbTables {
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@JsonProperty("profiles") final Table profiles,
@JsonProperty("profilesV2") final Table profilesV2,
@JsonProperty("pushChallenge") final Table pushChallenge,
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
@@ -104,9 +106,9 @@ public class DynamoDbTables {
this.accounts = accounts;
this.appleDeviceChecks = appleDeviceChecks;
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
this.appleDeviceCheckPublicKeys = appleDeviceCheckPublicKeys;
this.backups = backups;
this.clientPublicKeys = clientPublicKeys;
this.clientReleases = clientReleases;
this.deletedAccounts = deletedAccounts;
this.deletedAccountsLock = deletedAccountsLock;
@@ -119,6 +121,7 @@ public class DynamoDbTables {
this.onetimeDonations = onetimeDonations;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profiles = profiles;
this.profilesV2 = profilesV2;
this.pushChallenge = pushChallenge;
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
this.redeemedReceipts = redeemedReceipts;
@@ -142,6 +145,12 @@ public class DynamoDbTables {
return appleDeviceChecks;
}
@NotNull
@Valid
public Table getChangeNumberWaitingPeriods() {
return changeNumberWaitingPeriods;
}
@NotNull
@Valid
public Table getAppleDeviceCheckPublicKeys() {
@@ -154,12 +163,6 @@ public class DynamoDbTables {
return backups;
}
@NotNull
@Valid
public Table getClientPublicKeys() {
return clientPublicKeys;
}
@NotNull
@Valid
public Table getClientReleases() {
@@ -228,10 +231,16 @@ public class DynamoDbTables {
@NotNull
@Valid
public Table getProfiles() {
public Table getProfilesV1() {
return profiles;
}
@NotNull
@Valid
public Table getProfilesV2() {
return profilesV2;
}
@NotNull
@Valid
public Table getPushChallenge() {
@@ -5,11 +5,33 @@
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
/// Configuration for the gRPC Server
///
/// @param bindAddress The host to bind the omnibus server to
/// @param port The port to bind the omnibus server to
/// @param websocketAddress The address of a listening websocket server for handling legacy requests
/// @param websocketPort The port of a listening websocket server for handling legacy requests
/// @param idleTimeout The duration after which an idle connection may be disconnected
/// @param h2c If true, listen for plaintext h2c with prior-knowledge
public record GrpcConfiguration(
@NotNull String bindAddress,
@NotNull Integer port,
@NotNull String websocketAddress,
@NotNull Integer websocketPort,
@NotNull Duration idleTimeout,
boolean h2c) {
public record GrpcConfiguration(@NotNull String bindAddress, @NotNull Integer port) {
public GrpcConfiguration {
if (bindAddress == null || bindAddress.isEmpty()) {
bindAddress = "localhost";
}
if (websocketAddress == null || websocketAddress.isEmpty()) {
websocketAddress = "localhost";
}
if (idleTimeout == null) {
idleTimeout = Duration.ofMinutes(5);
}
}
}
@@ -7,6 +7,9 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.annotation.Nullable;
public record TlsKeyStoreConfiguration(@NotNull SecretString password) {
public record TlsKeyStoreConfiguration(
@Nullable String path,
@NotNull SecretString password) {
}
@@ -12,7 +12,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.signal.chat.calling.GetTurnCredentialsResponseOrBuilder;
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
public class DynamicConfiguration {
@@ -45,6 +44,10 @@ public class DynamicConfiguration {
@Valid
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
@JsonProperty
@Valid
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
@JsonProperty
@Valid
DynamicRegistrationConfiguration registrationConfiguration = new DynamicRegistrationConfiguration(false);
@@ -111,6 +114,10 @@ public class DynamicConfiguration {
return messagePersister;
}
public DynamicMessageDeliveryConfiguration getMessageDeliveryConfiguration() {
return messageDelivery;
}
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
return registrationConfiguration;
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
public class DynamicMessageDeliveryConfiguration {
@JsonProperty
private boolean readOnly = false;
public boolean isReadOnly() {
return readOnly;
}
}
@@ -22,6 +22,7 @@ import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.ServiceUnavailableException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
@@ -75,7 +76,7 @@ public class AccountControllerV2 {
@ApiResponse(responseCode = "423", content = @Content(schema = @Schema(implementation = RegistrationLockFailure.class)))
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final ChangeNumberRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
@@ -121,6 +122,8 @@ public class AccountControllerV2 {
throw new BadRequestException(e);
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
} catch (final MessageDeliveryNotAllowedException e) {
throw new ServiceUnavailableException();
}
}
@@ -103,19 +103,22 @@ public class ArchiveController {
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
private final long maxAttachmentSize;
private final long maxMessageBackupSize;
public ArchiveController(
final AccountsManager accountsManager,
final BackupAuthManager backupAuthManager,
final BackupManager backupManager,
final BackupMetrics backupMetrics,
final long maxAttachmentSize) {
final long maxAttachmentSize,
final long maxMessageBackupSize) {
this.accountsManager = accountsManager;
this.backupAuthManager = backupAuthManager;
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
this.maxAttachmentSize = maxAttachmentSize;
this.maxMessageBackupSize = maxMessageBackupSize;
}
public record SetBackupIdRequest(
@@ -602,7 +605,7 @@ public class ArchiveController {
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final boolean oversize = uploadLength
.map(length -> length > maxAttachmentSize)
.map(length -> length > maxMessageBackupSize)
.orElse(false);
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
@@ -610,7 +613,7 @@ public class ArchiveController {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
final BackupUploadDescriptor uploadDescriptor =
backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength.orElse(maxAttachmentSize));
backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength.orElse(maxMessageBackupSize));
return new UploadDescriptorResponse(
uploadDescriptor.cdn(),
uploadDescriptor.key(),
@@ -33,6 +33,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.ServiceUnavailableException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
@@ -471,6 +472,8 @@ public class MessageController {
}
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
} catch (final MessageDeliveryNotAllowedException e) {
throw new ServiceUnavailableException();
}
}
@@ -724,6 +727,8 @@ public class MessageController {
.type(MediaType.APPLICATION_JSON)
.entity(accountStaleDevices)
.build());
} catch (final MessageDeliveryNotAllowedException e) {
throw new ServiceUnavailableException();
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class MessageDeliveryNotAllowedException extends NoStackTraceException {
}
@@ -62,6 +62,8 @@ import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -94,7 +96,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
@@ -172,33 +174,28 @@ public class ProfileController {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Optional<VersionedProfile> currentProfile =
profilesManager.get(auth.accountIdentifier(), request.version());
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
final Optional<VersionedProfileV1> currentProfile =
profilesManager.getV1(auth.accountIdentifier(), request.version());
if (request.paymentAddress() != null && request.paymentAddress().length != 0) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
if (hasDisallowedPrefix && currentProfile.map(VersionedProfileV1::paymentAddress).isEmpty()) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
Optional<String> currentAvatar = Optional.empty();
if (currentProfile.isPresent() && currentProfile.get().avatar() != null && currentProfile.get().avatar()
.startsWith("profiles/")) {
currentAvatar = Optional.of(currentProfile.get().avatar());
}
final Optional<String> currentAvatar = ProfileHelper.getCurrentAvatar(currentProfile);
final String avatar = ProfileHelper.getAvatar(request.getAvatarChange(), currentAvatar);
final String avatar = switch (request.getAvatarChange()) {
case UNCHANGED -> currentAvatar.orElse(null);
case CLEAR -> null;
case UPDATE -> ProfileHelper.generateAvatarObjectName();
};
profilesManager.set(auth.accountIdentifier(),
new VersionedProfile(
profilesManager.setV1(auth.accountIdentifier(),
new VersionedProfileV1(
request.version(),
request.name(),
avatar,
@@ -219,7 +216,7 @@ public class ProfileController {
.orElseGet(a::getBadges);
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.version());
a.setCurrentProfileVersion(HexFormat.of().parseHex(request.version()));
});
if (request.getAvatarChange() == CreateProfileRequest.AvatarChange.UPDATE) {
@@ -439,14 +436,15 @@ public class ProfileController {
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
if (account.getCurrentProfileVersion().map(version::equals).orElse(false)) {
expiringProfileKeyCredentialResponse = profilesManager.get(account.getUuid(), version)
if (account.getCurrentProfileVersion().map(v -> HexFormat.of().formatHex(v).equals(version)).orElse(false)) {
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
HexFormat.of().parseHex(encodedCredentialRequest),
profile, new ServiceId.Aci(account.getUuid()), zkProfileOperations);
new ProfileKeyCredentialRequest(HexFormat.of().parseHex(encodedCredentialRequest)),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getUuid()),
zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw new BadRequestException(e);
}
@@ -468,7 +466,7 @@ public class ProfileController {
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getUuid(), version);
if (maybeProfile.isEmpty()) {
// this can happen if an account re-registers, which includes some device-transfer scenarios
@@ -481,17 +479,17 @@ public class ProfileController {
.increment();
}
final byte[] name = maybeProfile.map(VersionedProfile::name).orElse(null);
final byte[] about = maybeProfile.map(VersionedProfile::about).orElse(null);
final byte[] aboutEmoji = maybeProfile.map(VersionedProfile::aboutEmoji).orElse(null);
final String avatar = maybeProfile.map(VersionedProfile::avatar).orElse(null);
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfile::phoneNumberSharing).orElse(null);
final byte[] name = maybeProfile.map(VersionedProfileV1::name).orElse(null);
final byte[] about = maybeProfile.map(VersionedProfileV1::about).orElse(null);
final byte[] aboutEmoji = maybeProfile.map(VersionedProfileV1::aboutEmoji).orElse(null);
final String avatar = maybeProfile.map(VersionedProfileV1::avatar).orElse(null);
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfileV1::phoneNumberSharing).orElse(null);
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
final byte[] paymentAddress = maybeProfile
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(version)).orElse(true))
.map(VersionedProfile::paymentAddress)
.filter(p -> account.getCurrentProfileVersion().map(v -> HexFormat.of().formatHex(v).equals(p.version())).orElse(true))
.map(VersionedProfileV1::paymentAddress)
.orElse(null);
return new VersionedProfileResponse(
@@ -26,13 +26,10 @@ import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.Arrays;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -61,9 +58,7 @@ public class RemoteConfigController {
.map(p -> p.name().toLowerCase())
.collect(Collectors.toSet());
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager,
Map<String, String> globalConfig,
final Clock clock) {
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager, Map<String, String> globalConfig) {
this.remoteConfigsManager = remoteConfigsManager;
this.globalConfig = globalConfig;
}
@@ -1,45 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.time.Instant;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.util.InstantAdapter;
public class UserRemoteConfigList {
@JsonProperty
@Schema(description = "List of remote configurations applicable to the user")
private List<UserRemoteConfig> config;
@JsonProperty
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
@Schema(description = """
Timestamp when the configuration was generated. Deprecated in favor of `X-Signal-Timestamp` response header.
""", deprecated = true)
@Deprecated
private Instant serverEpochTime;
public UserRemoteConfigList() {}
public UserRemoteConfigList(List<UserRemoteConfig> config, Instant serverEpochTime) {
this.config = config;
this.serverEpochTime = serverEpochTime;
}
public List<UserRemoteConfig> getConfig() {
return config;
}
public Instant getServerEpochTime() {
return serverEpochTime;
}
}
@@ -0,0 +1,82 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.filters;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletContext;
import java.util.EnumSet;
import java.util.Objects;
import org.eclipse.jetty.ee10.servlet.FilterHolder;
import org.eclipse.jetty.ee10.servlet.FilterMapping;
import org.eclipse.jetty.ee10.servlet.ServletContextHandler;
import org.eclipse.jetty.ee10.servlet.ServletHandler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.component.LifeCycle;
public class PriorityFilter {
private PriorityFilter() {}
private static FilterHolder getFilter(ServletContext servletContext, final Class<? extends Filter> filterClass) {
final ContextHandler contextHandler = Objects.requireNonNull(ServletContextHandler.getServletContextHandler(servletContext));
final ServletHandler servletHandler = contextHandler.getDescendant(ServletHandler.class);
return servletHandler.getFilter(filterClass.getName());
}
/**
* Ensure a filter is available on the provided ServletContext, a new filter will added if one does not already
* exist.
* <p>
* If a new filter is added, it will be added before all other filters.
* <p>
* Modeled after {@link org.eclipse.jetty.ee10.websocket.servlet.WebSocketUpgradeFilter#ensureFilter(ServletContext)},
* since its use of {@link org.eclipse.jetty.ee10.servlet.ServletHandler#prependFilter(FilterHolder)} is what makes
* this necessary.
*/
public static void ensureFilter(final ServletContext servletContext, final Filter filter) {
FilterHolder existingFilter = getFilter(servletContext, filter.getClass());
if (existingFilter != null) {
return;
}
final ContextHandler contextHandler = ServletContextHandler.getServletContextHandler(servletContext);
final ServletHandler servletHandler = contextHandler.getDescendant(ServletHandler.class);
final String pathSpec = "/*";
final FilterHolder holder = new FilterHolder(filter);
holder.setName(filter.getClass().getName());
holder.setAsyncSupported(true);
final FilterMapping mapping = new FilterMapping();
mapping.setFilterName(holder.getName());
mapping.setPathSpec(pathSpec);
mapping.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST));
// Add as the first filter in the list.
servletHandler.prependFilter(holder);
servletHandler.prependFilterMapping(mapping);
// If we create the filter we must also make sure it is removed if the context is stopped.
contextHandler.addEventListener(new LifeCycle.Listener()
{
@Override
public void lifeCycleStopping(LifeCycle event)
{
servletHandler.removeFilterHolder(holder);
servletHandler.removeFilterMapping(mapping);
contextHandler.removeEventListener(this);
}
@Override
public String toString()
{
return String.format("%sCleanupListener", filter.getClass().getSimpleName());
}
});
}
}
@@ -26,10 +26,6 @@ public class RemoteAddressFilter implements Filter {
public static final String REMOTE_ADDRESS_ATTRIBUTE_NAME = RemoteAddressFilter.class.getName() + ".remoteAddress";
private static final Logger logger = LoggerFactory.getLogger(RemoteAddressFilter.class);
public RemoteAddressFilter() {
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws ServletException, IOException {
@@ -0,0 +1,71 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.filters;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.eclipse.jetty.ee10.servlet.ServletContextRequest;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.server.HttpStream;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.Callback;
/// Our current version of jetty (12.1.5) has a bug where it includes content-length:0 on
/// CONNECT websocket upgrade requests. Providing an HTTP/2 header frame with a
/// content-length that does not match the sum of the lengths of the data frames is technically
/// a malformed HTTP/2 stream and our netty-based reverse proxy implementation rejects it. This
/// filter strips out the superfluous content-length at stream-send time. It can be removed once
/// we update to a jetty version that fixes [jetty/jetty.project#15074](https://github.com/jetty/jetty.project/issues/15074)
public class StripContentLengthOnConnectFilter implements Filter {
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest hsr &&
HttpVersion.HTTP_2.is(hsr.getProtocol()) &&
HttpMethod.CONNECT.is(hsr.getMethod())) {
final Request coreRequest = ServletContextRequest.getServletContextRequest(hsr);
if (coreRequest != null) {
coreRequest.addHttpStreamWrapper(StripContentLengthStream::new);
}
}
chain.doFilter(request, response);
}
private static class StripContentLengthStream extends HttpStream.Wrapper {
StripContentLengthStream(final HttpStream wrapped) {
super(wrapped);
}
@Override
public void send(MetaData.Request request, MetaData.Response response, boolean last, ByteBuffer content,
Callback callback) {
if (response != null && response.getStatus() == 200 && response.getHttpFields()
.contains(HttpHeader.CONTENT_LENGTH)) {
final HttpFields fieldsWithoutContentLengthHeader =
HttpFields.build(response.getHttpFields()).remove(HttpHeader.CONTENT_LENGTH);
response = new MetaData.Response(
response.getStatus(),
response.getReason(),
response.getHttpVersion(),
fieldsWithoutContentLengthHeader,
-1,
response.getTrailersSupplier());
}
super.send(request, response, last, content, callback);
}
}
}
@@ -9,7 +9,7 @@ import io.grpc.Status;
import org.whispersystems.textsecuregcm.entities.AvatarChange;
public class AvatarChangeUtil {
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileRequest.AvatarChange avatarChangeType) {
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileV1Request.AvatarChange avatarChangeType) {
return switch (avatarChangeType) {
case AVATAR_CHANGE_UNCHANGED -> AvatarChange.AVATAR_CHANGE_UNCHANGED;
case AVATAR_CHANGE_CLEAR -> AvatarChange.AVATAR_CHANGE_CLEAR;
@@ -62,11 +62,13 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
private final long maxAttachmentSize;
private final long maxMessageBackupSize;
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics, final long maxAttachmentSize) {
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics, final long maxAttachmentSize, final long maxMessageBackupSize) {
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
this.maxAttachmentSize = maxAttachmentSize;
this.maxMessageBackupSize = maxMessageBackupSize;
}
@Override
@@ -157,16 +159,19 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
@Override
public SetPublicKeyResponse setPublicKey(final SetPublicKeyRequest request)
throws BackupFailedZkAuthenticationException {
public SetPublicKeyResponse setPublicKey(final SetPublicKeyRequest request) {
final ECPublicKey publicKey = deserialize(ECPublicKey::new, request.getPublicKey().toByteArray());
final BackupAuthCredentialPresentation presentation = deserialize(
BackupAuthCredentialPresentation::new,
request.getSignedPresentation().getPresentation().toByteArray());
final byte[] signature = request.getSignedPresentation().getPresentationSignature().toByteArray();
backupManager.setPublicKey(presentation, signature, publicKey);
return SetPublicKeyResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
try {
backupManager.setPublicKey(presentation, signature, publicKey);
return SetPublicKeyResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (BackupFailedZkAuthenticationException e) {
return SetPublicKeyResponse.newBuilder().setFailedAuthentication(FailedZkAuthentication.getDefaultInstance()).build();
}
}
@@ -182,18 +187,21 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.build();
}
final long uploadLength = request.getUploadLength();
if (uploadLength > maxAttachmentSize) {
if (request.getUploadTypeCase() == GetUploadFormRequest.UploadTypeCase.MESSAGES) {
backupMetrics.updateMessageBackupSizeDistribution(backupUser, true, Optional.of(uploadLength));
final boolean oversize = switch (request.getUploadTypeCase()) {
case MEDIA -> uploadLength > maxAttachmentSize;
case MESSAGES -> {
backupMetrics.updateMessageBackupSizeDistribution(backupUser, uploadLength > maxMessageBackupSize, Optional.of(uploadLength));
yield uploadLength > maxMessageBackupSize;
}
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
};
if (oversize) {
return GetUploadFormResponse.newBuilder().setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance()).build();
}
final BackupUploadDescriptor uploadDescriptor = switch (request.getUploadTypeCase()) {
case MESSAGES -> {
backupMetrics.updateMessageBackupSizeDistribution(backupUser, false, Optional.of(uploadLength));
yield backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength);
}
case MESSAGES -> backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength);
case MEDIA -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, uploadLength);
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
};
@@ -18,6 +18,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -29,6 +30,7 @@ public class DeviceCapabilityUtil {
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
};
}
}
@@ -158,6 +158,10 @@ public class GrpcExceptions {
return StatusProto.toStatusRuntimeException(builder.build());
}
public static StatusRuntimeException unavailable() {
return unavailable(null);
}
/// There was an internal error processing the RPC. The client should retry the request with exponential backoff.
///
/// @return A [StatusRuntimeException] encoding the error
@@ -11,6 +11,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.protobuf.Empty;
import io.grpc.Status;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
@@ -28,6 +29,7 @@ import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -229,6 +231,8 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
.build();
} catch (final MessageTooLargeException e) {
throw GrpcExceptions.invalidArguments("message too large");
} catch (final MessageDeliveryNotAllowedException e) {
throw GrpcExceptions.unavailable();
}
}
@@ -325,6 +329,8 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
return SendMultiRecipientMessageResponse.newBuilder()
.setMismatchedDevices(mismatchedDevicesBuilder)
.build();
} catch (final MessageDeliveryNotAllowedException e) {
throw GrpcExceptions.unavailable();
}
}
@@ -5,21 +5,24 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.MessagesGrpcHelper.buildMismatchedDevices;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.protobuf.Empty;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.SendSyncMessageRequest;
import org.signal.chat.messages.SimpleMessagesGrpc;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -36,8 +39,6 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import static org.whispersystems.textsecuregcm.grpc.MessagesGrpcHelper.buildMismatchedDevices;
public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final AccountsManager accountsManager;
@@ -192,6 +193,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
.build();
} catch (final MessageTooLargeException e) {
throw GrpcExceptions.invalidArguments("message too large");
} catch (final MessageDeliveryNotAllowedException e) {
throw GrpcExceptions.unavailable();
}
}
@@ -5,16 +5,18 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import io.grpc.StatusException;
import java.time.Clock;
import java.util.Optional;
import com.google.common.annotations.VisibleForTesting;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
@@ -38,77 +40,116 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerSecretParams serverSecretParams) {
this(accountsManager,
profilesManager,
profileBadgeConverter,
new ServerZkProfileOperations(serverSecretParams),
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
}
@VisibleForTesting
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerZkProfileOperations zkProfileOperations,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.profileBadgeConverter = profileBadgeConverter;
this.zkProfileOperations = new ServerZkProfileOperations(serverSecretParams);
this.groupSendTokenUtil = new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC());
this.zkProfileOperations = zkProfileOperations;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) throws StatusException {
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
throw Status.UNAUTHENTICATED.asException();
throw GrpcExceptions.invalidArguments("aci service identifier type required");
}
final Account account = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> {
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier)) {
throw Status.UNAUTHENTICATED.asException();
}
yield accountsManager.getByServiceIdentifier(targetIdentifier)
.orElseThrow(Status.NOT_FOUND::asException);
}
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
final boolean authorized = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
case UNIDENTIFIED_ACCESS_KEY ->
getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
default -> throw Status.INVALID_ARGUMENT.asException();
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
.orElse(false);
default -> throw GrpcExceptions.constraintViolation("invalid authentication");
};
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
null,
account,
profileBadgeConverter);
if (!authorized) {
return GetUnversionedProfileAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return targetAccount.map(account ->
GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
null,
account,
profileBadgeConverter))
.build())
.orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) throws StatusException {
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
final Account targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getVersionedProfile(targetAccount, profilesManager, request.getRequest().getVersion());
return targetAccount.flatMap(account ->
ProfileGrpcHelper.getVersionedProfile(account,
profilesManager,
request.getRequest().getVersion().toByteArray(),
request.getRequest().getDataEtag().toByteArray(),
request.getRequest().getPaymentAddressEtag().toByteArray()))
.map(result ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) throws StatusException {
public GetExpiringProfileKeyCredentialAnonymousResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
throw GrpcExceptions.constraintViolation("invalid credential type");
}
final Account account = getTargetAccountAndValidateUnidentifiedAccess(
final Optional<Account> maybeAccount = getTargetAccountAndValidateUnidentifiedAccess(
targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(account.getUuid(),
request.getRequest().getVersion(), request.getRequest().getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
return maybeAccount.map(account ->
ProfileGrpcHelper.getExpiringProfileKeyCredentialResult(account,
request.getRequest().getVersion().toByteArray(), request.getRequest().getCredentialRequest().toByteArray(),
profilesManager, zkProfileOperations)
.map(result -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
private Account getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) throws StatusException {
private Optional<Account> getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) {
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey))
.orElseThrow(Status.UNAUTHENTICATED::asException);
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
}
}
@@ -7,21 +7,27 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import io.grpc.StatusException;
import org.signal.chat.profile.Badge;
import org.signal.chat.profile.BadgeSvg;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -30,32 +36,88 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcHelper {
static GetVersionedProfileResponse getVersionedProfile(final Account account,
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
final ProfilesManager profilesManager,
final String requestVersion) throws StatusException {
final byte[] requestVersion,
final byte[] requestDataEtag,
final byte[] requestPaymentAddressEtag) {
final VersionedProfile profile = profilesManager.get(account.getUuid(), requestVersion)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
final GetVersionedProfileResponse.Builder responseBuilder = GetVersionedProfileResponse.newBuilder();
responseBuilder
.setName(ByteString.copyFrom(profile.name()))
.setAbout(ByteString.copyFrom(profile.about()))
.setAboutEmoji(ByteString.copyFrom(profile.aboutEmoji()))
.setAvatar(profile.avatar())
.setPhoneNumberSharing(ByteString.copyFrom(profile.phoneNumberSharing()));
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
if (account.getCurrentProfileVersion().map(v -> v.equals(requestVersion)).orElse(true)) {
responseBuilder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
final Optional<VersionedProfile> profile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
profile = profilesManager.get(account.getUuid(), requestVersion);
} else {
profile = Optional.empty();
}
return responseBuilder.build();
final Optional<VersionedProfileV1> v1Profile;
if (profile.isEmpty()) {
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
} else {
v1Profile = Optional.empty();
}
if (profile.isEmpty() && v1Profile.isEmpty()) {
return Optional.empty();
}
final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder();
profile.ifPresent(p -> {
if (requestDataEtag.length > 0 && Arrays.equals(requestDataEtag, p.dataHash())) {
responseBuilder.setDataEtagMatched(true);
} else {
responseBuilder.setDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(p.data()))
.setEtagSha256(ByteString.copyFrom(p.dataHash()))
.build());
}
});
v1Profile.ifPresent(p -> {
final GetVersionedProfileV1Response.Builder v1ResponseBuilder = GetVersionedProfileV1Response.newBuilder();
v1ResponseBuilder
.setName(ByteString.copyFrom(p.name()))
.setAbout(ByteString.copyFrom(p.about()))
.setAboutEmoji(ByteString.copyFrom(p.aboutEmoji()))
.setPhoneNumberSharing(ByteString.copyFrom(p.phoneNumberSharing()));
if (p.avatar() != null) {
v1ResponseBuilder.setAvatar(p.avatar());
}
responseBuilder.setV1Response(v1ResponseBuilder);
});
// Include payment address if the version matches the latest version on Account or the latest version on Account
// is empty
if (account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
final Optional<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
if (paymentAddress.isPresent()) {
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
profile.map(VersionedProfile::paymentAddressHash)
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
.orElse(false);
if (paymentAddressETagMatches) {
responseBuilder.setPaymentAddressEtagMatched(true);
} else {
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress.get()))
.setEtagSha256(ByteString.copyFrom(
profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get()))))
.build());
}
}
}
return Optional.of(responseBuilder.build());
}
@VisibleForTesting
@@ -95,54 +157,79 @@ public class ProfileGrpcHelper {
return grpcBadgeSvgs;
}
static GetUnversionedProfileResponse buildUnversionedProfileResponse(
static GetUnversionedProfileResult buildUnversionedProfileResult(
final ServiceIdentifier targetIdentifier,
final UUID requesterUuid,
final Account targetAccount,
final ProfileBadgeConverter profileBadgeConverter) {
final GetUnversionedProfileResponse.Builder responseBuilder = GetUnversionedProfileResponse.newBuilder()
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
.addAllCapabilities(buildAccountCapabilities(targetAccount));
switch (targetIdentifier.identityType()) {
case ACI -> {
responseBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(buildBadges(profileBadgeConverter.convert(
RequestAttributesUtil.getAvailableAcceptedLocales(),
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
targetAccount.getBadges(),
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
targetAccount.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(responseBuilder::setUnidentifiedAccess);
.ifPresent(resultBuilder::setUnidentifiedAccess);
}
case PNI -> responseBuilder.setUnrestrictedUnidentifiedAccess(false);
case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false);
}
return responseBuilder.build();
return resultBuilder.build();
}
static GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredentialResponse(
final UUID targetUuid,
final String version,
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
final Account account,
final byte[] version,
final byte[] encodedCredentialRequest,
final ProfilesManager profilesManager,
final ServerZkProfileOperations zkProfileOperations) throws StatusException {
final ServerZkProfileOperations zkProfileOperations) {
final VersionedProfile profile = profilesManager.get(targetUuid, version)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(encodedCredentialRequest,
profile, new ServiceId.Aci(targetUuid), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw Status.INVALID_ARGUMENT.withCause(e).asException();
final Optional<VersionedProfile> versionedProfile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
versionedProfile = profilesManager.get(account.getUuid(), version);
} else {
versionedProfile = Optional.empty();
}
return GetExpiringProfileKeyCredentialResponse.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
return versionedProfile.map(VersionedProfile::commitment)
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version)).map(VersionedProfileV1::commitment))
.map(commitment -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.constraintViolation("invalid credential request");
}
return GetExpiringProfileKeyCredentialResult.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
});
}
/**
* Computes the SHA-256 hash of the given data.
* <p>
* Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[])
*/
@VisibleForTesting
public static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
}
}
@@ -6,29 +6,30 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.grpc.StatusException;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.GetUnversionedProfileRequest;
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.SetProfileRequest.AvatarChange;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
import org.signal.chat.profile.SimpleProfileGrpc;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -44,9 +45,12 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
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;
@@ -61,7 +65,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private final PolicySigner policySigner;
private final ProfileBadgeConverter profileBadgeConverter;
private final RateLimiters rateLimiters;
private final ServerZkProfileOperations zkProfileOperations;
private record AvatarData(Optional<String> currentAvatar,
Optional<String> finalAvatar,
@@ -76,8 +79,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final PostPolicyGenerator policyGenerator,
final PolicySigner policySigner,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters,
final ServerZkProfileOperations zkProfileOperations) {
final RateLimiters rateLimiters) {
this.clock = clock;
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
@@ -88,33 +90,49 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.policySigner = policySigner;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
this.zkProfileOperations = zkProfileOperations;
}
@Override
public SetProfileResponse setProfile(final SetProfileRequest request) throws StatusException {
validateRequest(request);
public SetProfileResponse setProfile(final SetProfileRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(
authenticatedDevice.accountIdentifier()).orElseThrow(Status.UNAUTHENTICATED::asException);
final Optional<VersionedProfile> maybeProfile = profilesManager.get(
authenticatedDevice.accountIdentifier(), request.getVersion());
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found"));
if (!request.getPaymentAddress().isEmpty()) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && maybeProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
throw Status.PERMISSION_DENIED.asException();
}
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
return SetProfileResponse.newBuilder()
.setProfilesV2CapabilityRequired(ProfilesV2CapabilityRequired.getDefaultInstance())
.build();
}
final Optional<String> currentAvatar = maybeProfile.map(VersionedProfile::avatar)
validateRequest(request);
final byte[] expectedCurrentVersion = request.getExpectedCurrentVersion().toByteArray();
final boolean currentVersionMatchesExpected = Arrays.equals(account.getCurrentProfileVersion().orElse(new byte[0]), expectedCurrentVersion);
if (!currentVersionMatchesExpected) {
return SetProfileResponse.newBuilder().setExpectedVersionWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected profile versions must match")
.build()).build();
}
final byte[] version = request.getVersion().toByteArray();
final Optional<VersionedProfile> maybeProfile = profilesManager.get(authenticatedDevice.accountIdentifier(),
version);
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(
authenticatedDevice.accountIdentifier(), HexFormat.of().formatHex(version));
if (!request.getPaymentAddress().isEmpty() && ProfileHelper.isPaymentAddressUpdateForbidden(account, maybeProfile, maybeV1Profile, dynamicConfigurationManager)) {
return SetProfileResponse.newBuilder()
.setPaymentsForbiddenInRegion(PaymentsForbiddenInRegion.getDefaultInstance())
.build();
}
final Optional<String> currentAvatar = maybeV1Profile.map(VersionedProfileV1::avatar)
.filter(avatar -> avatar.startsWith("profiles/"));
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getV1Request().getAvatarChange())) {
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
case AVATAR_CHANGE_UPDATE -> {
@@ -124,120 +142,128 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
};
profilesManager.set(account.getIdentifier(IdentityType.ACI),
new VersionedProfile(
request.getVersion(),
request.getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getAboutEmoji().toByteArray(),
request.getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getPhoneNumberSharing().toByteArray(),
request.getCommitment().toByteArray()));
final byte[] commitment = !request.getCommitment().isEmpty()
? request.getCommitment().toByteArray()
: maybeProfile.orElseThrow(IllegalStateException::new).commitment();
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
final VersionedProfileV1 v1Profile = new VersionedProfileV1(
HexFormat.of().formatHex(version),
request.getV1Request().getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getV1Request().getAboutEmoji().toByteArray(),
request.getV1Request().getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getV1Request().getPhoneNumberSharing().toByteArray(),
commitment);
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
a.getBadges()))
.orElseGet(a::getBadges);
final VersionedProfile profile = new VersionedProfile(version,
request.getData().toByteArray(),
request.getPaymentAddress().isEmpty() ? null : request.getPaymentAddress().toByteArray(),
commitment
);
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.getVersion());
});
try {
profilesManager.set(account.getIdentifier(IdentityType.ACI), v1Profile, profile,
request.getExpectedCurrentDataHash().isEmpty() ? null : request.getExpectedCurrentDataHash().toByteArray());
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
} catch (WriteConflictException _) {
return SetProfileResponse.newBuilder()
.setExpectedDataWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected data hash mismatch")
.build())
.build();
}
try {
accountsManager.updateCurrentProfileVersion(account.getIdentifier(IdentityType.ACI), version, expectedCurrentVersion, a -> {
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
a.getBadges()))
.orElseGet(a::getBadges);
a.setBadges(clock, updatedBadges);
});
} catch (final WriteConflictException _) {
return SetProfileResponse.newBuilder()
.setExpectedVersionWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected version mismatch")
.build())
.build();
}
if (request.getV1Request().getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
profilesManager.deleteAvatar(avatarData.currentAvatar().get());
}
return avatarData.uploadAttributes()
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
.orElse(SetProfileResponse.newBuilder().build());
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder()
.setResult(SetProfileResult.newBuilder()
.setV1AvatarUploadForm(avatarUploadAttributes).build())
.build())
.orElse(SetProfileResponse.newBuilder()
.setResult(SetProfileResult.getDefaultInstance())
.build());
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws StatusException, RateLimitExceededException {
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
authenticatedDevice.accountIdentifier(),
targetAccount,
profileBadgeConverter);
account,
profileBadgeConverter))
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws StatusException, RateLimitExceededException {
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Account account = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getVersionedProfile(account, profilesManager, request.getVersion());
return maybeAccount.map(account ->
ProfileGrpcHelper.getVersionedProfile(account, profilesManager,
request.getVersion().toByteArray(),
request.getDataEtag().toByteArray(),
request.getPaymentAddressEtag().toByteArray())
.map(result ->
GetVersionedProfileResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialRequest request) throws StatusException, RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
}
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(targetAccount.getUuid(),
request.getVersion(), request.getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
}
private Account validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException, StatusException {
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException {
rateLimiters.getProfileLimiter().validate(requesterUuid);
return accountsManager.getByServiceIdentifier(targetIdentifier).orElseThrow(Status.NOT_FOUND::asException);
return accountsManager.getByServiceIdentifier(targetIdentifier);
}
private void validateRequest(final SetProfileRequest request) throws StatusException {
if (request.getVersion().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asException();
private void validateRequest(final SetProfileRequest request) {
if (request.getExpectedCurrentDataHash().isEmpty() && request.getCommitment().isEmpty()) {
throw GrpcExceptions.constraintViolation("At least one of expected current data hash and commitment is required");
}
// v1 -> v2 migration
if (request.getCommitment().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asException();
throw GrpcExceptions.constraintViolation("Request must include commitment during migration");
}
checkByteStringLength(request.getName(), "Invalid name length", List.of(81, 285));
checkByteStringLength(request.getAboutEmoji(), "Invalid about emoji length", List.of(0, 60));
checkByteStringLength(request.getAbout(), "Invalid about length", List.of(0, 156, 282, 540));
checkByteStringLength(request.getPaymentAddress(), "Invalid mobile coin address length", List.of(0, 582));
}
private static void checkByteStringLength(final ByteString byteString, final String errorMessage,
final List<Integer> allowedLengths) throws StatusException {
final int byteStringLength = byteString.toByteArray().length;
for (int allowedLength : allowedLengths) {
if (byteStringLength == allowedLength) {
return;
}
}
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asException();
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
@@ -48,6 +48,8 @@ public class RequestAttributesInterceptor implements ServerInterceptor {
final String acceptLanguageHeader = headers.get(ACCEPT_LANG_KEY);
final String xForwardedForHeader = headers.get(X_FORWARDED_FOR_KEY);
// This assumes that X-Forwarded-For has been set by a trusted intermediate proxy. For example, this may be set by
// OmnibusH2Server which itself sets X-Forwarded-For using a PPv2 header that comes from a trusted load-balancer.
final Optional<InetAddress> remoteAddress = getMostRecentProxy(xForwardedForHeader)
.flatMap(mostRecentProxy -> {
try {
@@ -26,6 +26,7 @@ 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;
import org.whispersystems.textsecuregcm.grpc.validators.ServiceIdentifierIdentityTypeValidator;
import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
public class ValidatingInterceptor implements ServerInterceptor {
@@ -39,7 +40,8 @@ public class ValidatingInterceptor implements ServerInterceptor {
"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.base64url", new Base64UrlFieldValidator(),
"org.signal.chat.require.identityType", new ServiceIdentifierIdentityTypeValidator()
);
@Override
@@ -64,9 +66,6 @@ public class ValidatingInterceptor implements ServerInterceptor {
try {
validateMessage(message);
super.onMessage(message);
} catch (final StatusRuntimeException e) {
call.close(e.getStatus(), e.getTrailers());
forwardCalls = false;
} catch (RuntimeException runtimeException) {
final StatusRuntimeException grpcException = switch (runtimeException) {
case StatusRuntimeException e -> e;
@@ -0,0 +1,91 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import io.micrometer.core.instrument.Metrics;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http2.Http2StreamFrame;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/// Writes all inbound H2 frames to [this#peerStream], renumbering the inbound H2 stream-id for peer H2 stream
public class H2FrameProxyHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(H2FrameProxyHandler.class);
private static final String WRITABILITY_CHANGED_COUNTER_NAME = MetricsUtil.name(H2FrameProxyHandler.class, "writabilityChanged");
private final Channel peerStream;
private final String proxyNameTag;
// If we fail to write to the peerStream, we want to close the inbound channel. Rather than allocate a new listener
// that captures the inbound ChannelHandlerContext on every message, we capture the ChannelHandlerContext in
// handlerAdded and use it on all forwarded writes. This would not work if we attached this handler to more than
// one channel, but we already have a designated peerStream so this handler is fundamentally single-channel.
private ChannelFutureListener closeInboundOnPeerFailure = null;
public H2FrameProxyHandler(final Channel peerStream, final String proxyNameTag) {
this.peerStream = peerStream;
this.proxyNameTag = proxyNameTag;
}
@Override
public void handlerAdded(final ChannelHandlerContext ctx) {
closeInboundOnPeerFailure = f -> {
if (!f.isSuccess()) {
ctx.close();
}
};
// When the peer stream we are forwarding to becomes unwritable/writable, stop/start reading from the source stream.
// This prevents us from reading from the source stream as fast as we can just to buffer requests for the peer
// stream.
peerStream.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelWritabilityChanged(final ChannelHandlerContext peerCtx) throws Exception {
Metrics.counter(WRITABILITY_CHANGED_COUNTER_NAME,
"isWritable", Boolean.toString(peerCtx.channel().isWritable()),
"proxy", proxyNameTag)
.increment();
ctx.channel().config().setAutoRead(peerStream.isWritable());
super.channelWritabilityChanged(peerCtx);
}
});
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
logger.trace("Received frame {}", msg);
if (!(msg instanceof Http2StreamFrame streamFrame)) {
logger.error("Received unexpected frame {}", msg);
ReferenceCountUtil.release(msg);
ctx.close();
return;
}
// Clear the stream-id on this frame, so netty will associate it with the peerStream's stream-id. The inbound
// frame has a stream-id associated with the inbound connection. This will not match the stream-id of the peer
// stream we are forwarding the frames to. If the stream-id on a frame is not set, netty handles sending the
// stream-id on the frame to the target stream's stream-id.
streamFrame.stream(null);
peerStream.writeAndFlush(streamFrame).addListener(closeInboundOnPeerFailure);
}
@Override
public void channelInactive(final ChannelHandlerContext ctx) {
peerStream.close();
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
logger.warn("Exception proxying frames", cause);
ctx.close();
}
}
@@ -0,0 +1,30 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import io.dropwizard.lifecycle.Managed;
import io.netty.channel.EventLoopGroup;
/**
* A wrapper for a Netty {@link EventLoopGroup} that implements Dropwizard's {@link Managed} interface, allowing
* Dropwizard to manage the lifecycle of the event loop group.
*/
public class ManagedEventLoopGroup<T extends EventLoopGroup> implements Managed {
private final T eventLoopGroup;
public ManagedEventLoopGroup(final T eventLoopGroup) {
this.eventLoopGroup = eventLoopGroup;
}
@Override
public void stop() throws Exception {
this.eventLoopGroup.shutdownGracefully().await();
}
public T getEventLoopGroup() {
return eventLoopGroup;
}
}
@@ -1,16 +0,0 @@
package org.whispersystems.textsecuregcm.grpc.net;
import io.dropwizard.lifecycle.Managed;
import io.netty.channel.nio.NioEventLoopGroup;
/**
* A wrapper for a Netty {@link NioEventLoopGroup} that implements Dropwizard's {@link Managed} interface, allowing
* Dropwizard to manage the lifecycle of the event loop group.
*/
public class ManagedNioEventLoopGroup extends NioEventLoopGroup implements Managed {
@Override
public void stop() throws Exception {
this.shutdownGracefully().await();
}
}
@@ -0,0 +1,38 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import java.util.concurrent.atomic.AtomicLong;
@ChannelHandler.Sharable
public class OmnibusConnectionCounterHandler extends ChannelInboundHandlerAdapter {
private final AtomicLong openConnections;
private final Counter acceptedConnectionsCounter =
Metrics.counter(MetricsUtil.name(OmnibusConnectionCounterHandler.class, "connectionsAccepted"));
public OmnibusConnectionCounterHandler() {
openConnections =
Metrics.gauge(MetricsUtil.name(OmnibusConnectionCounterHandler.class, "openConnections"), new AtomicLong());
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
acceptedConnectionsCounter.increment();
openConnections.incrementAndGet();
super.channelRegistered(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
openConnections.decrementAndGet();
super.channelInactive(ctx);
}
}
@@ -0,0 +1,55 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import io.micrometer.core.instrument.Metrics;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/// A handler that closes the channel on an exception and records errors in a counter. This should be placed at the tail
/// of pipelines to catch uncaught exceptions gracefully
@ChannelHandler.Sharable
public class OmnibusExceptionHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(OmnibusExceptionHandler.class);
private static final String UNCAUGHT_EXCEPTION_COUNTER_NAME = MetricsUtil.name(OmnibusExceptionHandler.class,
"uncaughtException");
private final String channelName;
private final List<Class<? extends Exception>> expectedExceptions;
public OmnibusExceptionHandler(final String channelName, final List<Class<? extends Exception>> expectedExceptions) {
this.channelName = channelName;
this.expectedExceptions = expectedExceptions;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
Metrics.counter(UNCAUGHT_EXCEPTION_COUNTER_NAME,
"channelName", channelName,
"exceptionClass", cause.getClass().getSimpleName())
.increment();
// There are 'expected' ways to get exceptions on a channel (e.g. client disconnects) so we only log them at debug.
if (expectedException(cause)) {
logger.debug("uncaught exception on channel {}", channelName, cause);
} else {
logger.warn("unexpected uncaught exception on channel {}", channelName, cause);
}
ctx.close();
}
private boolean expectedException(final Throwable exception) {
return expectedExceptions
.stream()
.anyMatch(expectedException -> expectedException.isInstance(exception));
}
}
@@ -0,0 +1,176 @@
/*
* 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.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.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.SimpleUserEventChannelHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
import io.netty.handler.ssl.SniHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.Mapping;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/// An HTTP/2 server that proxies H2 streams to configurable backends via path-based routing
public class OmnibusH2Server implements Managed {
private static final Logger logger = LoggerFactory.getLogger(OmnibusH2Server.class);
private static final OmnibusConnectionCounterHandler CONNECT_COUNTER = new OmnibusConnectionCounterHandler();
private static final OmnibusExceptionHandler HANDSHAKE_EXCEPTION_HANDLER =
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 String IDLE_DISCONNECT_COUNTER_NAME = MetricsUtil.name(OmnibusH2Server.class, "idleDisconnect");
private final @Nullable Mapping<String, SslContext> sslContextBySni;
private final OmnibusRouter router;
private final Duration idleTimeout;
private final DefaultEventLoopGroup localEventLoopGroup;
private final NioEventLoopGroup nioEventLoopGroup;
private final SocketAddress bindAddress;
private Channel serverChannel;
/// 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
public OmnibusH2Server(
final @Nullable Mapping<String, SslContext> sslContextBySni,
final NioEventLoopGroup nioEventLoopGroup,
final DefaultEventLoopGroup localEventLoopGroup,
final SocketAddress bindAddress,
final OmnibusRouter router,
final Duration idleTimeout) {
this.sslContextBySni = sslContextBySni;
this.nioEventLoopGroup = nioEventLoopGroup;
this.localEventLoopGroup = localEventLoopGroup;
this.bindAddress = bindAddress;
this.router = router;
this.idleTimeout = idleTimeout;
}
@Override
public void start() throws Exception {
if (this.sslContextBySni == null) {
logger.warn("No SSL configuration provided for OmnibusH2Server, serving h2c");
}
if (ByteBufAllocator.DEFAULT instanceof ByteBufAllocatorMetricProvider alloc) {
Metrics.gauge(MetricsUtil.name(OmnibusH2Server.class, "nettyUsedDirectMemory"),
alloc,
allocator -> allocator.metric().usedDirectMemory());
Metrics.gauge(MetricsUtil.name(OmnibusH2Server.class, "nettyUsedHeapMemory"),
alloc,
allocator -> allocator.metric().usedHeapMemory());
}
final ServerBootstrap bootstrap = new ServerBootstrap()
.group(nioEventLoopGroup)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel ch) {
ch.pipeline().addLast(new IdleStateHandler(0, 0, idleTimeout.toMillis(), TimeUnit.MILLISECONDS));
ch.pipeline().addLast(new SimpleUserEventChannelHandler<IdleStateEvent>() {
@Override
protected void eventReceived(final ChannelHandlerContext ctx, final IdleStateEvent evt) {
Metrics.counter(IDLE_DISCONNECT_COUNTER_NAME, "type", evt.state().name()).increment();
ctx.close();
}
});
ch.pipeline().addLast(CONNECT_COUNTER);
ch.pipeline().addLast(new ProxyProtocolHandler());
ch.pipeline().addLast(new ProxyMessageAttributeSetterHandler());
if (sslContextBySni == null) {
configureH2Pipeline(ch.pipeline());
} else {
ch.pipeline().addLast(new SniHandler(sslContextBySni));
ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) {
@Override
protected void configurePipeline(final ChannelHandlerContext ctx, final String protocol) {
if (!ApplicationProtocolNames.HTTP_2.equals(protocol)) {
// HTTP/2 should be enforced by our ALPN settings
logger.error("Unsupported protocol negotiated: {}, closing connection", protocol);
ctx.close();
return;
}
configureH2Pipeline(ctx.pipeline());
}
});
ch.pipeline().addLast(HANDSHAKE_EXCEPTION_HANDLER);
}
}
});
serverChannel = bootstrap.bind(bindAddress).sync().channel();
logger.info("Omnibus server listening on {}", getLocalAddress());
}
@VisibleForTesting
InetSocketAddress getLocalAddress() {
return (InetSocketAddress) serverChannel.localAddress();
}
@Override
public void stop() {
if (serverChannel != null) {
logger.info("Stopping omnibus server");
serverChannel.close().syncUninterruptibly();
logger.info("Omnibus server stopped");
}
}
private void configureH2Pipeline(final ChannelPipeline pipeline) {
// Advertise support for RFC-8441 extended connect
final Http2Settings settings = Http2Settings.defaultSettings().connectProtocolEnabled(true);
pipeline.addLast(Http2FrameCodecBuilder.forServer().initialSettings(settings).build());
pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(final Http2StreamChannel ch) {
ch.pipeline().addLast(new OmnibusH2StreamHandler(nioEventLoopGroup, localEventLoopGroup, router));
}
}));
pipeline.addLast(SESSION_EXCEPTION_HANDLER);
}
}
@@ -0,0 +1,230 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/// Handler added on each newly created [Http2StreamChannel] on an H2 connection. Inspects the [Http2HeadersFrame] and
/// determines which backend to forward the stream to, and then proxies frames to and from the backend.
///
/// When this handler receives an H2 header for a new stream-id=X on our parent H2 connection it will
/// - Receive the stream-id=X header and check the path to determine the correct backend
/// - Make a new H2 connection to the backend
/// - Forward the header with stream-id=Y to the backend
/// - Install a [H2FrameProxyHandler] on the backend stream pipeline that forwards the received stream-id=Y frames from
/// the backend back to the client on stream-id=X
/// - Install a [H2FrameProxyHandler] on the client stream pipeline forwards the received stream-id=X frames from the
/// client to the backend on stream-id=Y
public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(OmnibusH2StreamHandler.class);
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
new OmnibusExceptionHandler("backend-connection", List.of());
private static final String BACKEND_STREAM_COUNTER_NAME = name(OmnibusH2StreamHandler.class, "backendStream");
private static final String BACKEND_CONNECT_DURATION_NAME = name(OmnibusH2StreamHandler.class,
"backendConnectDuration");
private static final String BACKEND_TAG = "backend";
private final OmnibusRouter router;
private final DefaultEventLoopGroup localEventLoopGroup;
private final NioEventLoopGroup nioEventLoopGroup;
public OmnibusH2StreamHandler(
final NioEventLoopGroup nioEventLoopGroup,
final DefaultEventLoopGroup localEventLoopGroup,
final OmnibusRouter router) {
this.router = router;
this.localEventLoopGroup = localEventLoopGroup;
this.nioEventLoopGroup = nioEventLoopGroup;
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
if (!(msg instanceof Http2HeadersFrame headersFrame)) {
logger.warn("Expected initial HEADERS frame but got {}", msg.getClass().getSimpleName());
ReferenceCountUtil.release(msg);
ctx.close();
return;
}
// We don't expect headers frames to come with manually managed memory attached. Assert this in case this changes
// in the future, but for now we don't have to worry about freeing the headers frame
assert !(headersFrame instanceof ReferenceCounted);
// Disable reading from the client because we want to wait until we make the backend connection and install the
// forwarding handler before processing any more frames.
ctx.channel().config().setAutoRead(false);
// Select the target backend based on the path
final String path = Optional.ofNullable(headersFrame.headers().path()).map(CharSequence::toString).orElse("");
final SocketAddress target = router.match(path);
final String backendTag = target.toString();
Metrics.counter(BACKEND_STREAM_COUNTER_NAME, BACKEND_TAG, backendTag).increment();
// Set X-Forwarded-For from the PROXY protocol header if present, otherwise via the remote address
final InetAddress proxyRemoteAddress = ctx.channel().parent()
.attr(ProxyMessageAttributeSetterHandler.PROXY_REMOTE_ADDRESS)
.get();
headersFrame.headers().set("x-forwarded-for", proxyRemoteAddress != null
? proxyRemoteAddress.getHostAddress()
: ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
// Make a new H2 connection to the target backend
final Timer.Sample connectSample = Timer.start();
new Bootstrap()
.group(selectEventLoop(ctx, target))
.channel(target instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class)
.handler(new ChannelInitializer<>() {
@Override
protected void initChannel(final Channel ch) {
ch.pipeline()
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
}
})
.connect(target)
.addListener((ChannelFuture connectFuture) -> {
connectSample.stop(Timer.builder(BACKEND_CONNECT_DURATION_NAME)
.tag(BACKEND_TAG, backendTag)
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
.register(Metrics.globalRegistry));
if (!connectFuture.isSuccess()) {
// Close the client stream with a 502: Bad Gateway if the backend wasn't available
logger.warn("Failed to connect to backend {}", target, connectFuture.cause());
ctx.channel()
.writeAndFlush(new DefaultHttp2HeadersFrame(
new DefaultHttp2Headers().status("502"), true))
.addListener(ChannelFutureListener.CLOSE);
return;
}
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
logger.trace("Opening a HTTP/2 stream to the backend {}", target);
final Channel backendConnection = connectFuture.channel();
createBackendProxyStream(ctx, backendConnection, headersFrame);
});
}
/// Create a proxy stream on the provided `backendConnection` that forwards H2 frames to/from the client H2 stream.
///
/// @param clientStreamCtx The context for a client H2 stream that targets the backend
/// @param backendConnection An established H2 connection [Channel], on which a new h2 stream will be opened
/// @param headersFrame The first `headersFrame` from the client h2 stream that should be forwarded to the new
/// backend stream
private void createBackendProxyStream(
final ChannelHandlerContext clientStreamCtx,
final Channel backendConnection,
final Http2HeadersFrame headersFrame) {
new Http2StreamChannelBootstrap(backendConnection)
// Forwards response frames from the backend back to the client stream
.handler(new H2FrameProxyHandler(clientStreamCtx.channel(), "responseStream"))
.open()
.addListener((io.netty.util.concurrent.Future<Http2StreamChannel> streamFuture) -> {
if (!streamFuture.isSuccess()) {
logger.warn("Failed to open backend stream", streamFuture.cause());
clientStreamCtx.channel()
.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.INTERNAL_ERROR))
.addListener(ChannelFutureListener.CLOSE);
backendConnection.close();
return;
}
final Http2StreamChannel backendStream = streamFuture.getNow();
// Close the entire H2 connection whenever the stream we just opened closes. We only plan on using
// a single stream on this connection.
backendStream.closeFuture().addListener(_ -> backendConnection.close());
// We're going to modify the inbound H2 stream channel, which runs on a different eventloop than the
// outbound channel we've made to the backend. We have to submit our updates back to the inbound
// channel's event loop for thread safety
clientStreamCtx.channel().eventLoop().execute(() -> {
if (!clientStreamCtx.channel().isActive()) {
// The client disconnected already and the client pipeline is already torn down.
backendConnection.close();
return;
}
// Install proxy on client stream, remove this handler, then fire the buffered headers through the proxy
clientStreamCtx.pipeline().replace(
OmnibusH2StreamHandler.this,
"backend-to-client-proxy",
new H2FrameProxyHandler(backendStream, "requestStream"));
clientStreamCtx.channel().pipeline().fireChannelRead(headersFrame);
// Resume inbound reads, which should now be forwarded
clientStreamCtx.channel().config().setAutoRead(true);
});
});
}
private EventLoopGroup selectEventLoop(final ChannelHandlerContext inboundCtx, SocketAddress target) {
final boolean localInbound = inboundCtx.channel() instanceof LocalChannel;
final boolean localTarget = target instanceof LocalAddress;
// If the inbound eventloop matches the target type, we can just reuse the inbound's event loop
if (localInbound == localTarget) {
return inboundCtx.channel().eventLoop();
}
return localTarget ? this.localEventLoopGroup : this.nioEventLoopGroup;
}
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRegistered(final ChannelHandlerContext ctx) {
logger.error("Inbound stream handler was registered when no inbound streams expected");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
super.channelRead(ctx, msg);
}
}
}
@@ -0,0 +1,30 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import java.net.SocketAddress;
import java.util.List;
public class OmnibusRouter {
public record OmnibusRoute(String prefix, SocketAddress backend) {}
private final List<OmnibusRoute> prefixRoutes;
private final SocketAddress defaultBackend;
public OmnibusRouter(final List<OmnibusRoute> prefixRoutes, final SocketAddress defaultBackend) {
this.prefixRoutes = prefixRoutes;
this.defaultBackend = defaultBackend;
}
SocketAddress match(final String path) {
for (final OmnibusRoute route : prefixRoutes) {
if (path.startsWith(route.prefix)) {
return route.backend;
}
}
return defaultBackend;
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.util.AttributeKey;
import java.net.InetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/// Reads the decoded [HAProxyMessage], stores the source address as a channel attribute, and removes itself.
class ProxyMessageAttributeSetterHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(ProxyMessageAttributeSetterHandler.class);
/// Attribute for the remote address extracted from a proxy protocol header
static final AttributeKey<InetAddress> PROXY_REMOTE_ADDRESS = AttributeKey.newInstance("proxyRemoteAddress");
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (!(msg instanceof HAProxyMessage proxyMessage)) {
ctx.pipeline().remove(this);
ctx.fireChannelRead(msg);
return;
}
try {
final String sourceAddress = proxyMessage.sourceAddress();
if (sourceAddress != null) {
ctx.channel().attr(PROXY_REMOTE_ADDRESS).set(InetAddress.getByName(sourceAddress));
} else {
logger.warn("PROXY protocol message has no source address");
}
} finally {
proxyMessage.release();
ctx.pipeline().remove(this);
}
}
}
@@ -0,0 +1,48 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.ProtocolDetectionResult;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
import java.util.List;
class ProxyProtocolHandler extends ByteToMessageDecoder {
private static final String PROXY_PROTOCOL_DETECTED_NAME =
name(ProxyProtocolHandler.class, "proxyProtocol");
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
// This does not advance the read index, so the bytes we accumulate via ByteToMessageDecoder are always forwarded
// once we get enough (either to an HAProxyMessageDecoder, or just to the rest of the pipeline)
final ProtocolDetectionResult<HAProxyProtocolVersion> detected = HAProxyMessageDecoder.detectProtocol(in);
switch (detected.state()) {
case NEEDS_MORE_DATA:
break;
case DETECTED:
// There is a valid proxy-protocol header. Replace ourselves with the actual decoder (which will forward our
// accumulated bytes to the decoder via handlerRemoved)
Metrics.counter(PROXY_PROTOCOL_DETECTED_NAME, "detected", "true").increment();
ctx.pipeline().replace(this, "haproxy-decoder", new HAProxyMessageDecoder());
break;
case INVALID:
// No header, we can just forward any bytes we've accumulated.
Metrics.counter(PROXY_PROTOCOL_DETECTED_NAME, "detected", "false").increment();
ctx.pipeline().remove(this);
break;
}
}
}
@@ -0,0 +1,164 @@
/*
* 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.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.util.Mapping;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SniMapper {
private static final Logger logger = LoggerFactory.getLogger(SniMapper.class);
private SniMapper() {
}
/// Build a [Mapping] from a [KeyStore] that maps from domain (via SAN) to [io.netty.handler.ssl.SslContext] that
/// can be used with an [io.netty.handler.ssl.SniHandler]. The provided keystore may contain multiple certificates
/// for a single domain, all matching certificates will be included in the corresponding SslContext. The domain for
/// a certificate is only determined by the SAN and all certificates must have a SAN. The returned [Mapping] returns
/// an arbitrary set of certificates if none of the certificates in the keystore match a requested domain, as
/// permitted by RFC-6066.
///
/// @param keyStorePath The path to the [KeyStore]
/// @param keyStorePassword The password for the keyStore
/// @return A [Mapping] that maps domains to the corresponding [SslContext] containing the certificates for that
/// domain
public static Mapping<String, SslContext> buildSniMapping(final String keyStorePath, final String keyStorePassword)
throws IOException {
try (final FileInputStream fis = new FileInputStream(keyStorePath)) {
return buildSniMapping(fis, keyStorePassword);
}
}
@VisibleForTesting
static Mapping<String, SslContext> buildSniMapping(final InputStream keyStore, final String keyStorePassword)
throws IOException {
try {
final Map<String, KeyStore> domainKeyStores = partitionByDomain(keyStore, keyStorePassword.toCharArray());
final Map<String, SslContext> sslContextsByDomain = new HashMap<>();
for (final Map.Entry<String, KeyStore> entry : domainKeyStores.entrySet()) {
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(entry.getValue(), keyStorePassword.toCharArray());
sslContextsByDomain.put(entry.getKey(), buildSslContext(kmf));
}
// Netty expects the SNI mapping to always return an SslContext. Per RFC-6066 it's valid to continue the handshake
// on an SNI mismatch, it's the client's responsibility to check the returned certificate's SNI. We sort first so
// our choice of certificate is deterministic.
final SslContext defaultSslContext = sslContextsByDomain.entrySet().stream()
.min(Map.Entry.comparingByKey())
.orElseThrow(() -> new IllegalArgumentException("Key store contained no certificates"))
.getValue();
logger.info("Loaded TLS contexts for domains: {}", sslContextsByDomain.keySet());
return hostname -> sslContextsByDomain.getOrDefault(hostname, defaultSslContext);
} catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException e) {
throw new IOException("Failed to load keystore", e);
}
}
private static SslContext buildSslContext(final KeyManagerFactory kmf) throws SSLException {
return SslContextBuilder.forServer(kmf)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.protocols("TLSv1.3")
.build();
}
private static Map<String, KeyStore> partitionByDomain(final InputStream keystoreStream, final char[] keystorePassword)
throws KeyStoreException, CertificateException, UnrecoverableKeyException, IOException, NoSuchAlgorithmException {
final KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(keystoreStream, keystorePassword);
// Group key entries by the domain(s) in each certificate's SANs
final Map<String, KeyStore> domainKeyStores = new HashMap<>();
for (final String alias : Collections.list(keyStore.aliases())) {
if (!keyStore.isKeyEntry(alias)) {
continue;
}
final Certificate[] chain = keyStore.getCertificateChain(alias);
if (chain == null || chain.length == 0) {
continue;
}
final X509Certificate leaf = (X509Certificate) chain[0];
final Key key = keyStore.getKey(alias, keystorePassword);
for (final String domain : getDnsNames(leaf)) {
domainKeyStores
.computeIfAbsent(domain, _ -> newEmptyKeyStore())
.setKeyEntry(alias, key, keystorePassword, chain);
}
}
if (domainKeyStores.isEmpty()) {
throw new IOException("Keystore contains no usable key entries with DNS names");
}
return domainKeyStores;
}
private static KeyStore newEmptyKeyStore() {
try {
final KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null, null);
return ks;
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
// All Java runtime implementations are required to support PKCS12, and we aren't loading anything from disk
// so an exception here is impossible.
throw new AssertionError("Failed to create empty keystore", e);
}
}
/// Extract all DNS-type SAN names on this certificate
private static List<String> getDnsNames(final X509Certificate cert) throws CertificateParsingException, IOException {
final Collection<List<?>> sans = cert.getSubjectAlternativeNames();
if (sans == null) {
throw new IOException("Certificate did not have SAN extension");
}
final List<String> dnsSans = sans.stream()
// GeneralName type 2 = dNSName. See getSubjectAlternativeNames
.filter(san -> (int) san.getFirst() == 2)
.map(san -> (String) san.get(1))
.map(s -> s.toLowerCase(Locale.ROOT))
.toList();
if (dnsSans.isEmpty()) {
throw new IOException("Certificate did not have a DNS SAN entry");
}
return dnsSans;
}
}
@@ -0,0 +1,52 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.Objects;
import java.util.Set;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
public class ServiceIdentifierIdentityTypeValidator extends BaseFieldValidator<IdentityType> {
public ServiceIdentifierIdentityTypeValidator() {
super("identityType", Set.of(Descriptors.FieldDescriptor.Type.MESSAGE), MissingOptionalAction.SUCCEED, false);
}
@Override
protected IdentityType resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
if (extensionValue instanceof Descriptors.EnumValueDescriptor d) {
if (d.getType().equals(org.signal.chat.require.IdentityType.getDescriptor())) {
return switch (Objects.requireNonNull(org.signal.chat.require.IdentityType.forNumber(d.getNumber()))) {
case IDENTITY_TYPE_ACI -> IdentityType.IDENTITY_TYPE_ACI;
case IDENTITY_TYPE_PNI -> IdentityType.IDENTITY_TYPE_PNI;
default -> throw new IllegalArgumentException("unsupported value: " + d.getName());
};
}
}
throw new IllegalArgumentException("value must be org.signal.chat.require.IdentityType");
}
@Override
protected void validateMessageValue(final IdentityType extensionValue, final Message msg) throws FieldValidationException {
if (msg == null) {
return;
}
if (msg instanceof ServiceIdentifier i) {
if (i.getIdentityType() == extensionValue) {
return;
}
throw new FieldValidationException("identity type must be " + extensionValue.getValueDescriptor().getName());
}
throw new IllegalArgumentException("field must be " + ServiceIdentifier.class.getName());
}
}
@@ -40,8 +40,6 @@ public class JettyHttpConfigurationCustomizer implements Container.Listener, Lif
httpConfiguration.setNotifyRemoteAsyncErrors(false);
}
}
c.addBean(new JettyConnectionMetrics(Metrics.globalRegistry));
}
}
@@ -14,7 +14,7 @@ import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
/**
* Delegates request events to a listener that captures and reports request-level metrics.
*
* @see MetricsHttpChannelListener
* @see MetricsHttpEventHandler
* @see MetricsRequestEventListener
*/
public class MetricsApplicationEventListener implements ApplicationEventListener {
@@ -23,7 +23,7 @@ public class MetricsApplicationEventListener implements ApplicationEventListener
public MetricsApplicationEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
if (trafficSource == TrafficSource.HTTP) {
throw new IllegalArgumentException("Use " + MetricsHttpChannelListener.class.getName() + " for HTTP traffic");
throw new IllegalArgumentException("Use " + MetricsHttpEventHandler.class.getName() + " for HTTP traffic");
}
this.metricsRequestEventListener = new MetricsRequestEventListener(trafficSource, clientReleaseManager);
}
@@ -1,226 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.core.setup.Environment;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.component.Container;
import org.eclipse.jetty.util.component.LifeCycle;
import org.glassfish.jersey.server.ExtendedUriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
/**
* Gathers and reports HTTP request metrics at the Jetty container level, which sits above Jersey. In order to get
* templated Jersey request paths, it implements {@link jakarta.ws.rs.container.ContainerResponseFilter}, in order to give
* itself access to the template. It is limited to {@link TrafficSource#HTTP} requests.
* <p>
* It implements {@link LifeCycle.Listener} without overriding methods, so that it can be an event listener that
* Dropwizard will attach to the container&mdash;the {@link Container.Listener} implementation is where it attaches
* itself to any {@link Connector}s.
*
* @see MetricsRequestEventListener
*/
public class MetricsHttpChannelListener implements HttpChannel.Listener, Container.Listener, LifeCycle.Listener,
ContainerResponseFilter {
private static final Set<String> EXPECTED_HTTP_METHODS =
Set.of("GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH");
private static final Logger logger = LoggerFactory.getLogger(MetricsHttpChannelListener.class);
private record RequestInfo(String path, String method, int statusCode, @Nullable String userAgent) {
}
private final ClientReleaseManager clientReleaseManager;
private final Set<String> servletPaths;
// Use the same counter namespace as MetricsRequestEventListener for continuity
public static final String REQUEST_COUNTER_NAME = MetricsRequestEventListener.REQUEST_COUNTER_NAME;
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricsRequestEventListener.REQUESTS_BY_VERSION_COUNTER_NAME;
@VisibleForTesting
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME;
@VisibleForTesting
static final String REQUEST_BYTES_COUNTER_NAME = MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME;
@VisibleForTesting
static final String URI_INFO_PROPERTY_NAME = MetricsHttpChannelListener.class.getName() + ".uriInfo";
@VisibleForTesting
static final String PATH_TAG = "path";
@VisibleForTesting
static final String METHOD_TAG = "method";
@VisibleForTesting
static final String STATUS_CODE_TAG = "status";
@VisibleForTesting
static final String TRAFFIC_SOURCE_TAG = "trafficSource";
private final MeterRegistry meterRegistry;
public MetricsHttpChannelListener(final ClientReleaseManager clientReleaseManager, final Set<String> servletPaths) {
this(Metrics.globalRegistry, clientReleaseManager, servletPaths);
}
@VisibleForTesting
MetricsHttpChannelListener(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager,
final Set<String> servletPaths) {
this.meterRegistry = meterRegistry;
this.clientReleaseManager = clientReleaseManager;
this.servletPaths = servletPaths;
}
public void configure(final Environment environment) {
// register as ContainerResponseFilter
environment.jersey().register(this);
// hook into lifecycle events, to react to the Connector being added
environment.lifecycle().addEventListener(this);
}
@Override
public void onRequestFailure(final Request request, final Throwable failure) {
if (logger.isDebugEnabled()) {
final RequestInfo requestInfo = getRequestInfo(request);
logger.debug("Request failure: {} {} ({}) [{}] ",
requestInfo.method(),
requestInfo.path(),
requestInfo.userAgent(),
requestInfo.statusCode(), failure);
}
}
@Override
public void onResponseFailure(Request request, Throwable failure) {
if (failure instanceof org.eclipse.jetty.io.EofException) {
// the client disconnected early
return;
}
final RequestInfo requestInfo = getRequestInfo(request);
logger.warn("Response failure: {} {} ({}) [{}] ",
requestInfo.method(),
requestInfo.path(),
requestInfo.userAgent(),
requestInfo.statusCode(), failure);
}
@Override
public void onComplete(final Request request) {
final RequestInfo requestInfo = getRequestInfo(request);
@Nullable final UserAgent userAgent;
{
UserAgent parsedUserAgent;
try {
parsedUserAgent = UserAgentUtil.parseUserAgentString(requestInfo.userAgent());
} catch (final UnrecognizedUserAgentException e) {
parsedUserAgent = null;
}
userAgent = parsedUserAgent;
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
final List<Tag> tags = new ArrayList<>(5);
tags.add(Tag.of(PATH_TAG, requestInfo.path()));
tags.add(Tag.of(METHOD_TAG, requestInfo.method()));
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(requestInfo.statusCode())));
tags.add(Tag.of(TRAFFIC_SOURCE_TAG, TrafficSource.HTTP.name().toLowerCase()));
tags.add(platformTag);
final Optional<Tag> maybeClientVersionTag =
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager);
maybeClientVersionTag.ifPresent(tags::add);
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(request.getResponse().getContentCount());
meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(request.getContentRead());
maybeClientVersionTag.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
Tags.of(clientVersionTag, platformTag))
.increment());
}
@Override
public void beanAdded(final Container parent, final Object child) {
if (child instanceof Connector connector) {
connector.addBean(this);
}
}
@Override
public void beanRemoved(final Container parent, final Object child) {
}
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
throws IOException {
requestContext.setProperty(URI_INFO_PROPERTY_NAME, requestContext.getUriInfo());
}
private RequestInfo getRequestInfo(Request request) {
final String path = Optional.ofNullable(request.getAttribute(URI_INFO_PROPERTY_NAME))
.map(attr -> UriInfoUtil.getPathTemplate((ExtendedUriInfo) attr))
.orElseGet(() ->
Optional.ofNullable(request.getPathInfo())
.filter(servletPaths::contains)
.orElse("unknown")
);
// Response cannot be null, but its status might not always reflect an actual response status, since it gets
// initialized to 200
final int status = request.getResponse().getStatus();
@Nullable final String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
return new RequestInfo(path, normalizeMethod(request.getMethod()), status, userAgent);
}
static String normalizeMethod(@Nullable final String method) {
if (StringUtils.isBlank(method)) {
return "unknown";
}
return EXPECTED_HTTP_METHODS.contains(method.toUpperCase(Locale.ROOT)) ? method : "unknown";
}
}
@@ -0,0 +1,280 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.core.setup.Environment;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.io.Content;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.EventsHandler;
import org.eclipse.jetty.util.component.LifeCycle;
import org.glassfish.jersey.server.ExtendedUriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
/**
* Gathers and reports HTTP request metrics at the Jetty container level, which sits above Jersey. In order to get
* templated Jersey request paths, it adds a {@link jakarta.ws.rs.container.ContainerResponseFilter}, in order to give
* itself access to the template. It is limited to {@link TrafficSource#HTTP} requests.
*
* @see MetricsRequestEventListener
*/
public class MetricsHttpEventHandler extends EventsHandler {
private static final Logger logger = LoggerFactory.getLogger(MetricsHttpEventHandler.class);
private static final Set<String> EXPECTED_HTTP_METHODS =
Set.of("GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH");
private final ClientReleaseManager clientReleaseManager;
private final Set<String> servletPaths;
// Use the same counter namespace as MetricsRequestEventListener for continuity
public static final String REQUEST_COUNTER_NAME = MetricsRequestEventListener.REQUEST_COUNTER_NAME;
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricsRequestEventListener.REQUESTS_BY_VERSION_COUNTER_NAME;
@VisibleForTesting
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME;
@VisibleForTesting
static final String REQUEST_BYTES_COUNTER_NAME = MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME;
@VisibleForTesting
static final String REQUEST_INFO_PROPERTY_NAME = MetricsHttpEventHandler.class.getName() + ".requestInfo";
@VisibleForTesting
static final String PATH_TAG = "path";
@VisibleForTesting
static final String METHOD_TAG = "method";
@VisibleForTesting
static final String STATUS_CODE_TAG = "status";
@VisibleForTesting
static final String TRAFFIC_SOURCE_TAG = "trafficSource";
private final MeterRegistry meterRegistry;
@VisibleForTesting
MetricsHttpEventHandler(
final Handler handler,
final MeterRegistry meterRegistry,
final ClientReleaseManager clientReleaseManager,
final Set<String> servletPaths) {
super(handler);
this.meterRegistry = meterRegistry;
this.clientReleaseManager = clientReleaseManager;
this.servletPaths = servletPaths;
}
/**
* Configure a {@link MetricsHttpEventHandler}
*
* @param environment A dropwizard {@link org.eclipse.jetty.util.component.Environment}
* @param meterRegistry The meter registry to register metrics with
* @param clientReleaseManager A {@link ClientReleaseManager} that determines what tags to include with metrics
* @param servletPaths An allow-list of paths to include in metric tags for requests that are handled by above
* Jersey
*/
public static void configure(final Environment environment, final MeterRegistry meterRegistry,
final ClientReleaseManager clientReleaseManager, final Set<String> servletPaths) {
// register a filter that will set the initial request info
environment.jersey().register(new SetInfoRequestFilter());
// hook into lifecycle events, to react to the Connector being added
environment.lifecycle().addEventListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStarting(LifeCycle event) {
if (event instanceof Server server) {
server.setHandler(
new MetricsHttpEventHandler(server.getHandler(), meterRegistry, clientReleaseManager, servletPaths));
}
}
});
}
private void onResponseFailure(Request request, int status, Throwable failure) {
if (failure instanceof org.eclipse.jetty.io.EofException) {
// the client disconnected early
return;
}
final RequestInfo requestInfo = getRequestInfo(request);
logger.warn("Response failure: {} {} ({}) [{}] ",
requestInfo.method,
requestInfo.path,
requestInfo.userAgent,
status,
failure);
}
@Override
public void onComplete(Request request, int status, HttpFields headers, Throwable failure) {
super.onComplete(request, status, headers, failure);
if (failure != null) {
onResponseFailure(request, status, failure);
}
final RequestInfo requestInfo = getRequestInfo(request);
@Nullable final UserAgent userAgent;
{
UserAgent parsedUserAgent;
try {
parsedUserAgent = UserAgentUtil.parseUserAgentString(requestInfo.userAgent);
} catch (final UnrecognizedUserAgentException e) {
parsedUserAgent = null;
}
userAgent = parsedUserAgent;
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
final List<Tag> tags = new ArrayList<>(5);
tags.add(Tag.of(PATH_TAG, requestInfo.path));
tags.add(Tag.of(METHOD_TAG, requestInfo.method));
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(status)));
tags.add(Tag.of(TRAFFIC_SOURCE_TAG, TrafficSource.HTTP.name().toLowerCase()));
tags.add(platformTag);
final Optional<Tag> maybeClientVersionTag =
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager);
maybeClientVersionTag.ifPresent(tags::add);
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(requestInfo.responseBytes);
meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(requestInfo.requestBytes);
maybeClientVersionTag.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
Tags.of(clientVersionTag, platformTag))
.increment());
}
@Override
protected void onRequestRead(final Request request, final Content.Chunk chunk) {
super.onRequestRead(request, chunk);
if (chunk != null) {
getRequestInfo(request).requestBytes += chunk.remaining();
}
}
@Override
protected void onResponseWrite(final Request request, final boolean last, final ByteBuffer content) {
super.onResponseWrite(request, last, content);
if (content != null) {
getRequestInfo(request).responseBytes += content.remaining();
}
}
private RequestInfo getRequestInfo(Request request) {
Object obj = request.getAttribute(REQUEST_INFO_PROPERTY_NAME);
if (obj != null && obj instanceof RequestInfo requestInfo) {
return requestInfo;
}
// Our ContainerResponseFilter has not run yet. It should eventually run, and will override the path we set here.
// It may not run if this is a websocket upgrade request, a request handled by jetty directly, or a higher priority
// filter aborted the request by throwing an exception, in which case we'll use this path. To avoid giving every
// incorrect path a unique tag we check against a configured list of paths that we know would skip the filter.
final RequestInfo newInfo = new RequestInfo(
Optional.ofNullable(request.getHttpURI().getPath()).filter(servletPaths::contains).orElse("unknown"),
normalizeMethod(request.getMethod()),
request.getHeaders().get(HttpHeaders.USER_AGENT));
request.setAttribute(REQUEST_INFO_PROPERTY_NAME, newInfo);
return newInfo;
}
@VisibleForTesting
static class RequestInfo {
private String path;
private final String method;
private final @Nullable String userAgent;
private long requestBytes;
private long responseBytes;
RequestInfo(@NotNull String path, @NotNull String method, @Nullable String userAgent) {
this.path = path;
this.method = method;
this.userAgent = userAgent;
this.requestBytes = 0;
this.responseBytes = 0;
}
@Override
public boolean equals(final Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
RequestInfo that = (RequestInfo) o;
return requestBytes == that.requestBytes && responseBytes == that.responseBytes && Objects.equals(path, that.path)
&& Objects.equals(method, that.method) && Objects.equals(userAgent, that.userAgent);
}
@Override
public int hashCode() {
return Objects.hash(path, method, userAgent, requestBytes, responseBytes);
}
}
@VisibleForTesting
static class SetInfoRequestFilter implements ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
// Construct the templated URI path. If no matching path is found, this will be ""
final String path = UriInfoUtil.getPathTemplate((ExtendedUriInfo) requestContext.getUriInfo());
final Object obj = requestContext.getProperty(REQUEST_INFO_PROPERTY_NAME);
if (obj != null && obj instanceof RequestInfo requestInfo) {
requestInfo.path = path;
} else {
requestContext.setProperty(REQUEST_INFO_PROPERTY_NAME,
new RequestInfo(path, requestContext.getMethod(), requestContext.getHeaderString(HttpHeaders.USER_AGENT)));
}
}
}
static String normalizeMethod(@Nullable final String method) {
if (StringUtils.isBlank(method)) {
return "unknown";
}
return EXPECTED_HTTP_METHODS.contains(method.toUpperCase(Locale.ROOT)) ? method : "unknown";
}
}
@@ -31,7 +31,7 @@ import org.whispersystems.websocket.WebSocketResourceProvider;
/**
* Gathers and reports request-level metrics for WebSocket traffic only.
* For HTTP traffic, use {@link MetricsHttpChannelListener}.
* For HTTP traffic, use {@link MetricsHttpEventHandler}.
*/
public class MetricsRequestEventListener implements RequestEventListener {
@@ -69,7 +69,7 @@ public class MetricsRequestEventListener implements RequestEventListener {
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
if (trafficSource == TrafficSource.HTTP) {
logger.warn("Use {} for HTTP traffic", MetricsHttpChannelListener.class.getName());
logger.warn("Use {} for HTTP traffic", MetricsHttpEventHandler.class.getName());
}
}
@@ -107,7 +107,7 @@ public class MetricsRequestEventListener implements RequestEventListener {
final List<Tag> tags = new ArrayList<>();
tags.add(Tag.of(PATH_TAG, UriInfoUtil.getPathTemplate(event.getUriInfo())));
tags.add(Tag.of(METHOD_TAG, MetricsHttpChannelListener.normalizeMethod(event.getContainerRequest().getMethod())));
tags.add(Tag.of(METHOD_TAG, MetricsHttpEventHandler.normalizeMethod(event.getContainerRequest().getMethod())));
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(Optional
.ofNullable(event.getContainerResponse())
.map(ContainerResponse::getStatus)
@@ -21,7 +21,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.PathResourceFactory;
import org.eclipse.jetty.util.security.CertificateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,7 +37,7 @@ public class TlsCertificateExpirationUtil {
final KeyStore keyStore;
try {
keyStore = CertificateUtils.getKeyStore(Resource.newResource(keyStorePath), keyStoreType, keyStoreProvider,
keyStore = CertificateUtils.getKeyStore(new PathResourceFactory().newResource(keyStorePath), keyStoreType, keyStoreProvider,
keyStorePassword);
} catch (Exception e) {
@@ -26,6 +26,8 @@ import javax.annotation.Nullable;
import kotlin.Pair;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
@@ -36,6 +38,7 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.spam.MessageDeliveryListener;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.Util;
@@ -54,12 +57,12 @@ public class MessageSender {
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final List<MessageDeliveryListener> messageDeliveryListeners = new ArrayList<>();
// Note that these names deliberately reference `MessageController` for metric continuity
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageSender.class, "rejectOversizeMessage");
private static final String OVERSIZE_MESSAGE_WARNING_COUNTER_NAME = name(MessageSender.class, "oversizeMessageWarning");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageSender.class, "messageContentSize");
private static final String EMPTY_MESSAGE_LIST_COUNTER_NAME = MetricsUtil.name(MessageSender.class, "emptyMessageList");
@@ -73,16 +76,17 @@ public class MessageSender {
private static final String SYNC_MESSAGE_TAG_NAME = "sync";
@VisibleForTesting
public static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
private static final int OVERSIZE_MESSAGE_WARNING_THRESHOLD = (int) DataSize.kibibytes(96).toBytes();
public static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(96).toBytes();
@VisibleForTesting
static final byte NO_EXCLUDED_DEVICE_ID = -1;
public MessageSender(final MessagesManager messagesManager, final PushNotificationManager pushNotificationManager) {
public MessageSender(final MessagesManager messagesManager,
final PushNotificationManager pushNotificationManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.messagesManager = messagesManager;
this.pushNotificationManager = pushNotificationManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public void addMessageDeliveryListener(final MessageDeliveryListener messageDeliveryListener) {
@@ -112,7 +116,12 @@ public class MessageSender {
final Map<Byte, Envelope> messagesByDeviceId,
final Map<Byte, Integer> registrationIdsByDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Byte> syncMessageSenderDeviceId,
@Nullable final String userAgent) throws MismatchedDevicesException, MessageTooLargeException {
@Nullable final String userAgent)
throws MismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().isReadOnly()) {
throw new MessageDeliveryNotAllowedException();
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
@@ -189,7 +198,12 @@ public class MessageSender {
final boolean isStory,
final boolean isEphemeral,
final boolean isUrgent,
@Nullable final String userAgent) throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
@Nullable final String userAgent)
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().isReadOnly()) {
throw new MessageDeliveryNotAllowedException();
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
@@ -358,14 +372,6 @@ public class MessageSender {
.register(Metrics.globalRegistry)
.record(contentLength);
if (contentLength > OVERSIZE_MESSAGE_WARNING_THRESHOLD) {
Metrics.counter(OVERSIZE_MESSAGE_WARNING_COUNTER_NAME, Tags.of(platformTag,
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.increment();
}
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(platformTag,
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
@@ -3,6 +3,7 @@ package org.whispersystems.textsecuregcm.redis;
import com.google.common.annotations.VisibleForTesting;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.MaintNotificationsConfig;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisException;
import io.lettuce.core.RedisURI;
@@ -57,20 +58,10 @@ public class FaultTolerantRedisClient {
this.name = name;
// Lettuce will issue a CLIENT SETINFO command unconditionally if these fields are set (and they are by default),
// which can generate a bunch of spurious warnings in versions of Redis before 7.2.0.
//
// See:
//
// - https://github.com/redis/lettuce/pull/2823
// - https://github.com/redis/lettuce/issues/2817
redisUri.setClientName(null);
redisUri.setLibraryName(null);
redisUri.setLibraryVersion(null);
this.redisClient = RedisClient.create(clientResourcesBuilder.build(), redisUri);
final ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder()
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
.maintNotificationsConfig(MaintNotificationsConfig.disabled())
// for asynchronous commands
.timeoutOptions(TimeoutOptions.builder()
.fixedTimeout(commandTimeout)
@@ -9,6 +9,7 @@ import io.github.resilience4j.core.IntervalFunction;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.MaintNotificationsConfig;
import io.lettuce.core.RedisException;
import io.lettuce.core.RedisURI;
import io.lettuce.core.TimeoutOptions;
@@ -69,28 +70,15 @@ public class FaultTolerantRedisClusterClient {
this.name = name;
// Lettuce will issue a CLIENT SETINFO command unconditionally if these fields are set (and they are by default),
// which can generate a bunch of spurious warnings in versions of Redis before 7.2.0.
//
// See:
//
// - https://github.com/redis/lettuce/pull/2823
// - https://github.com/redis/lettuce/issues/2817
redisUris.forEach(redisUri -> {
redisUri.setClientName(null);
redisUri.setLibraryName(null);
redisUri.setLibraryVersion(null);
});
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker =
new LettuceShardCircuitBreaker(name, circuitBreakerConfigurationName);
this.clusterClient = RedisClusterClient.create(
clientResourcesBuilder.nettyCustomizer(lettuceShardCircuitBreaker).
build(),
clientResourcesBuilder.nettyCustomizer(lettuceShardCircuitBreaker)
.build(),
redisUris);
final ClusterClientOptions.Builder clusterClientOptionsBuilder = ClusterClientOptions.builder()
final ClusterClientOptions.Builder clusterClientOptionsBuilder = (ClusterClientOptions.Builder) ClusterClientOptions.builder()
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
.validateClusterNodeMembership(false)
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
@@ -100,7 +88,8 @@ public class FaultTolerantRedisClusterClient {
.timeoutOptions(TimeoutOptions.builder()
.fixedTimeout(commandTimeout)
.build())
.publishOnScheduler(true);
.publishOnScheduler(true)
.maintNotificationsConfig(MaintNotificationsConfig.disabled());
NettyUtil.setSocketTimeoutsIfApplicable(clusterClientOptionsBuilder);
@@ -4,16 +4,29 @@
*/
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -80,7 +93,9 @@ public class Account {
private IdentityKey phoneNumberIdentityKey;
@JsonProperty("cpv")
private String currentProfileVersion;
@JsonSerialize(using = ProfileVersionAdapter.Serializing.class)
@JsonDeserialize(using = ProfileVersionAdapter.Deserializing.class)
private byte[] currentProfileVersion;
@JsonProperty
private List<AccountBadge> badges = new ArrayList<>();
@@ -323,13 +338,13 @@ public class Account {
.orElse(0L);
}
public Optional<String> getCurrentProfileVersion() {
public Optional<byte[]> getCurrentProfileVersion() {
requireNotStale();
return Optional.ofNullable(currentProfileVersion);
}
public void setCurrentProfileVersion(final String currentProfileVersion) {
public void setCurrentProfileVersion(final byte[] currentProfileVersion) {
requireNotStale();
this.currentProfileVersion = currentProfileVersion;
@@ -564,4 +579,29 @@ public class Account {
logger.error("Accessor called on stale account", new RuntimeException());
}
}
private static class ProfileVersionAdapter {
private static class Deserializing extends JsonDeserializer<byte[]> {
private static final String CURRENT_PROFILE_VERSION_FORMAT_COUNTER_NAME = name(Account.class, "currentProfileMetricDeserialized");
@Override
public byte[] deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
final String val = jsonParser.getValueAsString();
Metrics.counter(CURRENT_PROFILE_VERSION_FORMAT_COUNTER_NAME, Tags.of("format", val.length() == 64 ? "hex" : "base64")).increment();
if (val.length() == 64) {
return HexFormat.of().parseHex(val);
} else {
return Base64.getDecoder().decode(val);
}
}
}
// after deploying this once we can get rid of it in favor of the default base64
private static class Serializing extends JsonSerializer<byte[]> {
@Override
public void serialize(byte[] bytes, JsonGenerator jsonGenerator, SerializerProvider serializaterProvider) throws IOException {
jsonGenerator.writeString(HexFormat.of().formatHex(bytes));
}
}
}
}
@@ -1673,7 +1673,13 @@ public class Accounts {
accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute);
}
account.setNumber(item.get(ATTR_ACCOUNT_E164).s(), phoneNumberIdentifierFromAttribute);
final String attributeNumber = item.get(ATTR_ACCOUNT_E164).s();
if (account.getNumber() == null || !account.getNumber().equals(attributeNumber)) {
log.error("Missing or mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getNumber(), attributeNumber);
}
account.setNumber(attributeNumber, phoneNumberIdentifierFromAttribute);
account.setUuid(accountIdentifier);
account.setUsernameHash(AttributeValues.getByteArray(item, ATTR_USERNAME_HASH, null));
account.setUsernameLinkHandle(AttributeValues.getUUID(item, ATTR_USERNAME_LINK_UUID, null));
@@ -39,6 +39,7 @@ import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
@@ -127,6 +128,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final KeysManager keysManager;
private final MessagesManager messagesManager;
private final ProfilesManager profilesManager;
private final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager;
private final SecureStorageClient secureStorageClient;
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final DisconnectionRequestManager disconnectionRequestManager;
@@ -208,7 +210,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final AccountLockManager accountLockManager,
final KeysManager keysManager,
final MessagesManager messagesManager,
final ProfilesManager profilesManager,
final ProfilesManager profilesManager, final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager,
final SecureStorageClient secureStorageClient,
final SecureValueRecoveryClient secureValueRecovery2Client,
final DisconnectionRequestManager disconnectionRequestManager,
@@ -225,6 +227,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.keysManager = keysManager;
this.messagesManager = messagesManager;
this.profilesManager = profilesManager;
this.changeNumberWaitingPeriodManager = changeNumberWaitingPeriodManager;
this.secureStorageClient = secureStorageClient;
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.disconnectionRequestManager = disconnectionRequestManager;
@@ -414,6 +417,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.join())
.orElse(false);
changeNumberWaitingPeriodManager.handleAccountCreated(account.getUuid(), clock.instant());
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
@@ -957,6 +961,40 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
/// Using a pessimistic lock, updates the current profile version to `newVersion` if `currentProfileVersion` matches
/// `expectedCurrentVersion`. The caller may provide a supplementary `Consumer<Account>` for additional updates
///
/// @throws WriteConflictException if the expected current version does not match the current version
public Account updateCurrentProfileVersion(final UUID accountIdentifier, final byte[] newVersion,
final byte[] expectedCurrentVersion, final Consumer<Account> updater) throws WriteConflictException {
Objects.requireNonNull(expectedCurrentVersion, "expectedCurrentVersion");
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
final Account maybeUpdatedAccount = update(accountIdentifier, a -> {
if (!a.getCurrentProfileVersion().orElse(new byte[0]).equals(expectedCurrentVersion)) {
return false;
}
a.setCurrentProfileVersion(newVersion);
updater.accept(a);
return true;
});
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> v.equals(newVersion)).orElse(false)) {
throw new WriteConflictException();
}
return maybeUpdatedAccount;
}, accountLockExecutor);
}
/**
* Specialized version of {@link #updateDevice(UUID, byte, Consumer)} that minimizes potentially contentious and
* redundant updates of {@code device.lastSeen}
@@ -4,23 +4,28 @@
*/
package org.whispersystems.textsecuregcm.storage;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.net.HttpHeaders;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.container.ContainerRequestContext;
import java.time.Clock;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -35,9 +40,6 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.util.Pair;
import javax.annotation.Nullable;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class ChangeNumberManager {
@@ -45,6 +47,7 @@ public class ChangeNumberManager {
private final AccountsManager accountsManager;
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager;
private final RateLimiters rateLimiters;
private final Clock clock;
@@ -53,6 +56,8 @@ public class ChangeNumberManager {
// Note that this counter name references another class deliberately in the interest of metric continuity
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
private static final String POST_REGISTRATION_WAITING_PERIOD_NOT_MET_COUNTER_NAME = name(ChangeNumberManager.class,
"postRegistrationWaitingPeriodNotMet");
public ChangeNumberManager(
final MessageSender messageSender,
@@ -60,6 +65,7 @@ public class ChangeNumberManager {
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters,
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager,
final Clock clock) {
this.messageSender = messageSender;
@@ -67,6 +73,7 @@ public class ChangeNumberManager {
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
this.changeNumberWaitingPeriodManager = changeNumberWaitingPeriodManager;
this.clock = clock;
}
@@ -81,7 +88,7 @@ public class ChangeNumberManager {
final List<IncomingMessage> deviceMessages,
final Map<Byte, Integer> pniRegistrationIds,
final ContainerRequestContext containerRequestContext)
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException {
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException {
final String senderUserAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
@@ -92,6 +99,13 @@ public class ChangeNumberManager {
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumber().equals(number)) {
final Optional<Duration> waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getUuid());
if (waitingPeriodRemaining.isPresent()) {
Metrics.counter(POST_REGISTRATION_WAITING_PERIOD_NOT_MET_COUNTER_NAME).increment();
throw new RateLimitExceededException(waitingPeriodRemaining.get());
}
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType =
@@ -0,0 +1,43 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
/// Manages post-registration change number waiting period expiration data
public class ChangeNumberWaitingPeriodManager {
private final ChangeNumberWaitingPeriods changeNumberWaitingPeriods;
private final Duration waitingPeriod;
private final Clock clock;
public ChangeNumberWaitingPeriodManager(final ChangeNumberWaitingPeriods changeNumberWaitingPeriods,
final Duration waitingPeriod, final Clock clock) {
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
this.waitingPeriod = waitingPeriod;
this.clock = clock;
}
/// Must be called when an account is created, including re-registration
@VisibleForTesting
public void handleAccountCreated(final UUID aci, final Instant created) {
changeNumberWaitingPeriods.setExpiration(aci, created.plus(waitingPeriod));
}
/// Returns the waiting period duration remaining, if any. If present, {@code duration} will always be positive.
Optional<Duration> getWaitingPeriodRemaining(final UUID aci) {
return changeNumberWaitingPeriods.getExpiration(aci)
.flatMap(expiration -> {
final Duration remaining = Duration.between(clock.instant(), expiration);
return remaining.isPositive() ? Optional.of(remaining) : Optional.empty();
});
}
}
@@ -0,0 +1,69 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
public class ChangeNumberWaitingPeriods {
// hash key; bytes
static final String KEY_ACCOUNT_UUID = "U";
// expiration timestamp in epoch seconds; number
static final String ATTR_TTL = "E";
private final String tableName;
private final DynamoDbClient dynamoDbClient;
public ChangeNumberWaitingPeriods(final String tableName, final DynamoDbClient dynamoDbClient) {
this.tableName = tableName;
this.dynamoDbClient = dynamoDbClient;
}
public void setExpiration(final UUID aci, final Instant expiration) {
dynamoDbClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(aci),
ATTR_TTL, AttributeValues.fromLong(expiration.getEpochSecond())))
.build());
}
public Optional<Instant> getExpiration(final UUID aci) {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(aci)))
.consistentRead(true)
.build());
if (!response.hasItem()) {
return Optional.empty();
}
return AttributeValues.get(response.item(), ATTR_TTL)
.map(AttributeValue::n)
.map(Long::parseLong)
.map(Instant::ofEpochSecond)
.filter(instant -> instant.isAfter(Instant.now()));
}
@VisibleForTesting
public void delete(final UUID aci) {
dynamoDbClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(aci)))
.build());
}
}
@@ -15,7 +15,8 @@ public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true);
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false);
public enum AccountCapabilityMode {
/**
@@ -5,7 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
public class KeyIdUtil {
public static final long MAX_KEY_ID = (1L << 32) - 1;
public static final long MAX_KEY_ID = (1L << 31) - 1;
public static final long MIN_KEY_ID = 0;
private KeyIdUtil(){}
@@ -19,9 +19,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@@ -31,6 +29,8 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.Update;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
public class Profiles {
@@ -93,7 +93,7 @@ public class Profiles {
this.tableName = tableName;
}
public void set(final UUID uuid, final VersionedProfile profile) {
public void set(final UUID uuid, final VersionedProfileV1 profile) {
SET_PROFILES_TIMER.record(() -> {
dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
@@ -105,16 +105,17 @@ public class Profiles {
});
}
public CompletableFuture<Void> setAsync(final UUID uuid, final VersionedProfile profile) {
return AsyncTimerUtil.record(SET_PROFILES_TIMER, () -> dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
/// Used to update a profile during the v2 migration.
public TransactWriteItem getTransactWriteItem(final UUID uuid, final VersionedProfileV1 profile) {
return TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, profile.version()))
.updateExpression(buildUpdateExpression(profile))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
.build()
).thenRun(Util.NOOP)
).toCompletableFuture();
.build())
.build();
}
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final String version) {
@@ -124,7 +125,7 @@ public class Profiles {
}
@VisibleForTesting
static String buildUpdateExpression(final VersionedProfile profile) {
static String buildUpdateExpression(final VersionedProfileV1 profile) {
final List<String> updatedAttributes = new ArrayList<>(5);
final List<String> deletedAttributes = new ArrayList<>(5);
@@ -186,7 +187,7 @@ public class Profiles {
}
@VisibleForTesting
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfile profile) {
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile) {
final Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.commitment()));
@@ -217,7 +218,7 @@ public class Profiles {
return expressionValues;
}
public Optional<VersionedProfile> get(final UUID uuid, final String version) {
public Optional<VersionedProfileV1> get(final UUID uuid, final String version) {
return GET_PROFILE_TIMER.record(() -> {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
@@ -229,19 +230,8 @@ public class Profiles {
});
}
public CompletableFuture<Optional<VersionedProfile>> getAsync(final UUID uuid, final String version) {
return AsyncTimerUtil.record(GET_PROFILE_TIMER, () -> dynamoDbAsyncClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.consistentRead(true)
.build())
.thenApply(response ->
response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.<VersionedProfile>empty())
).toCompletableFuture();
}
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfile(
private static VersionedProfileV1 fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfileV1(
AttributeValues.getString(item, ATTR_VERSION, null),
getBytes(item, ATTR_NAME),
AttributeValues.getString(item, ATTR_AVATAR, null),
@@ -11,8 +11,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.RedisException;
import io.lettuce.core.ScriptOutputType;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -21,12 +23,13 @@ import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
@@ -35,39 +38,90 @@ public class ProfilesManager {
private final Logger logger = LoggerFactory.getLogger(ProfilesManager.class);
private static final String CACHE_PREFIX_V1 = "profiles_v1::";
private static final String CACHE_PREFIX_V2 = "profiles_v2::";
private final Profiles profiles;
private static final byte[] EMPTY = new byte[0];
private final Profiles profilesV1;
private final ProfilesV2 profilesV2;
private final FaultTolerantRedisClusterClient cacheCluster;
private final ScheduledExecutorService retryExecutor;
private final S3AsyncClient s3Client;
private final String bucket;
private final ClusterLuaScript setLuaScript;
private final ObjectMapper mapper;
private static final String RETRY_NAME = ResilienceUtil.name(ProfilesManager.class);
private static final String DELETE_AVATAR_COUNTER_NAME = name(ProfilesManager.class, "deleteAvatar");
public ProfilesManager(final Profiles profiles,
public ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket) {
this.profiles = profiles;
final String bucket) throws IOException {
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
}
@VisibleForTesting
ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket,
final ClusterLuaScript setLuaScript) {
this.profilesV1 = profilesV1;
this.profilesV2 = profilesV2;
this.cacheCluster = cacheCluster;
this.retryExecutor = retryExecutor;
this.s3Client = s3Client;
this.bucket = bucket;
this.setLuaScript = setLuaScript;
this.mapper = SystemMapper.jsonMapper();
}
public void set(UUID uuid, VersionedProfile versionedProfile) {
redisSet(uuid, versionedProfile);
profiles.set(uuid, versionedProfile);
public void setV1(UUID uuid, VersionedProfileV1 versionedProfile) {
redisDelete(uuid);
profilesV1.set(uuid, versionedProfile);
redisSet(uuid, null, versionedProfile);
try {
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
// downgrades to v1, all v2 profiles are stale
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
profilesV2.deleteAll(uuid);
} catch (final Exception e) {
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
}
}
public CompletableFuture<Void> setAsync(UUID uuid, VersionedProfile versionedProfile) {
return profiles.setAsync(uuid, versionedProfile)
.thenCompose(ignored -> redisSetAsync(uuid, versionedProfile));
/// Transactionally sets v1 and v2 Profile data in DynamoDB.
///
/// Note: writes to the Redis cache are not transactional, and a failed DynamoDB write may leave incorrect data in Redis
/// @throws WriteConflictException if the expected data hash does not match the stored data hash
public void set(UUID uuid, VersionedProfileV1 versionedProfileV1, VersionedProfile versionedProfile, @Nullable byte[] expectedCurrentDataHash) throws WriteConflictException {
final TransactWriteItem v1TransactWriteItem = profilesV1.getTransactWriteItem(uuid, versionedProfileV1);
redisDelete(uuid);
profilesV2.set(uuid,
versionedProfile.version(),
versionedProfile.data(),
versionedProfile.dataHash(),
versionedProfile.commitment(),
versionedProfile.paymentAddress(),
versionedProfile.paymentAddressHash(),
expectedCurrentDataHash,
v1TransactWriteItem);
redisSet(uuid, versionedProfile, versionedProfileV1);
}
/**
@@ -78,7 +132,7 @@ public class ProfilesManager {
*/
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
final CompletableFuture<Void> profilesAndAvatars = Mono.fromFuture(profiles.deleteAll(uuid))
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
.flatMapIterable(Function.identity())
.flatMap(avatar ->
Mono.fromFuture(includeAvatar ? deleteAvatar(avatar) : CompletableFuture.completedFuture(null))
@@ -87,7 +141,7 @@ public class ProfilesManager {
.onErrorComplete())
.then().toFuture();
return CompletableFuture.allOf(redisDelete(uuid), profilesAndAvatars);
return CompletableFuture.allOf(redisDeleteAsync(uuid), profilesV1AndAvatars, profilesV2.deleteAll(uuid));
}
public CompletableFuture<Void> deleteAvatar(String avatar) {
@@ -110,87 +164,99 @@ public class ProfilesManager {
.thenRun(Util.NOOP);
}
public Optional<VersionedProfile> get(UUID uuid, String version) {
Optional<VersionedProfile> profile = redisGet(uuid, version);
if (profile.isEmpty()) {
profile = profiles.get(uuid, version);
public Optional<VersionedProfileV1> getV1(UUID uuid, String version) {
return redisGetV1(uuid, version).or(() -> {
final Optional<VersionedProfileV1> profile = profilesV1.get(uuid, version);
try {
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile));
profile.ifPresent(versionedProfile -> redisSet(uuid, null, versionedProfile));
} catch (RedisException e) {
logger.warn("Failed to cache retrieved profile", e);
}
}
return profile;
return profile;
});
}
public CompletableFuture<Optional<VersionedProfile>> getAsync(UUID uuid, String version) {
return redisGetAsync(uuid, version)
.thenCompose(maybeVersionedProfile -> maybeVersionedProfile
.map(versionedProfile -> CompletableFuture.completedFuture(maybeVersionedProfile))
.orElseGet(() -> profiles.getAsync(uuid, version)
.thenCompose(maybeVersionedProfileFromDynamo -> maybeVersionedProfileFromDynamo
.map(profile -> redisSetAsync(uuid, profile)
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
logger.warn("Failed to cache retrieved profile", e);
return null;
}))
.thenApply(ignored -> maybeVersionedProfileFromDynamo))
.orElseGet(() -> CompletableFuture.completedFuture(maybeVersionedProfileFromDynamo)))));
public Optional<VersionedProfile> get(UUID uuid, byte[] version) {
return redisGet(uuid, version).or(() -> {
final Optional<VersionedProfile> profile = profilesV2.get(uuid, version);
try {
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile, null));
} catch (RedisException e) {
logger.warn("Failed to cache retrieved profile", e);
}
return profile;
});
}
private void redisSet(UUID uuid, VersionedProfile profile) {
@VisibleForTesting
void redisSet(UUID uuid, @Nullable VersionedProfile v2Profile, @Nullable VersionedProfileV1 v1Profile) {
try {
final byte[] profileJson = mapper.writeValueAsBytes(profile);
if (v1Profile == null && v2Profile == null) {
logger.error("Expected at least one profile");
return;
}
final byte[] v1ProfileVersion;
final byte[] v1ProfileBytes;
if (v1Profile != null) {
v1ProfileVersion = v1Profile.version().getBytes();
v1ProfileBytes = mapper.writeValueAsBytes(v1Profile);
} else {
v1ProfileVersion = EMPTY;
v1ProfileBytes = EMPTY;
}
final byte[] v2ProfileVersion;
final byte[] v2ProfileBytes;
if (v2Profile != null) {
v2ProfileVersion = v2Profile.version();
v2ProfileBytes = mapper.writeValueAsBytes(v2Profile);
} else {
v2ProfileVersion = EMPTY;
v2ProfileBytes = EMPTY;
}
setLuaScript.executeBinary(List.of(getCacheKeyV1(uuid), getCacheKeyV2(uuid)),
List.of(v1ProfileVersion, v1ProfileBytes, v2ProfileVersion, v2ProfileBytes));
cacheCluster.useBinaryCluster(connection -> connection.sync().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
private CompletableFuture<Void> redisSetAsync(UUID uuid, VersionedProfile profile) {
final byte[] profileJson;
private Optional<VersionedProfile> redisGet(UUID uuid, byte[] version) {
try {
profileJson = mapper.writeValueAsBytes(profile);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV2(uuid), version));
return cacheCluster.withBinaryCluster(connection ->
connection.async().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson)).toCompletableFuture()
.thenRun(Util.NOOP)
.toCompletableFuture();
return parseProfileJson(json, VersionedProfile.class);
} catch (RedisException e) {
logger.warn("Redis exception", e);
return Optional.empty();
}
}
private Optional<VersionedProfile> redisGet(UUID uuid, String version) {
@VisibleForTesting
static byte[] getCacheKeyV2(UUID uuid) {
return (CACHE_PREFIX_V2 + '{' + uuid.toString() + '}').getBytes();
}
private Optional<VersionedProfileV1> redisGetV1(UUID uuid, String version) {
try {
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV1(uuid), version.getBytes()));
return parseProfileJson(json);
return parseProfileJson(json, VersionedProfileV1.class);
} catch (RedisException e) {
logger.warn("Failed to retrieve profile from cache", e);
return Optional.empty();
}
}
private CompletableFuture<Optional<VersionedProfile>> redisGetAsync(UUID uuid, String version) {
return cacheCluster.withBinaryCluster(connection ->
connection.async().hget(getCacheKeyV1(uuid), version.getBytes()))
.thenApply(this::parseProfileJson)
.exceptionally(throwable -> {
logger.warn("Failed to read versioned profile from Redis", throwable);
return Optional.empty();
})
.toCompletableFuture();
}
private Optional<VersionedProfile> parseProfileJson(@Nullable final byte[] maybeJson) {
private <T> Optional<T> parseProfileJson(@Nullable final byte[] maybeJson, Class<T> klass) {
try {
if (maybeJson != null) {
return Optional.of(mapper.readValue(maybeJson, VersionedProfile.class));
return Optional.of(mapper.readValue(maybeJson, klass));
}
return Optional.empty();
} catch (final IOException e) {
@@ -199,10 +265,17 @@ public class ProfilesManager {
}
}
private CompletableFuture<Void> redisDelete(UUID uuid) {
private void redisDelete(UUID uuid) {
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeRunnable(() -> cacheCluster.withBinaryCluster(
connection -> connection.sync().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))));
}
private CompletableFuture<Void> redisDeleteAsync(UUID uuid) {
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid))))
.executeCompletionStage(retryExecutor,
() -> cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))))
.toCompletableFuture()
.thenRun(Util.NOOP);
}
@@ -0,0 +1,342 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.Arrays;
import java.util.HashMap;
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 javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
import software.amazon.awssdk.services.dynamodb.model.Update;
public class ProfilesV2 {
private static final String CONDITIONAL_CHECK_FAILED_CODE = "ConditionalCheckFailed";
private static final String TRANSACTION_CONFLICT_CODE = "TransactionConflict";
private final DynamoDbClient dynamoDbClient;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
// UUID of the account that owns this profile; hash key; byte array
@VisibleForTesting
static final String KEY_ACCOUNT_UUID = "U";
// Version of this profile; sort key; byte array
@VisibleForTesting
static final String KEY_VERSION = "V";
// Profile data (serialized ciphertext); byte array
private static final String ATTR_DATA = "D";
// SHA-256 hash of data attribute; byte array
private static final String ATTR_DATA_HASH = "DH";
// Commitment; byte array
private static final String ATTR_COMMITMENT = "C";
// Payment address; byte array
private static final String ATTR_PAYMENT_ADDRESS = "P";
// SHA-256 hash of payment address attribute; byte array
private static final String ATTR_PAYMENT_ADDRESS_HASH = "PH";
private static final Map<String, String> UPDATE_EXPRESSION_ATTRIBUTE_NAMES = Map.of(
"#data", ATTR_DATA,
"#dataHash", ATTR_DATA_HASH,
"#commitment", ATTR_COMMITMENT,
"#paymentAddress", ATTR_PAYMENT_ADDRESS,
"#paymentAddressHash", ATTR_PAYMENT_ADDRESS_HASH);
private static final Timer SET_PROFILES_TIMER = Metrics.timer(name(ProfilesV2.class, "set"));
private static final Timer GET_PROFILE_TIMER = Metrics.timer(name(ProfilesV2.class, "get"));
private static final String DELETE_PROFILES_TIMER_NAME = name(ProfilesV2.class, "delete");
private static final String WRITE_CONFLICTS_COUNTER_NAME = name(ProfilesV2.class, "writeConflicts");
private static final int COMMITMENT_LENGTH = 97;
private static final int DELETE_MAX_CONCURRENCY = 32;
public ProfilesV2(final DynamoDbClient dynamoDbClient,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName) {
this.dynamoDbClient = dynamoDbClient;
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
}
/// Put a profile version with the given data
///
/// During the migration from v1 &rarr; v2, both updates are executed transactionally
///
/// @param uuid the account UUID
/// @param version the profile version
/// @param data serialized profile ciphertext
/// @param commitment serialized profile key commitment (required for initial write, optional for updates)
/// @param paymentAddress serialized payment address ciphertext (nullable)
/// @param expectedCurrentDataHash the expected current data hash, used for conditional update (nullable for the initial write)
/// @param profileV1TransactWriteItem transact write item for v1 profile during migration
/// @throws WriteConflictException if the expected data hash does not match the stored data hash
/// @throws IllegalArgumentException if commitment is null on initial write or commitment does not match on an update
/// @throws IllegalStateException if commitment is missing after a write
public void set(final UUID uuid,
final byte[] version,
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash,
final TransactWriteItem profileV1TransactWriteItem) throws WriteConflictException {
// Commitment is required for initial write (when expectedCurrentDataHash is null)
if (expectedCurrentDataHash == null && commitment == null) {
throw new IllegalArgumentException("Commitment is required for initial write");
}
final Timer.Sample sample = Timer.start();
try {
final List<TransactWriteItem> transactWriteItems = List.of(
getTransactWriteItem(uuid, version, data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash),
profileV1TransactWriteItem);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
} catch (TransactionCanceledException e) {
if (e.hasCancellationReasons()) {
// check for fields with conditional check failures
if (e.cancellationReasons().getFirst() != null
&& e.cancellationReasons().getFirst().code().equals(CONDITIONAL_CHECK_FAILED_CODE)
&& e.cancellationReasons().getFirst().hasItem()) {
final Map<String, AttributeValue> item = e.cancellationReasons().getFirst().item();
final byte[] oldCommitment = AttributeValues.getByteArray(item, ATTR_COMMITMENT, null);
if (oldCommitment != null && commitment != null && !Arrays.equals(oldCommitment, commitment)) {
throw new IllegalArgumentException("Commitment is immutable");
}
if (oldCommitment == null && commitment == null) {
throw new IllegalStateException("Commitment is absent from existing profile");
}
}
final Optional<String> cancellationCode = e.cancellationReasons().stream()
.map(CancellationReason::code)
.filter(code -> CONDITIONAL_CHECK_FAILED_CODE.equals(code) || TRANSACTION_CONFLICT_CODE.equals(code))
.findFirst();
if (cancellationCode.isPresent()) {
// any other conditional check failure is an expected data hash mismatch, which is a write conflict
Metrics.counter(WRITE_CONFLICTS_COUNTER_NAME, "code", cancellationCode.get()).increment();
throw new WriteConflictException();
}
}
throw e;
} finally {
sample.stop(SET_PROFILES_TIMER);
}
}
/// Get a [TransactWriteItem] for a profile update during the v2 migration
///
/// @param uuid the account UUID
/// @param version the profile version
/// @param data the serialized profile ciphertext
/// @param dataHash the serialized profile ciphertext hash
/// @param commitment the profile key commitment (required for initial write, optional for updates)
/// @param paymentAddress the payment address (nullable; will clear existing value for this version if null)
/// @param paymentAddressHash the payment address hash (nullable; will clear existing value for this version if null)
/// @param expectedCurrentDataHash the expected current data hash for conditional update (nullable for first write)
/// @return a [TransactWriteItem] containing the Update operation
@VisibleForTesting
TransactWriteItem getTransactWriteItem(final UUID uuid,
final byte[] version,
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash) {
return TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.updateExpression(buildUpdateExpression(commitment != null, paymentAddress != null))
.conditionExpression(buildConditionExpression(commitment != null, expectedCurrentDataHash != null))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build();
}
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final byte[] version) {
return Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
KEY_VERSION, AttributeValues.fromByteArray(version));
}
@VisibleForTesting
static String buildUpdateExpression(final boolean hasCommitment, final boolean hasPaymentAddress) {
final StringBuilder updateExpressionBuilder = new StringBuilder("SET #data = :data, #dataHash = :dataHash");
if (hasCommitment) {
updateExpressionBuilder.append(", #commitment = if_not_exists(#commitment, :commitment)");
}
if (hasPaymentAddress) {
updateExpressionBuilder.append(", #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash");
} else {
updateExpressionBuilder.append(" REMOVE #paymentAddress, #paymentAddressHash");
}
return updateExpressionBuilder.toString();
}
@VisibleForTesting
static String buildConditionExpression(final boolean hasCommitment, final boolean hasExpectedCurrentDataHash) {
final StringBuilder sb = new StringBuilder();
if (hasCommitment) {
sb.append("(attribute_not_exists(#commitment) OR #commitment = :commitment)");
} else {
sb.append("size(#commitment) = :commitment_length");
}
if (hasExpectedCurrentDataHash) {
// If expected hash is provided, verify it matches the stored hash
sb.append(" AND #dataHash = :expectedDataHash");
} else {
// Initial write: dataHash must not exist
sb.append(" AND attribute_not_exists(#dataHash)");
}
return sb.toString();
}
@VisibleForTesting
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash) {
final Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":data", AttributeValues.fromByteArray(data));
expressionValues.put(":dataHash", AttributeValues.fromByteArray(dataHash));
if (commitment != null) {
expressionValues.put(":commitment", AttributeValues.fromByteArray(commitment));
} else {
expressionValues.put(":commitment_length", AttributeValues.fromInt(COMMITMENT_LENGTH));
}
if (paymentAddress != null) {
expressionValues.put(":paymentAddress", AttributeValues.fromByteArray(paymentAddress));
expressionValues.put(":paymentAddressHash", AttributeValues.fromByteArray(paymentAddressHash));
}
if (expectedCurrentDataHash != null) {
expressionValues.put(":expectedDataHash", AttributeValues.fromByteArray(expectedCurrentDataHash));
}
return expressionValues;
}
/// Fetch a profile version
///
/// @param uuid the account UUID
/// @param version the profile version
/// @return the VersionedProfile, if found
public Optional<VersionedProfile> get(final UUID uuid, final byte[] version) {
return GET_PROFILE_TIMER.record(() -> {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.consistentRead(true)
.build());
return response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.empty();
});
}
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfile(
Objects.requireNonNull(AttributeValues.getByteArray(item, KEY_VERSION, null)),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA, null)),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA_HASH, null)),
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS, null),
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS_HASH, null),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_COMMITMENT, null)));
}
/// Deletes all profile versions for the given UUID.
///
/// @param uuid the account UUID
/// @return a CompletableFuture that completes when all versions have been deleted
public CompletableFuture<Void> deleteAll(final UUID uuid) {
final Timer.Sample sample = Timer.start();
final AttributeValue uuidAttributeValue = AttributeValues.fromUUID(uuid);
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(":uuid", uuidAttributeValue))
.projectionExpression(KEY_VERSION)
.consistentRead(true)
.build())
.items())
.flatMap(item -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_ACCOUNT_UUID, uuidAttributeValue,
KEY_VERSION, item.get(KEY_VERSION)))
.build())), DELETE_MAX_CONCURRENCY)
.then()
.doOnSuccess(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "success")))
.doOnError(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error")))
.toFuture();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
@@ -7,34 +7,77 @@ package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
public record VersionedProfile (String version,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
public record VersionedProfile(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] version,
@Nullable
String avatar,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] data,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] dataHash,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@Nullable
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] paymentAddress,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@Nullable
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] paymentAddressHash,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] phoneNumberSharing,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {}
public VersionedProfile(byte[] version, byte[] data, @Nullable byte[] paymentAddress, byte[] commitment) {
this(Objects.requireNonNull(version), Objects.requireNonNull(data), hash(Objects.requireNonNull(data)), paymentAddress, paymentAddress == null ? null : hash(paymentAddress), Objects.requireNonNull(commitment));
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof final VersionedProfile that))
return false;
return Arrays.equals(data, that.data) && Arrays.equals(version, that.version) && Arrays.equals(dataHash,
that.dataHash) && Arrays.equals(commitment, that.commitment) && Arrays.equals(paymentAddress,
that.paymentAddress) && Arrays.equals(paymentAddressHash, that.paymentAddressHash);
}
@Override
public int hashCode() {
return Objects.hash(
Arrays.hashCode(version),
Arrays.hashCode(data),
Arrays.hashCode(dataHash),
Arrays.hashCode(paymentAddress),
Arrays.hashCode(paymentAddressHash),
Arrays.hashCode(commitment));
}
/**
* Computes the SHA-256 hash of the given data.
*/
@VisibleForTesting
static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
}
}
@@ -0,0 +1,67 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
import java.util.Arrays;
import java.util.Objects;
public record VersionedProfileV1(String version,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
@Nullable
String avatar,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] phoneNumberSharing,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {
@Override
public boolean equals(final Object o) {
if (!(o instanceof final VersionedProfileV1 that))
return false;
return Arrays.equals(name, that.name) && Arrays.equals(about, that.about) && Objects.equals(avatar, that.avatar)
&& Objects.equals(version, that.version) && Arrays.equals(aboutEmoji, that.aboutEmoji) && Arrays.equals(
commitment, that.commitment) && Arrays.equals(paymentAddress, that.paymentAddress) && Arrays.equals(
phoneNumberSharing, that.phoneNumberSharing);
}
@Override
public int hashCode() {
return Objects.hash(
version,
Arrays.hashCode(name),
Objects.hashCode(avatar),
Arrays.hashCode(aboutEmoji),
Arrays.hashCode(about),
Arrays.hashCode(paymentAddress),
Arrays.hashCode(phoneNumberSharing),
Arrays.hashCode(commitment));
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class WriteConflictException extends NoStackTraceException {
}
@@ -1,92 +0,0 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import com.google.common.annotations.VisibleForTesting;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A closable epoch is a concurrency construct that measures the number of callers in some critical section. A closable
* epoch can be closed to prevent new callers from entering the critical section, and takes a specific action when the
* critical section is empty after closure.
*/
public class ClosableEpoch {
private final Runnable onCloseHandler;
private final AtomicInteger state = new AtomicInteger();
private static final int CLOSING_BIT_MASK = 0x00000001;
/**
* Constructs a new closable epoch that will execute the given handler when the epoch is closed and all callers have
* departed the critical section. The handler will be executed on the thread that calls {@link #close()} if the
* critical section is empty at the time of the call or on the last thread to call {@link #depart()} otherwise.
* Callers should provide handlers that delegate execution to a specific thread/executor if more precise control over
* which thread runs the handler is required.
*
* @param onCloseHandler a handler to run when the epoch is closed and all callers have departed the critical section
*/
public ClosableEpoch(final Runnable onCloseHandler) {
this.onCloseHandler = onCloseHandler;
}
/**
* Announces the arrival of a caller at the start of the critical section. If the caller is allowed to enter the
* critical section, the epoch's internal caller counter is incremented accordingly.
*
* @return {@code true} if the caller is allowed to enter the critical section or {@code false} if it is not allowed
* to enter the critical section because this epoch is closing
*/
public boolean tryArrive() {
// Increment the number of active callers if and only if we're not closing. We add 2 because the lowest bit encodes
// the "closing" state, and the bits above it encode the actual call count. More verbosely, we're doing
// `state += (1 << 1)` to avoid overwriting the closing state bit.
return !isClosing(state.updateAndGet(state -> isClosing(state) ? state : state + 2));
}
/**
* Announces the departure of a caller from the critical section. If the epoch is closing and the caller is the last
* to depart the critical section, then the epoch will fire its {@code onCloseHandler}.
*/
public void depart() {
// Decrement the active caller count unconditionally. As with `tryActive`, we work in increments of 2 to "dodge" the
// "is closing" bit. If the call count is zero and we're closing then `state` will just have the "closing" bit set.
if (state.addAndGet(-2) == CLOSING_BIT_MASK) {
onCloseHandler.run();
}
}
/**
* Closes this epoch, preventing new callers from entering the critical section. If the critical section is empty when
* this method is called, it will trigger the {@code onCloseHandler} immediately. Otherwise, the
* {@code onCloseHandler} will fire when the last caller departs the critical section.
*
* @throws IllegalStateException if this epoch is already closed; note that this exception is thrown on a
* "best-effort" basis to help callers detect bugs
*/
public void close() {
// Note that this is not airtight and is a "best-effort" check
if (isClosing(state.get())) {
throw new IllegalStateException("Epoch already closed");
}
// Set the "closing" bit. If the closing bit is the only bit set, then the call count is zero and we can call the
// "on close" handler.
if (state.updateAndGet(state -> state | CLOSING_BIT_MASK) == CLOSING_BIT_MASK) {
onCloseHandler.run();
}
}
@VisibleForTesting
int getActiveCallers() {
return state.get() >> 1;
}
private static boolean isClosing(final int state) {
return (state & CLOSING_BIT_MASK) != 0;
}
}
@@ -1,33 +0,0 @@
package org.whispersystems.textsecuregcm.util;
import io.dropwizard.lifecycle.Managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import java.util.concurrent.ScheduledExecutorService;
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
public class JmxDumper implements Managed {
private static final Logger log = LoggerFactory.getLogger(JmxDumper.class);
private final ScheduledExecutorService executor;
public JmxDumper(final ScheduledExecutorService executor) {
this.executor = executor;
}
@Override
public void start() throws Exception {
// executor.schedule()
}
private void dump() {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
}
}
@@ -1,18 +1,6 @@
package org.whispersystems.textsecuregcm.util;
import com.google.common.annotations.VisibleForTesting;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import javax.annotation.Nullable;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
@@ -23,7 +11,25 @@ import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
public class ProfileHelper {
public static int MAX_PROFILE_AVATAR_SIZE_BYTES = 10 * 1024 * 1024;
@@ -86,15 +92,43 @@ public class ProfileHelper {
}
public static ExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final byte[] encodedCredentialRequest,
final VersionedProfile profile,
final ProfileKeyCredentialRequest request,
final ProfileKeyCommitment commitment,
final ServiceId.Aci accountIdentifier,
final ServerZkProfileOperations zkProfileOperations) throws InvalidInputException, VerificationFailedException {
final Instant expiration = Instant.now().plus(EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION).truncatedTo(ChronoUnit.DAYS);
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.commitment());
final ProfileKeyCredentialRequest request = new ProfileKeyCredentialRequest(
encodedCredentialRequest);
return zkProfileOperations.issueExpiringProfileKeyCredential(request, accountIdentifier, commitment, expiration);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static boolean isPaymentAddressUpdateForbidden(
final Account account, final Optional<VersionedProfile> maybeProfile,
final Optional<VersionedProfileV1> maybeV1Profile,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final Optional<byte[]> currentPaymentAddress = maybeProfile.map(VersionedProfile::paymentAddress)
.or(() -> maybeV1Profile.map(VersionedProfileV1::paymentAddress));
final boolean hasDisallowedPrefix = dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration()
.getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
return hasDisallowedPrefix && currentPaymentAddress.isEmpty();
}
@Nullable
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static String getAvatar(final CreateProfileRequest.AvatarChange avatarChange, final Optional<String> currentAvatar) {
return switch (avatarChange) {
case UNCHANGED -> currentAvatar.orElse(null);
case CLEAR -> null;
case UPDATE -> ProfileHelper.generateAvatarObjectName();
};
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static Optional<String> getCurrentAvatar(Optional<VersionedProfileV1> maybeV1Profile) {
return maybeV1Profile.map(VersionedProfileV1::avatar).filter(avatar -> avatar.startsWith("profiles/"));
}
}
@@ -8,14 +8,14 @@ package org.whispersystems.textsecuregcm.websocket;
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicCredentialsFromAuthHeader;
import com.google.common.net.HttpHeaders;
import javax.annotation.Nullable;
import io.dropwizard.auth.basic.BasicCredentials;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import java.util.Optional;
import javax.annotation.Nullable;
import org.eclipse.jetty.ee10.websocket.server.JettyServerUpgradeRequest;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.websocket.auth.InvalidCredentialsException;
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
import java.util.Optional;
public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<AuthenticatedDevice> {
@@ -27,7 +27,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
}
@Override
public Optional<AuthenticatedDevice> authenticate(final UpgradeRequest request)
public Optional<AuthenticatedDevice> authenticate(final JettyServerUpgradeRequest request)
throws InvalidCredentialsException {
@Nullable final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
@@ -52,6 +52,8 @@ import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryC
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
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.IssuedReceiptsManager;
@@ -63,6 +65,7 @@ import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
@@ -220,8 +223,10 @@ public record CommandDependencies(
configuration.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfiles().getTableName());
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV2().getTableName());
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
.region(Region.of(configuration.getPagedSingleUseKEMPreKeyStore().region()))
@@ -263,7 +268,7 @@ public record CommandDependencies(
disconnectionRequestListenerExecutor, retryExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC(), experimentEnrollmentManager);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getReportMessage().getTableName(),
@@ -278,9 +283,13 @@ public record CommandDependencies(
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
configuration.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
changeNumberWaitingPeriods, configuration.getChangeNumber().postRegistrationWaitingPeriod(), clock);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value());
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
@@ -282,16 +282,20 @@ message GetBackupInfoRequest {
}
message GetMessageBackupInfoResponse {
message MessageBackupInfo {
// The base directory of your backup data on the cdn. The message backup can
// be found in the returned cdn at /backup_dir/backup_name
// The base directory of your backup data on the cdn. Always non-empty, even
// if a backup has not actually been stored to the cdn. If a backup was
// previously uploaded and has not expired, it can be found in the returned
// cdn at /backup_dir/backup_name.
string backup_dir = 1;
// The CDN type where the message backup is stored. Media may be stored
// elsewhere.
uint32 cdn = 2;
// The location of the message backup on the cdn. If a backup was previously
// uploaded and unexpired, it can be found at /backup_dir/backup_name.
// The location of the message backup on the cdn. Always non-empty, even
// if a backup has not actually been stored to the cdn. If a backup was
// previously uploaded and has not expired, it can be found in the returned
// cdn at /backup_dir/backup_name.
string backup_name = 3;
}
@@ -307,12 +311,16 @@ message GetMessageBackupInfoResponse {
}
message GetMediaBackupInfoResponse {
message MediaBackupInfo {
// The base directory of your backup data on the cdn.
// The base directory of your backup data on the cdn. Always non-empty, even
// if no media has been stored to the cdn or the credential is for a tier
// that does not support media.
string backup_dir = 1;
// The prefix path component for media objects on a cdn. Stored media for a
// media_id can be found at /backup_dir/media_dir/media_id, where the media_id
// is encoded in unpadded url-safe base64.
// media_id can be found at /backup_dir/media_dir/media_id, where the
// media_id is encoded in unpadded url-safe base64. Always non-empty, even
// if no media has been stored to the cdn or the credential is for a tier
// that does not support media.
string media_dir = 2;
// The amount of space used to store media
@@ -19,7 +19,7 @@ enum IdentityType {
message ServiceIdentifier {
// The type of identity represented by this service identifier.
IdentityType identity_type = 1;
IdentityType identity_type = 1 [(require.specified) = true];
// The UUID of the identity represented by this service identifier.
bytes uuid = 2 [(require.exactlySize) = 16];
@@ -41,7 +41,7 @@ message EcPreKey {
// A locally-unique identifier for this key, which will be provided by
// peers using this key to encrypt messages so the private key can be looked
// up.
uint32 key_id = 1;
int32 key_id = 1 [(require.range).min = 0];
// The public key, serialized in libsignal's elliptic-curve public key format.
bytes public_key = 2 [(require.nonEmpty) = true];
@@ -51,7 +51,7 @@ message EcSignedPreKey {
// A locally-unique identifier for this key, which will be provided by
// peers using this key to encrypt messages so the private key can be looked
// up.
uint32 key_id = 1;
int32 key_id = 1 [(require.range).min = 0];
// The public key, serialized in libsignal's elliptic-curve public key format.
bytes public_key = 2 [(require.nonEmpty) = true];
@@ -64,7 +64,7 @@ message EcSignedPreKey {
message KemSignedPreKey {
// An locally-unique identifier for this key, which will be provided by peers
// using this key to encrypt messages so the private key can be looked up.
uint32 key_id = 1;
int32 key_id = 1 [(require.range).min = 0];
// The public key, serialized in libsignal's Kyber1024 public key format.
bytes public_key = 2 [(require.nonEmpty) = true];
@@ -83,6 +83,7 @@ enum DeviceCapability {
reserved 5;
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
DEVICE_CAPABILITY_PROFILES_V2 = 8;
}
message ZkCredential {
@@ -10,44 +10,22 @@ option java_multiple_files = true;
package org.signal.chat.profile;
import "org/signal/chat/common.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
// Provides methods for working with profiles and profile-related data.
service Profile {
// Sets profile data and if needed, returns S3 credentials used by clients to upload an avatar.
//
// This RPC may fail with `PERMISSION_DENIED` if it attempts to set the MobileCoin wallet ID
// on an account whose profile does not currently have a MobileCoin wallet ID and
// whose phone number contains a disallowed country prefix.
// Sets profile data and, if needed, returns credentials used by clients to upload a v1 avatar.
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
// Retrieves versioned profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
// exceeded, in which case a `retry-after` header containing an ISO 8601
// duration string will be present in the response trailers.
rpc GetVersionedProfile(GetVersionedProfileRequest) returns (GetVersionedProfileResponse) {}
// Retrieves unversioned profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
// exceeded, in which case a `retry-after` header containing an ISO 8601
// duration string will be present in the response trailers.
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
// Retrieves a profile key credential.
// Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
// exceeded, in which case a `retry-after` header containing an ISO 8601
// duration string will be present in the response trailers. It may also fail with an
// `INVALID_ARGUMENT` status if the given credential type is invalid.
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
}
// Provides methods for working with profiles and profile-related data using "unidentified access"
@@ -58,97 +36,218 @@ service Profile {
// methods in `Profile` instead.
service ProfileAnonymous {
// Retrieves versioned profile data.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may also fail with an `UNAUTHENTICATED` status if the given
// unidentified access key did not match the target account's unidentified
// access key.
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileResponse) {}
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {}
// Retrieves unversioned profile data.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may also fail with an `UNAUTHENTICATED` status if the given
// unidentified access key did not match the target account's unidentified
// access key.
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileResponse) {}
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {}
// Retrieves a profile key credential.
//
// This RPC may fail with a `NOT_FOUND` status if the target account was not
// found. It may also fail with an `UNAUTHENTICATED` status if the given
// unidentified access key did not match the target account's unidentified
// access key, or an `INVALID_ARGUMENT` status if the given credential type is invalid.
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {}
}
message SetProfileRequest {
message SetProfileV1Request {
enum AvatarChange {
AVATAR_CHANGE_UNCHANGED = 0;
AVATAR_CHANGE_CLEAR = 1;
AVATAR_CHANGE_UPDATE = 2;
}
// The profile version. Must be set.
string version = 1;
// The ciphertext of a name that users must set on the profile.
bytes name = 2;
bytes name = 1 [(require.exactlySize) = 81, (require.exactlySize) = 285];
// An enum to indicate what change, if any, is made to the avatar with this request.
AvatarChange avatarChange = 3;
AvatarChange avatar_change = 2;
// The ciphertext of an emoji that users can set on their profile.
bytes about_emoji = 4;
bytes about_emoji = 3 [(require.exactlySize) = 0, (require.exactlySize) = 60];
// The ciphertext of a description that users can set on their profile.
bytes about = 5;
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 6;
// A list of badge IDs associated with the profile.
repeated string badge_ids = 7;
bytes about = 4 [(require.exactlySize) = 0, (require.exactlySize) = 156, (require.exactlySize) = 282, (require.exactlySize) = 540];
// The ciphertext of the phone-number sharing setting on the profile. 29-byte encrypted boolean.
bytes phone_number_sharing = 8;
bytes phone_number_sharing = 6 [(require.exactlySize) = 29];
}
message SetProfileRequest {
// The profile version. Required.
bytes version = 1 [(require.exactlySize) = 32];
// The ciphertext of a serialized Profile protobuf. Required.
// 937 max length = 909 plaintext serialization + 28 bytes encryption overhead
bytes data = 2 [(require.nonEmpty) = true, (require.size).max = 937];
// The SHA-256 hash of the Profile ciphertext being replaced.
// This is used an optimistic lock against concurrent changes.
//
// Optional, if this is the initial request to create a version.
bytes expected_current_data_hash = 3 [(require.exactlySize) = 0, (require.exactlySize) = 32];
// The current profile version being updated.
// This is used as an optimistic lock against concurrent changes.
//
// Optional, if there is no current profile version for the account.
bytes expected_current_version = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 5 [(require.exactlySize) = 0, (require.exactlySize) = 582];
// A list of badge IDs associated with the profile.
repeated string badge_ids = 6;
// The profile key commitment. Used to issue a profile key credential response.
// Must be set on the request.
bytes commitment = 9;
//
// Required during the v1 -> v2 migration period. Afterwards will be optional, if this is an update to an existing version.
bytes commitment = 7 [(require.exactlySize) = 0, (require.exactlySize) = 97];
// An embedded v1 request. Required during the v1 -> v2 migration period.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
SetProfileV1Request v1Request = 15 [(require.present) = true];
// next: 8
}
// Indicates that the account is not permitted to set a payment address,
// due to a disallowed country prefix on the account's phone number.
message PaymentsForbiddenInRegion {}
// Indicates that the account does not have the Profiles v2 capability, which
// is required to call Profiles.SetProfile
message ProfilesV2CapabilityRequired {}
message SetProfileResult {
// If the request included a v1 avatar change, this field contains the policy
// and credential used by clients to upload an avatar to the CDN.
//
// 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;
// next: 1
}
message SetProfileResponse {
// The policy and credential used by clients to upload an avatar to S3.
ProfileAvatarUploadAttributes attributes = 1;
oneof response {
SetProfileResult result = 1;
// The current data hash did not match the request's expectation, indicating
// another device on the account may have written an update the caller does not know about.
errors.FailedPrecondition expected_data_write_conflict = 2 [(tag.reason) = "expected_data_write_conflict"];
// Payments are not permitted in the account's region, based on its phone number.
// The request should be retried without `payment_address.
PaymentsForbiddenInRegion payments_forbidden_in_region = 3 [(tag.reason) = "payments_forbidden_in_region"];
// The current version did not match the request's expectation, indicating
// another device on the account may have created a new version the caller does not know about.
errors.FailedPrecondition expected_version_write_conflict = 4 [(tag.reason) = "expected_version_write_conflict"];
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
ProfilesV2CapabilityRequired profiles_v2_capability_required = 15 [(tag.reason) = "profiles_v2_capability_required"];
// next: 4
}
}
message GetVersionedProfileRequest {
// The ACI of the account for which to get profile data.
common.ServiceIdentifier accountIdentifier = 1;
common.ServiceIdentifier accountIdentifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
// The profile version to retrieve.
string version = 2;
bytes version = 2 [(require.exactlySize) = 32];
// The `data_etag` from the previous request for this Profile version. If
// unchanged, the response will omit `data` and `data_etag_matched` will be
// `true`.
bytes data_etag = 3 [(require.exactlySize) = 0, (require.exactlySize) = 32];
// The `payment_address_etag` from the previous request for this account’s
// profile. If unchanged, the response will omit `payment_address` and
// `payment_address_etag_matched` will be `true`.
bytes payment_address_etag = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
}
message GetVersionedProfileAnonymousRequest {
// Contains the data necessary to request a versioned profile.
GetVersionedProfileRequest request = 1;
GetVersionedProfileRequest request = 1 [(require.present) = true];
// The unidentified access key for the targeted account.
bytes unidentified_access_key = 2;
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
}
message DataEtag {
bytes data = 1;
// An entity tag for `data`. This may be used in subsequent requests for
// this profile version to optimize bandwidth.
//
// Clients may validate that the value has been correctly calculated by deriving
// the SHA-256 digest of `data`.
bytes etag_sha256 = 2;
}
message GetVersionedProfileResult {
oneof data_result {
// The ciphertext of a serialized Profile.
// Absent if a v2 Profile is not available
// for this version, in which the client should use `v1_response`.
DataEtag data_etag = 1;
// Indicates that the request’s ETag matched the stored `data`
bool data_etag_matched = 2;
// Will be present if there is no v2 Profile data for this version.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
GetVersionedProfileV1Response v1_response = 15;
}
oneof payment_address_result {
// The ciphertext of the MobileCoin wallet ID on the profile.
DataEtag payment_address_data_etag = 3;
// Indicates that the request’s ETag matched the stored `payment_address`
bool payment_address_etag_matched = 4;
}
// next: 5
}
message GetVersionedProfileResponse {
oneof response {
GetVersionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message GetVersionedProfileAnonymousResponse {
oneof response {
GetVersionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
message GetVersionedProfileV1Response {
// The ciphertext of the name on the profile.
bytes name = 1;
// The ciphertext of the description on the profile.
bytes about = 2;
// The ciphertext of the emoji on the profile.
bytes about_emoji = 3;
// The S3 path of the avatar on the profile.
// The cdn0 path of the avatar on the profile.
string avatar = 4;
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 5;
// The ciphertext of the phone-number sharing setting on the profile.
bytes phone_number_sharing = 6;
bytes phone_number_sharing = 5;
}
message GetUnversionedProfileRequest {
// The service identifier of the account for which to get profile data.
common.ServiceIdentifier serviceIdentifier = 1;
common.ServiceIdentifier service_identifier = 1 [(require.present) = true];
}
message GetUnversionedProfileAnonymousRequest {
// Contains the data necessary to request an unversioned profile.
GetUnversionedProfileRequest request = 1;
// Note: Only ACI service identifiers are permitted for anonymous requests.
GetUnversionedProfileRequest request = 1 [(require.present) = true];
oneof authentication {
// The unidentified access key for the targeted account.
@@ -159,7 +258,7 @@ message GetUnversionedProfileAnonymousRequest {
}
}
message GetUnversionedProfileResponse {
message GetUnversionedProfileResult {
// The identity key of the targeted account/identity type.
bytes identity_key = 1;
// A checksum of the unidentified access key for the targeted account.
@@ -172,28 +271,54 @@ message GetUnversionedProfileResponse {
repeated Badge badges = 5;
}
message GetUnversionedProfileResponse {
oneof response {
GetUnversionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message GetUnversionedProfileAnonymousResponse {
oneof response {
GetUnversionedProfileResult result = 1;
// The target profile was not found
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
// The unidentified access key or group send endorsement were not valid for
// the request.
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
message GetExpiringProfileKeyCredentialRequest {
// The ACI of the account for which to get a profile key credential.
common.ServiceIdentifier accountIdentifier = 1;
common.ServiceIdentifier account_identifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
// A zkgroup request for a profile key credential.
bytes credential_request = 2;
bytes credential_request = 2 [(require.nonEmpty) = true];
// The type of credential being requested.
CredentialType credential_type = 3;
CredentialType credential_type = 3 [(require.specified) = true];
// The profile version for which to generate a profile key credential.
string version = 4;
bytes version = 4 [(require.exactlySize) = 32];
}
message GetExpiringProfileKeyCredentialAnonymousRequest {
// Contains the data necessary to request an expiring profile key credential.
GetExpiringProfileKeyCredentialRequest request = 1;
GetExpiringProfileKeyCredentialRequest request = 1 [(require.present) = true];
// The unidentified access key for the targeted account.
bytes unidentified_access_key = 2;
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
}
message GetExpiringProfileKeyCredentialResponse {
message GetExpiringProfileKeyCredentialResult {
// A zkgroup credential used by a client to prove that it has the profile key
// of a targeted account.
bytes profileKeyCredential = 1;
bytes profile_key_credential = 1;
}
message GetExpiringProfileKeyCredentialAnonymousResponse {
oneof response {
GetExpiringProfileKeyCredentialResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
message ProfileAvatarUploadAttributes {
@@ -157,11 +157,28 @@ extend google.protobuf.FieldOptions {
* import "org/signal/chat/require.proto";
*
* message Data {
* string myString = 1 [(require.base64url)];
* string myString = 1 [(require.base64url) = true];
* }
* ```
*/
optional bool base64url = 70008;
/*
* Requires a common.ServiceIdentifier field to have its IdentityType
* be the given type (`aci` or `pni`).
*
* ```
* import "org/signal/chat/require.proto";
* import "org/signal/chat/common.proto";
*
* message Data {
* common.ServiceIdentifier accountIdentifier = 1 [(require.identityType) = IDENTITY_TYPE_ACI];
* }
* ```
*/
optional IdentityType identityType = 70009;
// next 70010
}
message SizeConstraint {
@@ -197,3 +214,11 @@ enum Auth {
AUTH_ONLY_ANONYMOUS = 2;
}
// This is duplicated from common.proto because:
// 1. importing would be a circular dependency
// 2. the canonical declaration belongs there
enum IdentityType {
IDENTITY_TYPE_UNSPECIFIED = 0;
IDENTITY_TYPE_ACI = 1;
IDENTITY_TYPE_PNI = 2;
}
@@ -0,0 +1,15 @@
-- Atomically sets v1 and v2 profile cache entries
local v1Key = KEYS[1] -- v1 profile hash key
local v2Key = KEYS[2] -- v2 profile hash key
local v1Field = ARGV[1] -- v1 profile version
local v1Value = ARGV[2] -- v1 profile data
local v2Field = ARGV[3] -- v2 profile version
local v2Value = ARGV[4] -- v2 profile data
if #v1Field > 0 then
redis.call("HSET", v1Key, v1Field, v1Value)
end
if #v2Field > 0 then
redis.call("HSET", v2Key, v2Field, v2Value)
end
@@ -15,7 +15,6 @@ import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.glassfish.jersey.server.ManagedAsync;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -35,7 +34,6 @@ public class BufferingInterceptorIntegrationTest {
environment.jersey().register(testController);
environment.jersey().register(new BufferingInterceptor());
environment.jersey().register(new VirtualExecutorServiceProvider("virtual-thread-", 10));
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
}
}
@@ -18,28 +18,29 @@ import io.dropwizard.core.Configuration;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.ServletRegistration;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.EnumSet;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
@@ -52,6 +53,7 @@ import org.whispersystems.websocket.messages.WebSocketMessage;
import org.whispersystems.websocket.setup.WebSocketEnvironment;
@ExtendWith(DropwizardExtensionsSupport.class)
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class ProvisioningTimeoutIntegrationTest {
private static final DropwizardAppExtension<Configuration> DROPWIZARD_APP_EXTENSION =
@@ -77,9 +79,9 @@ public class ProvisioningTimeoutIntegrationTest {
CompletableFuture<String> provisioningAddressFuture = new CompletableFuture<>();
@Override
public void onWebSocketBinary(final byte[] payload, final int offset, final int length) {
public void onWebSocketBinary(final ByteBuffer payload, final Callback callback) {
try {
WebSocketMessage webSocketMessage = messageFactory.parseMessage(payload, offset, length);
WebSocketMessage webSocketMessage = messageFactory.parseMessage(payload);
if (Objects.requireNonNull(webSocketMessage.getType()) == WebSocketMessage.Type.REQUEST_MESSAGE
&& webSocketMessage.getRequestMessage().getPath().equals("/v1/address")) {
MessageProtos.ProvisioningAddress provisioningAddress =
@@ -92,7 +94,7 @@ public class ProvisioningTimeoutIntegrationTest {
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
super.onWebSocketBinary(payload, offset, length);
super.onWebSocketBinary(payload, callback);
}
}
@@ -106,21 +108,17 @@ public class ProvisioningTimeoutIntegrationTest {
final WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment =
new WebSocketEnvironment<>(environment, webSocketConfiguration);
environment.servlets()
.addFilter("RemoteAddressFilter", new RemoteAddressFilter())
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
webSocketEnvironment.setConnectListener(
new ProvisioningConnectListener(mock(ProvisioningManager.class), () -> mock(AsnInfoProvider.class), mock(ClientReleaseManager.class), scheduler, Duration.ofSeconds(5)));
final WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet =
new WebSocketResourceProviderFactory<>(webSocketEnvironment, AuthenticatedDevice.class,
webSocketConfiguration, REMOTE_ADDRESS_ATTRIBUTE_NAME);
REMOTE_ADDRESS_ATTRIBUTE_NAME);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
final ServletRegistration.Dynamic websocketServlet = environment.servlets()
.addServlet("WebSocket", webSocketServlet);
websocketServlet.addMapping("/websocket");
websocketServlet.setAsyncSupported(true);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (servletContext, container) -> {
container.addMapping("/websocket", webSocketServlet);
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
});
}
}
@@ -9,8 +9,6 @@ import io.dropwizard.core.Configuration;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.ServletRegistration;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
@@ -20,19 +18,20 @@ import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.URI;
import java.util.EnumSet;
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.glassfish.jersey.server.ManagedAsync;
import org.glassfish.jersey.server.ServerProperties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
@@ -41,6 +40,7 @@ import org.whispersystems.websocket.messages.WebSocketResponseMessage;
import org.whispersystems.websocket.setup.WebSocketEnvironment;
@ExtendWith(DropwizardExtensionsSupport.class)
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class WebsocketResourceProviderIntegrationTest {
private static final DropwizardAppExtension<Configuration> DROPWIZARD_APP_EXTENSION =
new DropwizardAppExtension<>(TestApplication.class);
@@ -72,9 +72,6 @@ public class WebsocketResourceProviderIntegrationTest {
new WebSocketEnvironment<>(environment, webSocketConfiguration);
environment.jersey().register(testController);
environment.servlets()
.addFilter("RemoteAddressFilter", new RemoteAddressFilter())
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
webSocketEnvironment.jersey().register(testController);
webSocketEnvironment.jersey().register(new RemoteAddressFilter());
webSocketEnvironment.setAuthenticator(upgradeRequest -> Optional.of(mock(AuthenticatedDevice.class)));
@@ -85,15 +82,13 @@ public class WebsocketResourceProviderIntegrationTest {
final WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet =
new WebSocketResourceProviderFactory<>(webSocketEnvironment, AuthenticatedDevice.class,
webSocketConfiguration, REMOTE_ADDRESS_ATTRIBUTE_NAME);
REMOTE_ADDRESS_ATTRIBUTE_NAME);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (servletContext, container) -> {
container.addMapping("/websocket", webSocketServlet);
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
});
final ServletRegistration.Dynamic websocketServlet =
environment.servlets().addServlet("WebSocket", webSocketServlet);
websocketServlet.addMapping("/websocket");
websocketServlet.setAsyncSupported(true);
}
}
@@ -13,35 +13,47 @@ import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.util.Resources;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.stub.MetadataUtils;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.ServerSocket;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.io.ClientConnector;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.chat.account.AccountsAnonymousGrpc;
import org.signal.chat.account.CheckAccountExistenceRequest;
import org.signal.chat.account.CheckAccountExistenceResponse;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -58,13 +70,16 @@ class WhisperServerServiceTest {
System.setProperty("secrets.bundle.filename",
Resources.getResource("config/test-secrets-bundle.yml").getPath());
}
private static final int OMNIBUS_PORT = findAvailablePort();
private static final WebSocketClient webSocketClient = new WebSocketClient();
private static WebSocketClient webSocketClient;
private static WebSocketClient h2WebSocketClient;
private static final DropwizardAppExtension<WhisperServerConfiguration> EXTENSION = new DropwizardAppExtension<>(
WhisperServerService.class, Resources.getResource("config/test.yml").getPath(),
// Tables will be created by the local DynamoDbExtension
ConfigOverride.config("dynamoDbClient.initTables", "false"));
ConfigOverride.config("dynamoDbClient.initTables", "false"),
ConfigOverride.config("grpc.port", String.valueOf(OMNIBUS_PORT)));
@RegisterExtension
public static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.values());
@@ -76,7 +91,13 @@ class WhisperServerServiceTest {
@BeforeAll
static void setUp() throws Exception {
final ClientConnector clientConnector = new ClientConnector();
final HTTP2Client http2Client = new HTTP2Client(clientConnector);
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client));
h2WebSocketClient = new WebSocketClient(httpClient);
webSocketClient = new WebSocketClient();
webSocketClient.start();
h2WebSocketClient.start();
}
@Test
@@ -100,8 +121,9 @@ class WhisperServerServiceTest {
assertEquals(200, healthCheck.getStatus());
}
@Test
void websocket() throws Exception {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void websocket(final boolean useH2) throws Exception {
// test unauthenticated websocket
final long start = System.currentTimeMillis();
@@ -117,7 +139,7 @@ class WhisperServerServiceTest {
});
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
final Session session = webSocketClient.connect(testWebsocketListener,
final Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
.join();
final long sessionTimestamp = Long.parseLong(session.getUpgradeResponse().getHeader(HeaderUtils.TIMESTAMP_HEADER));
@@ -185,6 +207,51 @@ class WhisperServerServiceTest {
.build());
}
@Test
void omnibusWebsocket() throws Exception {
final HTTP2Client http2Client = new HTTP2Client(new ClientConnector());
final WebSocketClient h2WebSocketClient =
new WebSocketClient(new HttpClient(new HttpClientTransportOverHTTP2(http2Client)));
h2WebSocketClient.start();
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
final Session session = h2WebSocketClient.connect(testWebsocketListener,
URI.create(String.format("ws://localhost:%d/v1/websocket/", OMNIBUS_PORT)))
.join();
final WebSocketResponseMessage keepAlive = testWebsocketListener.doGet("/v1/keepalive").join();
assertEquals(200, keepAlive.getStatus());
final WebSocketResponseMessage whoami = testWebsocketListener.doGet("/v1/accounts/whoami").join();
assertEquals(401, whoami.getStatus());
session.close();
h2WebSocketClient.stop();
}
@Test
void omnibusGrpc() throws Exception {
final ManagedChannel channel = NettyChannelBuilder.forAddress("localhost", OMNIBUS_PORT)
.usePlaintext()
.build();
final Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("X-Forwarded-For", Metadata.ASCII_STRING_MARSHALLER), "127.0.0.1");
final AccountsAnonymousGrpc.AccountsAnonymousBlockingStub stub = AccountsAnonymousGrpc
.newBlockingStub(channel)
.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata));
final CheckAccountExistenceResponse response = stub.checkAccountExistence(
CheckAccountExistenceRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build())
.build());
assertFalse(response.getAccountExists());
channel.shutdownNow();
channel.awaitTermination(1, TimeUnit.SECONDS);
}
private static DynamoDbClient getDynamoDbClient() {
final AwsCredentialsProvider awsCredentialsProvider = EXTENSION.getConfiguration().getAwsCredentialsConfiguration()
.build();
@@ -193,4 +260,12 @@ class WhisperServerServiceTest {
.buildSyncClient(awsCredentialsProvider, new NoopAwsSdkMetricPublisher());
}
private static int findAvailablePort() {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -15,8 +15,8 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
import org.eclipse.jetty.ee10.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.ee10.websocket.server.JettyServerUpgradeResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@@ -210,8 +210,7 @@ class PhoneVerificationTokenManagerTest {
@ParameterizedTest
@MethodSource
void verifyRecoveryPasswordManagerException(final Throwable recoveryPasswordManagerException)
throws ExecutionException, InterruptedException, TimeoutException {
void verifyRecoveryPasswordManagerException(final Throwable recoveryPasswordManagerException) {
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
@@ -219,11 +218,8 @@ class PhoneVerificationTokenManagerTest {
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
.thenReturn(true);
@SuppressWarnings("unchecked") final CompletableFuture<Boolean> mockFuture = mock(CompletableFuture.class);
when(mockFuture.get(anyLong(), any())).thenThrow(recoveryPasswordManagerException);
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
.thenReturn(mockFuture);
.thenReturn(CompletableFuture.failedFuture(recoveryPasswordManagerException));
assertThrows(ServerErrorException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
PHONE_NUMBER,
@@ -292,7 +292,7 @@ class AccountControllerV2Test {
@ParameterizedTest
@MethodSource
void phoneVerificationException(final Exception exception, final int expectedStatus)
throws InterruptedException, MessageTooLargeException, MismatchedDevicesException, RateLimitExceededException {
throws InterruptedException, MessageTooLargeException, MismatchedDevicesException, RateLimitExceededException, MessageDeliveryNotAllowedException {
doThrow(exception)
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
@@ -338,6 +338,28 @@ class AccountControllerV2Test {
}
}
@Test
void messageDeliveryNotAllowed() throws Exception {
doThrow(MessageDeliveryNotAllowedException.class)
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
try (final Response response = resources.getJerseyTest()
.target("/v2/accounts/number")
.request()
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(
new ChangeNumberRequest(encodeSessionId("session"), null, NEW_NUMBER, "123", IDENTITY_KEY,
Collections.emptyList(),
Map.of(Device.PRIMARY_ID, KeysHelper.signedECPreKey(1, IDENTITY_KEY_PAIR)),
Map.of(Device.PRIMARY_ID, KeysHelper.signedKEMPreKey(2, IDENTITY_KEY_PAIR)),
Map.of(Device.PRIMARY_ID, 17)),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(503, response.getStatus());
}
}
/**
* Valid request JSON with the given Recovery Password
*/
@@ -93,6 +93,7 @@ import reactor.core.publisher.Flux;
public class ArchiveControllerTest {
private static final long MAX_ATTACHMENT_SIZE = 1000L;
private static final long MAX_MESSAGE_BACKUP_SIZE = 2000L;
private static final AccountsManager accountsManager = mock(AccountsManager.class);
private static final BackupAuthManager backupAuthManager = mock(BackupAuthManager.class);
private static final BackupManager backupManager = mock(BackupManager.class);
@@ -108,7 +109,7 @@ public class ArchiveControllerTest {
.addProvider(new RateLimitExceededExceptionMapper())
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new ArchiveController(accountsManager, backupAuthManager, backupManager, new BackupMetrics(), MAX_ATTACHMENT_SIZE))
.addResource(new ArchiveController(accountsManager, backupAuthManager, backupManager, new BackupMetrics(), MAX_ATTACHMENT_SIZE, MAX_MESSAGE_BACKUP_SIZE))
.build();
private final UUID aci = UUID.randomUUID();
@@ -615,8 +616,8 @@ public class ArchiveControllerTest {
static Stream<Arguments> messagesUploadForm() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE), true),
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE + 1), false)
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_SIZE), true),
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_SIZE + 1), false)
);
}
@@ -643,7 +644,7 @@ public class ArchiveControllerTest {
ArchiveController.UploadDescriptorResponse desc = response.readEntity(ArchiveController.UploadDescriptorResponse.class);
assertThat(desc)
.isEqualTo(new ArchiveController.UploadDescriptorResponse(3, "abc", Map.of("k", "v"), "example.org"));
verify(backupManager).createMessageBackupUploadDescriptor(any(), eq(uploadLength.orElse(MAX_ATTACHMENT_SIZE)));
verify(backupManager).createMessageBackupUploadDescriptor(any(), eq(uploadLength.orElse(MAX_MESSAGE_BACKUP_SIZE)));
} else {
assertThat(response.getStatus()).isEqualTo(413);
}
@@ -196,7 +196,8 @@ class MessageControllerTest {
.build();
@BeforeEach
void setup() throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
void setup()
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
reset(pushNotificationScheduler);
when(messageSender.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any()))
@@ -545,6 +546,24 @@ class MessageControllerTest {
}
}
@Test
void testSingleDeviceMessageDeliveryNotAllowed() throws Exception {
doThrow(MessageDeliveryNotAllowedException.class)
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(SystemMapper.jsonMapper().readValue(jsonFixture("fixtures/current_message_single_device.json"),
IncomingMessageList.class),
MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus(), is(equalTo(503)));
}
}
@Test
void testSendBadAuth() throws Exception {
try (final Response response =
@@ -1042,7 +1061,8 @@ class MessageControllerTest {
}
@Test
void testValidateContentLength() throws MismatchedDevicesException, MessageTooLargeException, IOException {
void testValidateContentLength()
throws MismatchedDevicesException, MessageTooLargeException, IOException, MessageDeliveryNotAllowedException {
doThrow(new MessageTooLargeException()).when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
try (final Response response =
@@ -1101,7 +1121,7 @@ class MessageControllerTest {
final Set<Account> expectedResolvedAccounts,
final Set<ServiceIdentifier> expectedUuids404,
@Nullable final MultiRecipientMismatchedDevicesException mismatchedDevicesException)
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
clock.pin(START_OF_DAY);
@@ -1674,6 +1694,72 @@ class MessageControllerTest {
}
}
@Test
void sendMultiRecipientMessageMessageDeliveryNotAllowed() throws Exception {
clock.pin(START_OF_DAY);
final UUID singleDeviceAccountAci = UUID.randomUUID();
final UUID singleDeviceAccountPni = UUID.randomUUID();
final byte[] singleDeviceAccountUak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final int singleDevicePrimaryRegistrationId = 1;
final Device singleDeviceAccountPrimary = mock(Device.class);
when(singleDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID);
when(singleDeviceAccountPrimary.getRegistrationId(IdentityType.ACI)).thenReturn(singleDevicePrimaryRegistrationId);
final Account singleDeviceAccount = mock(Account.class);
when(singleDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(singleDeviceAccountAci);
when(singleDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(singleDeviceAccountUak));
when(singleDeviceAccount.getDevices()).thenReturn(List.of(singleDeviceAccountPrimary));
when(singleDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty());
when(singleDeviceAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(singleDeviceAccountPrimary));
final Map<ServiceIdentifier, Account> accountsByServiceIdentifier = Map.of(
new AciServiceIdentifier(singleDeviceAccountAci), singleDeviceAccount,
new PniServiceIdentifier(singleDeviceAccountPni), singleDeviceAccount);
final byte[] aciMessage = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
new TestRecipient(new AciServiceIdentifier(singleDeviceAccountAci), Device.PRIMARY_ID, singleDevicePrimaryRegistrationId, new byte[48])));
when(accountsManager.getByServiceIdentifierAsync(any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
accountsByServiceIdentifier.forEach(((serviceIdentifier, account) ->
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)))));
final boolean ephemeral = true;
final boolean urgent = false;
final boolean story = false;
final Invocation.Builder invocationBuilder = resources
.getJerseyTest()
.target("/v1/messages/multi_recipient")
.queryParam("ts", clock.millis())
.queryParam("online", ephemeral)
.queryParam("story", story)
.queryParam("urgent", urgent)
.request()
.header(HeaderUtils.GROUP_SEND_TOKEN, AuthHelper.validGroupSendTokenHeader(serverSecretParams,
List.of(new AciServiceIdentifier(singleDeviceAccountAci)),
START_OF_DAY.plus(Duration.ofDays(1))));
when(rateLimiter.validateAsync(any(UUID.class)))
.thenReturn(CompletableFuture.completedFuture(null));
doThrow(MessageDeliveryNotAllowedException.class)
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
try (final Response response = invocationBuilder
.put(Entity.entity(aciMessage, MultiRecipientMessageProvider.MEDIA_TYPE))) {
assertThat(response.getStatus(), is(equalTo(503)));
}
}
@SuppressWarnings("SameParameterValue")
private static Envelope generateEnvelope(UUID guid, int type, long timestamp, UUID sourceUuid,
byte sourceDevice, UUID destinationUuid, UUID updatedPni, byte[] content, long serverTimestamp) {
@@ -106,7 +106,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
@@ -232,8 +232,8 @@ class ProfileControllerTest {
final byte[] about = TestRandomUtil.nextBytes(156);
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty());
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfile(
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty());
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfileV1(
versionHex("validversion"), name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes())));
when(profilesManager.deleteAvatar(anyString())).thenReturn(CompletableFuture.completedFuture(null));
@@ -467,10 +467,10 @@ class ProfileControllerTest {
name, null, null,
null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
@@ -516,10 +516,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
@@ -546,10 +546,10 @@ class ProfileControllerTest {
name, null, null,
null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar");
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -575,10 +575,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar"));
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -605,10 +605,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, never()).deleteAvatar(anyString());
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -633,10 +633,10 @@ class ProfileControllerTest {
null, null,
null, false, true, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE))) {
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar"));
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -663,10 +663,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verify(profilesManager, never()).deleteAvatar(anyString());
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -694,10 +694,10 @@ class ProfileControllerTest {
null, null, null, true, false, Optional.of(List.of()), null),
MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar");
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
@@ -731,14 +731,14 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
final VersionedProfile profile = profileArgumentCaptor.getValue();
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(version);
@@ -771,14 +771,14 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
final VersionedProfile profile = profileArgumentCaptor.getValue();
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(version);
@@ -813,7 +813,7 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.hasEntity()).isFalse();
verify(profilesManager, never()).set(any(), any());
verify(profilesManager, never()).setV1(any(), any());
}
}
@@ -831,9 +831,9 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any()))
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), any()))
.thenReturn(Optional.of(
new VersionedProfile("1", name, null, null, null,
new VersionedProfileV1("1", name, null, null, null,
existingPaymentAddressOnProfile ? TestRandomUtil.nextBytes(582) : null,
phoneNumberSharing,
commitment.serialize())));
@@ -852,14 +852,14 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
final VersionedProfile profile = profileArgumentCaptor.getValue();
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(version);
@@ -871,7 +871,7 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.hasEntity()).isFalse();
verify(profilesManager, never()).set(any(), any());
verify(profilesManager, never()).setV1(any(), any());
}
}
}
@@ -895,10 +895,10 @@ class ProfileControllerTest {
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.hasEntity()).isFalse();
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verifyNoMoreInteractions(profilesManager);
@@ -919,7 +919,7 @@ class ProfileControllerTest {
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
final String version = versionHex("validversion");
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfile(
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfileV1(
version, name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes())));
final VersionedProfileResponse profile = resources.getJerseyTest()
@@ -950,13 +950,14 @@ class ProfileControllerTest {
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final String version = versionHex("someversion");
final byte[] version = version("someversion");
final String versionHex = HexFormat.of().formatHex(version);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(
new CreateProfileRequest(commitment, version, name, null, null, paymentAddress, false, false,
new CreateProfileRequest(commitment, versionHex, name, null, null, paymentAddress, false, false,
Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -969,13 +970,14 @@ class ProfileControllerTest {
@Test
void testGetProfileReturnsNoPaymentAddressIfCurrentVersionMismatch() {
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final String version = versionHex("validversion");
when(profilesManager.get(AuthHelper.VALID_UUID_TWO, version)).thenReturn(
Optional.of(new VersionedProfile(null, null, null, null, null, paymentAddress, null, null)));
final byte[] version = version("validversion");
final String versionHex = HexFormat.of().formatHex(version);
when(profilesManager.getV1(AuthHelper.VALID_UUID_TWO, versionHex)).thenReturn(
Optional.of(new VersionedProfileV1(versionHex, null, null, null, null, paymentAddress, null, null)));
{
final VersionedProfileResponse profile = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/" + version)
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/" + versionHex)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
@@ -987,7 +989,7 @@ class ProfileControllerTest {
{
final VersionedProfileResponse profile = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/" + version)
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/" + versionHex)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
@@ -995,11 +997,11 @@ class ProfileControllerTest {
assertThat(profile.paymentAddress()).containsExactly(paymentAddress);
}
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("someotherversion")));
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version("someotherversion")));
{
final VersionedProfileResponse profile = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/" + version)
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/" + versionHex)
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
@@ -1013,13 +1015,13 @@ class ProfileControllerTest {
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("version")));
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version("version")));
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.empty());
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final ExpiringProfileKeyCredentialProfileResponse profile = resources.getJerseyTest()
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, versionHex("version-that-does-not-exist"), "credential-request"))
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, HexFormat.of().formatHex(version("version-that-does-not-exist")), "credential-request"))
.queryParam("credentialType", "expiringProfileKey")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
@@ -1043,12 +1045,13 @@ class ProfileControllerTest {
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final String version = versionHex("anotherversion");
final byte[] version = version("anotherversion");
final String versionHex = HexFormat.of().formatHex(version);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, version, name, emoji, about, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, versionHex, name, emoji, about, null, false, false,
Optional.of(List.of("TEST2")), null), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -1071,7 +1074,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, version, name, emoji, about, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, versionHex, name, emoji, about, null, false, false,
Optional.of(List.of("TEST3", "TEST2")), null), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -1097,7 +1100,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, version, name, emoji, about, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, versionHex, name, emoji, about, null, false, false,
Optional.of(List.of("TEST2", "TEST3")), null), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -1123,7 +1126,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, version, name, emoji, about, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, versionHex, name, emoji, about, null, false, false,
Optional.of(List.of("TEST1")), null), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -1150,7 +1153,8 @@ class ProfileControllerTest {
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
final String version = versionHex("anotherversion");
final byte[] version = version("anotherversion");
final String versionHex = HexFormat.of().formatHex(version);
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
reset(accountsManager);
@@ -1173,7 +1177,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, version, name, emoji, about, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, versionHex, name, emoji, about, null, false, false,
Optional.of(List.of("TEST1")), null), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -1198,7 +1202,8 @@ class ProfileControllerTest {
@MethodSource
void testGetProfileWithExpiringProfileKeyCredential(final MultivaluedMap<String, Object> authHeaders)
throws VerificationFailedException, InvalidInputException {
final String version = versionHex("version");
final byte[] version = version("version");
final String versionHex = HexFormat.of().formatHex(version);
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
final ServerPublicParams serverPublicParams = serverSecretParams.getPublicParams();
@@ -1211,7 +1216,7 @@ class ProfileControllerTest {
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
@@ -1233,12 +1238,12 @@ class ProfileControllerTest {
serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(AuthHelper.VALID_UUID), profileKeyCommitment, expiration);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(profilesManager.getV1(AuthHelper.VALID_UUID, versionHex)).thenReturn(Optional.of(versionedProfile));
when(zkProfileOperations.issueExpiringProfileKeyCredential(eq(credentialRequest), eq(new ServiceId.Aci(AuthHelper.VALID_UUID)), eq(profileKeyCommitment), any()))
.thenReturn(credentialResponse);
final ExpiringProfileKeyCredentialProfileResponse profile = resources.getJerseyTest()
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, version,
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, versionHex,
HexFormat.of().formatHex(credentialRequest.serialize())))
.queryParam("credentialType", "expiringProfileKey")
.request()
@@ -1267,7 +1272,8 @@ class ProfileControllerTest {
@Test
void testGetProfileWithExpiringProfileKeyCredentialBadRequest()
throws VerificationFailedException, InvalidInputException {
final String version = versionHex("version");
final byte[] version = version("version");
final String versionHex = HexFormat.of().formatHex(version);
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
final ServerPublicParams serverPublicParams = serverSecretParams.getPublicParams();
@@ -1279,7 +1285,7 @@ class ProfileControllerTest {
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
@@ -1294,12 +1300,12 @@ class ProfileControllerTest {
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(profilesManager.getV1(AuthHelper.VALID_UUID, versionHex)).thenReturn(Optional.of(versionedProfile));
when(zkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any()))
.thenThrow(new VerificationFailedException());
final Response response = resources.getJerseyTest()
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, version,
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, versionHex,
HexFormat.of().formatHex(credentialRequest.serialize())))
.queryParam("credentialType", "expiringProfileKey")
.request()
@@ -1312,7 +1318,8 @@ class ProfileControllerTest {
@Test
void testGetProfileWithExpiringProfileKeyCredentialNonCurrentVersion()
throws VerificationFailedException, InvalidInputException {
final String version = versionHex("version");
final byte[] version = version("version");
final String versionHex = HexFormat.of().formatHex(version);
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
final ServerPublicParams serverPublicParams = serverSecretParams.getPublicParams();
@@ -1324,7 +1331,7 @@ class ProfileControllerTest {
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
final String avatar = "avatar";
when(versionedProfile.avatar()).thenReturn(avatar);
@@ -1338,13 +1345,13 @@ class ProfileControllerTest {
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY));
when(account.isIdentifiedBy(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(true);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("the-current-version")));
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version("the-current-version")));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
when(profilesManager.getV1(AuthHelper.VALID_UUID, versionHex)).thenReturn(Optional.of(versionedProfile));
final Response response = resources.getJerseyTest()
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, version,
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, versionHex,
HexFormat.of().formatHex(credentialRequest.serialize())))
.queryParam("credentialType", "expiringProfileKey")
.request()
@@ -1580,11 +1587,15 @@ class ProfileControllerTest {
}
}
private static String versionHex(final String versionString) {
private static byte[] version(final String versionString) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(versionString.getBytes(StandardCharsets.UTF_8)));
return MessageDigest.getInstance("SHA-256").digest(versionString.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String versionHex(final String versionString) {
return HexFormat.of().formatHex(version(versionString));
}
}
@@ -21,7 +21,6 @@ import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -45,7 +44,6 @@ import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapp
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@ExtendWith(DropwizardExtensionsSupport.class)
@@ -53,16 +51,12 @@ class RemoteConfigControllerTest {
private static final RemoteConfigsManager remoteConfigsManager = mock(RemoteConfigsManager.class);
private static final long PINNED_EPOCH_SECONDS = 1701287216L;
private static final TestClock TEST_CLOCK = TestClock.pinned(Instant.ofEpochSecond(PINNED_EPOCH_SECONDS));
private static final ResourceExtension resources = ResourceExtension.builder()
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addProvider(new DeviceLimitExceededExceptionMapper())
.addResource(new RemoteConfigController(remoteConfigsManager, Map.of("maxGroupSize", "42"), TEST_CLOCK))
.addResource(new RemoteConfigController(remoteConfigsManager, Map.of("maxGroupSize", "42")))
.build();
@@ -167,7 +161,7 @@ class RemoteConfigControllerTest {
.get(RemoteConfigurationResponse.class);
assertThat(configuration.config().get("linked.config.0")).isEqualTo(configuration.config().get("linked.config.1"));
allUnlinkedConfigsMatched &= (configuration.config().get("linked.config.0") == configuration.config().get("unlinked.config"));
allUnlinkedConfigsMatched &= (configuration.config().get("linked.config.0").equals(configuration.config().get("unlinked.config")));
}
// with 20 test accounts, 1 in 2^20 chance that this fails when it shouldn't, but
@@ -13,20 +13,17 @@ import io.dropwizard.core.Configuration;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import jakarta.servlet.DispatcherType;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.security.Principal;
import java.time.Duration;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -35,14 +32,15 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.security.auth.Subject;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.util.HostPort;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -55,6 +53,7 @@ import org.whispersystems.websocket.messages.protobuf.ProtobufWebSocketMessageFa
import org.whispersystems.websocket.setup.WebSocketEnvironment;
@ExtendWith(DropwizardExtensionsSupport.class)
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class RemoteAddressFilterIntegrationTest {
private static final String WEBSOCKET_PREFIX = "/websocket";
@@ -131,7 +130,7 @@ class RemoteAddressFilterIntegrationTest {
}
}
private static class ClientEndpoint implements WebSocketListener {
public static class ClientEndpoint implements Session.Listener.AutoDemanding {
private final String requestPath;
private final CompletableFuture<byte[]> responseFuture;
@@ -145,22 +144,19 @@ class RemoteAddressFilterIntegrationTest {
}
@Override
public void onWebSocketConnect(final Session session) {
public void onWebSocketOpen(final Session session) {
final byte[] requestBytes = messageFactory.createRequest(Optional.of(1L), "GET", requestPath,
List.of("Accept: application/json"),
Optional.empty()).toByteArray();
try {
session.getRemote().sendBytes(ByteBuffer.wrap(requestBytes));
} catch (IOException e) {
throw new RuntimeException(e);
}
session.sendBinary(ByteBuffer.wrap(requestBytes), Callback.NOOP);
}
@Override
public void onWebSocketBinary(final byte[] payload, final int offset, final int length) {
public void onWebSocketBinary(final ByteBuffer payload, final Callback callback) {
try {
WebSocketMessage webSocketMessage = messageFactory.parseMessage(payload, offset, length);
WebSocketMessage webSocketMessage = messageFactory.parseMessage(payload);
if (Objects.requireNonNull(webSocketMessage.getType()) == WebSocketMessage.Type.RESPONSE_MESSAGE) {
assert 200 == webSocketMessage.getResponseMessage().getStatus();
@@ -206,10 +202,6 @@ class RemoteAddressFilterIntegrationTest {
public void run(final Configuration configuration,
final Environment environment) throws Exception {
environment.servlets().addFilter("RemoteAddressFilterRemoteAddress", new RemoteAddressFilter())
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, REMOTE_ADDRESS_PATH,
WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH);
environment.jersey().register(new TestRemoteAddressController());
// WebSocket set up
@@ -220,15 +212,14 @@ class RemoteAddressFilterIntegrationTest {
webSocketEnvironment.jersey().register(new TestWebSocketController());
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
WebSocketResourceProviderFactory<TestPrincipal> webSocketServlet = new WebSocketResourceProviderFactory<>(
webSocketEnvironment, TestPrincipal.class, webSocketConfiguration,
webSocketEnvironment, TestPrincipal.class,
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
environment.servlets().addServlet("WebSocketRemoteAddress", webSocketServlet)
.addMapping(WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (servletContext, container) -> {
container.addMapping(WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH, webSocketServlet);
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
});
}
}
@@ -0,0 +1,136 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.filters;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import io.dropwizard.core.Application;
import io.dropwizard.core.Configuration;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletContext;
import java.net.InetSocketAddress;
import java.util.EnumSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.ee10.servlet.FilterHolder;
import org.eclipse.jetty.ee10.servlet.FilterMapping;
import org.eclipse.jetty.ee10.servlet.ServletContextHandler;
import org.eclipse.jetty.ee10.servlet.ServletHandler;
import org.eclipse.jetty.ee10.websocket.server.JettyWebSocketCreator;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.http.HostPortHttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http2.api.Session;
import org.eclipse.jetty.http2.api.Stream;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.frames.HeadersFrame;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.Jetty;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(DropwizardExtensionsSupport.class)
class StripContentLengthOnConnectFilterTest {
private static final String WEBSOCKET_WITH_FILTER_PATH = "/websocket/filtered";
private static final String WEBSOCKET_WITHOUT_FILTER_PATH = "/websocket/unfiltered";
private static final DropwizardAppExtension<Configuration> EXTENSION =
new DropwizardAppExtension<>(TestApplicationWithFilter.class, null,
ConfigOverride.config("server.applicationConnectors[0].type", "h2c"),
ConfigOverride.config("server.applicationConnectors[0].port", "0"));
@Test
void contentLengthIsStrippedOnUpgrade() throws Exception {
final HttpFields fields = sendUpgradeRequest(WEBSOCKET_WITH_FILTER_PATH);
assertNull(fields.getField("content-length"));
}
@Test
void contentLengthIncorrectlyIncludedOnUpgrade() throws Exception {
final HttpFields fields = sendUpgradeRequest(WEBSOCKET_WITHOUT_FILTER_PATH);
assertNotNull(fields.getField("content-length"), """
If this fails, our jetty version no longer includes errant content-lengths on H2 connect responses.
StripContentLengthOnConnectFilter can now be removed.
""");
}
@Test
void versionCheck() {
assertEquals("12.1.5", Jetty.VERSION, "This class can be removed with https://github.com/jetty/jetty.project/issues/15074, likely 12.1.10");
}
private static HttpFields sendUpgradeRequest(final String path) throws Exception {
final int port = EXTENSION.getLocalPort();
try (final HTTP2Client client = new HTTP2Client()) {
client.start();
final Session session =
client.connect(new InetSocketAddress("localhost", port), new Session.Listener() {}).join();
final HttpFields requestFields = HttpFields.build().put("sec-websocket-version", "13");
final HostPortHttpField hostPort = new HostPortHttpField("localhost:" + port);
final MetaData.ConnectRequest connect =
new MetaData.ConnectRequest(HttpScheme.HTTP, hostPort, path, requestFields, "websocket");
final HeadersFrame headersFrame = new HeadersFrame(connect, null, false);
final CompletableFuture<MetaData.Response> responseFuture = new CompletableFuture<>();
Stream.Listener streamListener = new Stream.Listener() {
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
if (frame.getMetaData().isResponse()) {
responseFuture.complete((MetaData.Response) frame.getMetaData());
}
}
};
session.newStream(headersFrame, streamListener).get(5, TimeUnit.SECONDS);
final MetaData.Response response = responseFuture.get(5, TimeUnit.SECONDS);
return response.getHttpFields();
}
}
private static class NoopWebSocket implements org.eclipse.jetty.websocket.api.Session.Listener.AutoDemanding {}
public static class TestApplicationWithFilter extends Application<Configuration> {
@Override
public void run(final Configuration configuration, final Environment environment) throws Exception {
final JettyWebSocketCreator jwsc = (_, _) -> new NoopWebSocket();
JettyWebSocketServletContainerInitializer.configure(
environment.getApplicationContext(),
(servletContext, container) -> {
container.addMapping(WEBSOCKET_WITH_FILTER_PATH, jwsc);
container.addMapping(WEBSOCKET_WITHOUT_FILTER_PATH, jwsc);
ensureFilter(servletContext, WEBSOCKET_WITH_FILTER_PATH, StripContentLengthOnConnectFilter.class);
});
}
}
private static void ensureFilter(
final ServletContext servletContext,
final String pathSpec,
final Class<? extends Filter> filterClass) {
final ContextHandler contextHandler = ServletContextHandler.getServletContextHandler(servletContext);
final ServletHandler servletHandler = contextHandler.getDescendant(ServletHandler.class);
final FilterHolder holder = new FilterHolder(filterClass);
final FilterMapping mapping = new FilterMapping();
mapping.setFilterName(holder.getName());
mapping.setPathSpec(pathSpec);
mapping.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST));
servletHandler.prependFilter(holder);
servletHandler.prependFilterMapping(mapping);
}
}
@@ -7,13 +7,12 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import com.google.common.collect.Iterators;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
@@ -28,16 +27,12 @@ import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.collections4.IteratorUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
@@ -79,7 +74,8 @@ import reactor.core.publisher.Flux;
class BackupsAnonymousGrpcServiceTest extends
SimpleBaseGrpcTest<BackupsAnonymousGrpcService, BackupsAnonymousGrpc.BackupsAnonymousBlockingStub> {
private static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = 100;
private static final long MAX_ATTACHMENT_OBJECT_SIZE = 100;
private static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = 200;
private final UUID aci = UUID.randomUUID();
private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32);
@@ -92,7 +88,7 @@ class BackupsAnonymousGrpcServiceTest extends
@Override
protected BackupsAnonymousGrpcService createServiceBeforeEachTest() {
return new BackupsAnonymousGrpcService(backupManager, new BackupMetrics(), MAX_MESSAGE_BACKUP_OBJECT_SIZE);
return new BackupsAnonymousGrpcService(backupManager, new BackupMetrics(), MAX_ATTACHMENT_OBJECT_SIZE, MAX_MESSAGE_BACKUP_OBJECT_SIZE);
}
@BeforeEach
@@ -114,6 +110,16 @@ class BackupsAnonymousGrpcServiceTest extends
.getResponseCase()).isEqualTo(SetPublicKeyResponse.ResponseCase.SUCCESS);
}
@Test
void setPublicKeyBadZkAuth() throws BackupFailedZkAuthenticationException {
doThrow(BackupFailedZkAuthenticationException.class).when(backupManager).setPublicKey(any(), any(), any());
assertThat(unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(ECKeyPair.generate().getPublicKey().serialize()))
.setSignedPresentation(signedPresentation(presentation))
.build())
.getResponseCase()).isEqualTo(SetPublicKeyResponse.ResponseCase.FAILED_AUTHENTICATION);
}
@Test
void setBadPublicKey() {
assertThatExceptionOfType(StatusRuntimeException.class).isThrownBy(() ->
@@ -340,25 +346,27 @@ class BackupsAnonymousGrpcServiceTest extends
@EnumSource(value = GetUploadFormRequest.UploadTypeCase.class, names = "UPLOADTYPE_NOT_SET", mode = EnumSource.Mode.EXCLUDE)
public void uploadForm(GetUploadFormRequest.UploadTypeCase uploadType)
throws BackupException, RateLimitExceededException {
final long uploadLength = 100;
final BackupUploadDescriptor result =
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org");
final GetUploadFormRequest.Builder builder = switch (uploadType) {
case MESSAGES -> {
when(backupManager.createMessageBackupUploadDescriptor(any(), eq(uploadLength)))
when(backupManager.createMessageBackupUploadDescriptor(any(), eq(MAX_MESSAGE_BACKUP_OBJECT_SIZE)))
.thenReturn(result);
yield GetUploadFormRequest.newBuilder().setMessages(GetUploadFormRequest.MessagesUploadType.getDefaultInstance());
yield GetUploadFormRequest.newBuilder()
.setMessages(GetUploadFormRequest.MessagesUploadType.getDefaultInstance())
.setUploadLength(MAX_MESSAGE_BACKUP_OBJECT_SIZE);
}
case MEDIA -> {
when(backupManager.createTemporaryAttachmentUploadDescriptor(any(), eq(uploadLength)))
when(backupManager.createTemporaryAttachmentUploadDescriptor(any(), eq(MAX_ATTACHMENT_OBJECT_SIZE)))
.thenReturn(result);
yield GetUploadFormRequest.newBuilder().setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance());
yield GetUploadFormRequest.newBuilder()
.setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance())
.setUploadLength(MAX_ATTACHMENT_OBJECT_SIZE);
}
default -> throw new IllegalArgumentException("Unknown upload type: " + uploadType);
};
final GetUploadFormRequest request = builder
.setSignedPresentation(signedPresentation(presentation))
.setUploadLength(uploadLength)
.build();
final GetUploadFormResponse response = unauthenticatedServiceStub().getUploadForm(request);
assertThat(response.getUploadForm().getCdn()).isEqualTo(3);
@@ -372,14 +380,15 @@ class BackupsAnonymousGrpcServiceTest extends
public void uploadFormExceedsMax(GetUploadFormRequest.UploadTypeCase uploadType) throws BackupException {
final GetUploadFormRequest.Builder builder = switch (uploadType) {
case MESSAGES -> GetUploadFormRequest.newBuilder()
.setUploadLength(MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1)
.setMessages(GetUploadFormRequest.MessagesUploadType.getDefaultInstance());
case MEDIA -> GetUploadFormRequest.newBuilder()
.setUploadLength(MAX_ATTACHMENT_OBJECT_SIZE + 1)
.setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance());
default -> throw new IllegalArgumentException("Unknown upload type: " + uploadType);
};
final GetUploadFormRequest request = builder
.setSignedPresentation(signedPresentation(presentation))
.setUploadLength(MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1)
.build();
final GetUploadFormResponse response = unauthenticatedServiceStub().getUploadForm(request);
@@ -10,23 +10,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.verifyNoInteractions;
import com.google.protobuf.Any;
import com.google.protobuf.Message;
import com.google.rpc.ErrorInfo;
import com.google.rpc.RetryInfo;
import io.grpc.BindableService;
import io.grpc.ServerInterceptors;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import io.grpc.protobuf.StatusProto;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.function.Executable;
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
public final class GrpcTestUtils {
@@ -34,9 +26,11 @@ public final class GrpcTestUtils {
// noop
}
public static void assertStatusException(final Status expected, final Executable serviceCall) {
public static StatusRuntimeException assertStatusException(final Status expected, final Executable serviceCall) {
final StatusRuntimeException exception = Assertions.assertThrows(StatusRuntimeException.class, serviceCall);
assertEquals(expected.getCode(), exception.getStatus().getCode());
return exception;
}
public static void assertStatusException(final Status expected, final String expectedReason, final Executable serviceCall) {
@@ -45,16 +39,16 @@ public final class GrpcTestUtils {
assertEquals(expectedReason, extractErrorInfo(exception).getReason());
}
public static void assertStatusInvalidArgument(final Executable serviceCall) {
assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
public static StatusRuntimeException assertStatusInvalidArgument(final Executable serviceCall) {
return assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
}
public static void assertStatusUnauthenticated(final Executable serviceCall) {
assertStatusException(Status.UNAUTHENTICATED, serviceCall);
public static StatusRuntimeException assertStatusUnauthenticated(final Executable serviceCall) {
return assertStatusException(Status.UNAUTHENTICATED, serviceCall);
}
public static void assertStatusPermissionDenied(final Executable serviceCall) {
assertStatusException(Status.PERMISSION_DENIED, serviceCall);
public static StatusRuntimeException assertStatusPermissionDenied(final Executable serviceCall) {
return assertStatusException(Status.PERMISSION_DENIED, serviceCall);
}
public static void assertRateLimitExceeded(
@@ -68,8 +62,8 @@ public final class GrpcTestUtils {
final ErrorInfo errorInfo = extractErrorInfo(exception);
final RetryInfo retryInfo = extractDetail(RetryInfo.class, exception);
final Duration actual = Duration.ofSeconds(retryInfo.getRetryDelay().getSeconds(), retryInfo.getRetryDelay().getNanos());
assertEquals(errorInfo.getDomain(), GrpcExceptions.DOMAIN);
assertEquals(errorInfo.getReason(), "RESOURCE_EXHAUSTED");
assertEquals(GrpcExceptions.DOMAIN, errorInfo.getDomain());
assertEquals("RESOURCE_EXHAUSTED", errorInfo.getReason());
assertEquals(expectedRetryAfter, actual);
for (final Object mock: mocksToCheckForNoInteraction) {
@@ -54,6 +54,7 @@ import org.signal.chat.messages.SendMultiRecipientStoryRequest;
import org.signal.chat.messages.SendSealedSenderMessageRequest;
import org.signal.chat.messages.SendStoryMessageRequest;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -156,7 +157,7 @@ class MessagesAnonymousGrpcServiceTest extends
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
@CartesianTest.Values(booleans = {true, false}) final boolean includeReportSpamToken)
throws MessageTooLargeException, MismatchedDevicesException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -244,7 +245,8 @@ class MessagesAnonymousGrpcServiceTest extends
.setType(SendMessageType.DOUBLE_RATCHET)
.setPayload(ByteString.copyFrom(payload))
.build());
final byte[] reportSpamToken = TestRandomUtil.nextBytes(64);
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().sendSingleRecipientMessage(
generateRequest(serviceIdentifier, false, true, messages, UNIDENTIFIED_ACCESS_KEY, null)));
@@ -254,8 +256,7 @@ class MessagesAnonymousGrpcServiceTest extends
@CartesianTest
void sendUnrestrictedAccessMessage(
@CartesianTest.Values(booleans = {true, false}) final boolean useUak,
@CartesianTest.Values(booleans = {true, false}) final boolean isUua)
throws MessageTooLargeException, MismatchedDevicesException {
@CartesianTest.Values(booleans = {true, false}) final boolean isUua) {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -289,7 +290,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void mismatchedDevices() throws MessageTooLargeException, MismatchedDevicesException {
void mismatchedDevices()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -328,7 +330,8 @@ class MessagesAnonymousGrpcServiceTest extends
@ParameterizedTest
@ValueSource(booleans = {true, false})
void badCredentials(final boolean useUak) throws MessageTooLargeException, MismatchedDevicesException {
void badCredentials(final boolean useUak)
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -367,7 +370,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void destinationNotFound() throws MessageTooLargeException, MismatchedDevicesException {
void destinationNotFound()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
@@ -388,7 +392,7 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void pniIdentifierWithUak() throws MessageTooLargeException, MismatchedDevicesException {
void pniIdentifierWithUak() {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
final Device destinationDevice = DevicesHelper.createDevice(deviceId, CLOCK.millis(), registrationId);
@@ -410,13 +414,15 @@ class MessagesAnonymousGrpcServiceTest extends
final SendSealedSenderMessageRequest request =
generateRequest(pniIdentifier, false, true, messages, UNIDENTIFIED_ACCESS_KEY, null);
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(
Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().sendSingleRecipientMessage(request));
}
@Test
void rateLimited() throws RateLimitExceededException, MessageTooLargeException, MismatchedDevicesException {
void rateLimited()
throws RateLimitExceededException, MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -450,7 +456,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void oversizedMessage() throws MessageTooLargeException, MismatchedDevicesException {
void oversizedMessage()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -470,14 +477,15 @@ class MessagesAnonymousGrpcServiceTest extends
doThrow(new MessageTooLargeException())
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().sendSingleRecipientMessage(
generateRequest(serviceIdentifier, false, true, messages, UNIDENTIFIED_ACCESS_KEY, null)));
}
@Test
void spamWithStatus() throws MessageTooLargeException, MismatchedDevicesException {
void spamWithStatus()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -502,7 +510,7 @@ class MessagesAnonymousGrpcServiceTest extends
Optional.of(GrpcChallengeResponse.withStatusException(GrpcExceptions.rateLimitExceeded(null))),
Optional.empty()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED,
() -> unauthenticatedServiceStub().sendSingleRecipientMessage(
generateRequest(serviceIdentifier, false, true, messages, UNIDENTIFIED_ACCESS_KEY, null)));
@@ -516,7 +524,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void spamWithResponse() throws MessageTooLargeException, MismatchedDevicesException {
void spamWithResponse()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -544,6 +553,8 @@ class MessagesAnonymousGrpcServiceTest extends
final SendSealedSenderMessageRequest request =
generateRequest(serviceIdentifier, false, true, messages, UNIDENTIFIED_ACCESS_KEY, null);
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED, () ->
unauthenticatedServiceStub().sendSingleRecipientMessage(request));
@@ -555,6 +566,42 @@ class MessagesAnonymousGrpcServiceTest extends
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
}
@Test
void messageDeliveryNotAllowed()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
final Device destinationDevice = DevicesHelper.createDevice(deviceId, CLOCK.millis(), registrationId);
final Account destinationAccount = mock(Account.class);
when(destinationAccount.getDevices()).thenReturn(List.of(destinationDevice));
when(destinationAccount.getDevice(deviceId)).thenReturn(Optional.of(destinationDevice));
when(destinationAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY));
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(destinationAccount));
final byte[] payload = TestRandomUtil.nextBytes(128);
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
Map.of(deviceId, IndividualRecipientMessageBundle.Message.newBuilder()
.setRegistrationId(registrationId)
.setPayload(ByteString.copyFrom(payload))
.setType(SendMessageType.UNIDENTIFIED_SENDER)
.build());
doThrow(MessageDeliveryNotAllowedException.class)
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
() -> unauthenticatedServiceStub().sendSingleRecipientMessage(
generateRequest(serviceIdentifier, false, false, messages,
null,
GROUP_SEND_TOKEN)));
}
private static SendSealedSenderMessageRequest generateRequest(final ServiceIdentifier serviceIdentifier,
final boolean ephemeral,
final boolean urgent,
@@ -595,7 +642,7 @@ class MessagesAnonymousGrpcServiceTest extends
@CartesianTest
void sendMessage(@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
@CartesianTest.Values(booleans = {true, false}) final boolean urgent)
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -656,7 +703,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void mismatchedDevices() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void mismatchedDevices()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -704,7 +752,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void badCredentials() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void badCredentials()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -739,7 +788,7 @@ class MessagesAnonymousGrpcServiceTest extends
.setUrgent(true)
.build()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
unauthenticatedServiceStub().sendMultiRecipientMessage(SendMultiRecipientMessageRequest.newBuilder()
.setMessage(MultiRecipientMessage.newBuilder()
@@ -755,8 +804,9 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void badPayload() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
//noinspection ResultOfMethodCallIgnored
void badPayload()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
unauthenticatedServiceStub().sendMultiRecipientMessage(SendMultiRecipientMessageRequest.newBuilder()
.setMessage(MultiRecipientMessage.newBuilder()
@@ -765,7 +815,7 @@ class MessagesAnonymousGrpcServiceTest extends
.build())
.build()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
unauthenticatedServiceStub().sendMultiRecipientMessage(SendMultiRecipientMessageRequest.newBuilder().build()));
@@ -774,7 +824,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void repeatedRecipient() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void repeatedRecipient()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final Device destinationDevice = DevicesHelper.createDevice(Device.PRIMARY_ID, CLOCK.millis(), 1);
final Account destinationAccount = mock(Account.class);
@@ -790,7 +841,7 @@ class MessagesAnonymousGrpcServiceTest extends
final byte[] payload = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(recipient, recipient));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
unauthenticatedServiceStub().sendMultiRecipientMessage(SendMultiRecipientMessageRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(GROUP_SEND_TOKEN))
@@ -807,7 +858,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void oversizedMessage() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void oversizedMessage()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final Account destinationAccount = mock(Account.class);
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
@@ -831,13 +883,14 @@ class MessagesAnonymousGrpcServiceTest extends
doThrow(new MessageTooLargeException())
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().sendMultiRecipientMessage(request));
}
@Test
void spamWithStatus() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void spamWithStatus()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -872,7 +925,7 @@ class MessagesAnonymousGrpcServiceTest extends
Optional.of(GrpcChallengeResponse.withStatusException(GrpcExceptions.rateLimitExceeded(null))),
Optional.empty()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED,
() -> unauthenticatedServiceStub().sendMultiRecipientMessage(request));
@@ -883,7 +936,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void spamWithResponse() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void spamWithResponse()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -918,7 +972,7 @@ class MessagesAnonymousGrpcServiceTest extends
when(spamChecker.checkForMultiRecipientSpamGrpc(any()))
.thenReturn(new SpamCheckResult<>(Optional.of(GrpcChallengeResponse.withResponse(challengeResponse)), Optional.empty()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED,
() -> unauthenticatedServiceStub().sendMultiRecipientMessage(request));
@@ -927,6 +981,41 @@ class MessagesAnonymousGrpcServiceTest extends
verify(messageSender, never())
.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
}
@Test
void messageDeliveryNotAllowed()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
final Account destinationAccount = mock(Account.class);
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(destinationAccount)));
final byte[] payload = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
new TestRecipient(serviceIdentifier, staleDeviceId, 17, new byte[48])));
final SendMultiRecipientMessageRequest request = SendMultiRecipientMessageRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(GROUP_SEND_TOKEN))
.setMessage(MultiRecipientMessage.newBuilder()
.setTimestamp(CLOCK.millis())
.setPayload(ByteString.copyFrom(payload))
.build())
.setEphemeral(false)
.setUrgent(true)
.build();
doThrow(MessageDeliveryNotAllowedException.class)
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
() -> unauthenticatedServiceStub().sendMultiRecipientMessage(request));
}
}
@Nested
@@ -935,7 +1024,7 @@ class MessagesAnonymousGrpcServiceTest extends
@CartesianTest
void sendStory(@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
@CartesianTest.Values(booleans = {true, false}) final boolean includeReportSpamToken)
throws MessageTooLargeException, MismatchedDevicesException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -998,7 +1087,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void mismatchedDevices() throws MessageTooLargeException, MismatchedDevicesException {
void mismatchedDevices()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -1036,7 +1126,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void destinationNotFound() throws MessageTooLargeException, MismatchedDevicesException {
void destinationNotFound()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
Map.of(Device.PRIMARY_ID, IndividualRecipientMessageBundle.Message.newBuilder()
.setRegistrationId(7)
@@ -1053,7 +1144,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void rateLimited() throws RateLimitExceededException, MessageTooLargeException, MismatchedDevicesException {
void rateLimited()
throws RateLimitExceededException, MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -1085,7 +1177,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void oversizedMessage() throws MessageTooLargeException, MismatchedDevicesException {
void oversizedMessage()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -1105,13 +1198,14 @@ class MessagesAnonymousGrpcServiceTest extends
doThrow(new MessageTooLargeException()).when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusInvalidArgument(
() -> unauthenticatedServiceStub().sendStory(generateRequest(serviceIdentifier, false, messages)));
}
@Test
void spamWithStatus() throws MessageTooLargeException, MismatchedDevicesException {
void spamWithStatus()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -1136,7 +1230,7 @@ class MessagesAnonymousGrpcServiceTest extends
Optional.of(GrpcChallengeResponse.withStatusException(GrpcExceptions.rateLimitExceeded(null))),
Optional.empty()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED,
() -> unauthenticatedServiceStub().sendStory(generateRequest(serviceIdentifier, true, messages)));
@@ -1149,7 +1243,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void spamWithResponse() throws MessageTooLargeException, MismatchedDevicesException {
void spamWithResponse()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -1174,6 +1269,7 @@ class MessagesAnonymousGrpcServiceTest extends
when(spamChecker.checkForIndividualRecipientSpamGrpc(any(), any(), any(), any()))
.thenReturn(new SpamCheckResult<>(Optional.of(GrpcChallengeResponse.withResponse(challengeResponse)), Optional.empty()));
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED, () ->
unauthenticatedServiceStub().sendStory(generateRequest(serviceIdentifier, true, messages)));
@@ -1185,6 +1281,38 @@ class MessagesAnonymousGrpcServiceTest extends
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
}
@Test
void messageDeliveryNotAllowed()
throws MessageTooLargeException, MessageDeliveryNotAllowedException, MismatchedDevicesException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
final Device destinationDevice = DevicesHelper.createDevice(deviceId, CLOCK.millis(), registrationId);
final Account destinationAccount = mock(Account.class);
when(destinationAccount.getDevices()).thenReturn(List.of(destinationDevice));
when(destinationAccount.getDevice(deviceId)).thenReturn(Optional.of(destinationDevice));
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(destinationAccount));
final byte[] payload = TestRandomUtil.nextBytes(128);
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
Map.of(deviceId, IndividualRecipientMessageBundle.Message.newBuilder()
.setRegistrationId(registrationId)
.setPayload(ByteString.copyFrom(payload))
.setType(SendMessageType.UNIDENTIFIED_SENDER)
.build());
doThrow(MessageDeliveryNotAllowedException.class)
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
() -> unauthenticatedServiceStub().sendStory(generateRequest(serviceIdentifier, false, messages)));
}
private static SendStoryMessageRequest generateRequest(final ServiceIdentifier serviceIdentifier,
final boolean urgent,
final Map<Byte, IndividualRecipientMessageBundle.Message> messages) {
@@ -1207,7 +1335,8 @@ class MessagesAnonymousGrpcServiceTest extends
@ParameterizedTest
@ValueSource(booleans = {true, false})
void sendStory(final boolean urgent) throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void sendStory(final boolean urgent)
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -1260,7 +1389,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void mismatchedDevices() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void mismatchedDevices()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -1306,8 +1436,9 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void badPayload() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
//noinspection ResultOfMethodCallIgnored
void badPayload()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
unauthenticatedServiceStub().sendMultiRecipientStory(SendMultiRecipientStoryRequest.newBuilder()
.setMessage(MultiRecipientMessage.newBuilder()
@@ -1316,7 +1447,7 @@ class MessagesAnonymousGrpcServiceTest extends
.build())
.build()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
unauthenticatedServiceStub().sendMultiRecipientMessage(
SendMultiRecipientMessageRequest.newBuilder().build()));
@@ -1326,7 +1457,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void repeatedRecipient() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void repeatedRecipient()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final Device destinationDevice = DevicesHelper.createDevice(Device.PRIMARY_ID, CLOCK.millis(), 1);
final Account destinationAccount = mock(Account.class);
@@ -1342,7 +1474,7 @@ class MessagesAnonymousGrpcServiceTest extends
final byte[] payload = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(recipient, recipient));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () ->
unauthenticatedServiceStub().sendMultiRecipientStory(SendMultiRecipientStoryRequest.newBuilder()
.setMessage(MultiRecipientMessage.newBuilder()
@@ -1357,7 +1489,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void oversizedMessage() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void oversizedMessage()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final Account destinationAccount = mock(Account.class);
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
@@ -1379,12 +1512,13 @@ class MessagesAnonymousGrpcServiceTest extends
doThrow(new MessageTooLargeException())
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusInvalidArgument(() -> unauthenticatedServiceStub().sendMultiRecipientStory(request));
}
@Test
void spamWithStatus() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void spamWithStatus()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -1417,7 +1551,7 @@ class MessagesAnonymousGrpcServiceTest extends
Optional.of(GrpcChallengeResponse.withStatusException(GrpcExceptions.rateLimitExceeded(null))),
Optional.empty()));
//noinspection ResultOfMethodCallIgnored
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED,
() -> unauthenticatedServiceStub().sendMultiRecipientStory(request));
@@ -1428,7 +1562,8 @@ class MessagesAnonymousGrpcServiceTest extends
}
@Test
void spamWithResponse() throws MessageTooLargeException, MultiRecipientMismatchedDevicesException {
void spamWithResponse()
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -1461,6 +1596,7 @@ class MessagesAnonymousGrpcServiceTest extends
when(spamChecker.checkForMultiRecipientSpamGrpc(any()))
.thenReturn(new SpamCheckResult<>(Optional.of(GrpcChallengeResponse.withResponse(challengeResponse)), Optional.empty()));
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED, () ->
unauthenticatedServiceStub().sendMultiRecipientStory(request));
@@ -1469,5 +1605,47 @@ class MessagesAnonymousGrpcServiceTest extends
verify(messageSender, never())
.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
}
@Test
void messageDeliveryNotAllowed()
throws MessageTooLargeException, MessageDeliveryNotAllowedException, MultiRecipientMismatchedDevicesException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
final Device destinationDevice = DevicesHelper.createDevice(deviceId, CLOCK.millis(), registrationId);
final Account resolvedAccount = mock(Account.class);
when(resolvedAccount.getDevices()).thenReturn(List.of(destinationDevice));
when(resolvedAccount.getDevice(deviceId)).thenReturn(Optional.of(destinationDevice));
final AciServiceIdentifier resolvedServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final AciServiceIdentifier unresolvedServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(accountsManager.getByServiceIdentifierAsync(resolvedServiceIdentifier))
.thenReturn(CompletableFuture.completedFuture(Optional.of(resolvedAccount)));
final TestRecipient resolvedRecipient =
new TestRecipient(resolvedServiceIdentifier, deviceId, registrationId, new byte[48]);
final TestRecipient unresolvedRecipient =
new TestRecipient(unresolvedServiceIdentifier, Device.PRIMARY_ID, 1, new byte[48]);
final byte[] payload = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
resolvedRecipient, unresolvedRecipient));
doThrow(MessageDeliveryNotAllowedException.class)
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
final SendMultiRecipientStoryRequest request = SendMultiRecipientStoryRequest.newBuilder()
.setMessage(MultiRecipientMessage.newBuilder()
.setTimestamp(CLOCK.millis())
.setPayload(ByteString.copyFrom(payload))
.build())
.build();
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
() -> unauthenticatedServiceStub().sendMultiRecipientStory(request));
}
}
}
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more