mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 09:06:47 +00:00
Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f6d80cb39 | ||
|
|
da439e7144 | ||
|
|
22656396dc | ||
|
|
90b280d6a0 | ||
|
|
482a1b7bb5 | ||
|
|
fea4300d7d | ||
|
|
66b0ed16d1 | ||
|
|
defbc1c853 | ||
|
|
68a5e4e8ee | ||
|
|
f83efce4d4 | ||
|
|
0945e953f2 | ||
|
|
51f6e57bbd | ||
|
|
539a84d0d0 | ||
|
|
848c457bbe | ||
|
|
c5ae3963b5 | ||
|
|
771fecd396 | ||
|
|
b9a24fedea | ||
|
|
9d3b6ebb4a | ||
|
|
2cf91af5d9 | ||
|
|
d0e022c23b | ||
|
|
460e5cb499 | ||
|
|
23305e4460 | ||
|
|
06d96a04df | ||
|
|
022f2b874d | ||
|
|
b09a9b8f39 | ||
|
|
4e72422cfd | ||
|
|
d41c73917f | ||
|
|
dd29ee1f27 | ||
|
|
9dc6e049f4 | ||
|
|
7fe3d4a30f | ||
|
|
88a308fac0 | ||
|
|
34f5351a4c | ||
|
|
59f704b6cc | ||
|
|
0f7d5d7fa4 | ||
|
|
1ae361b15f | ||
|
|
2c9676a1ef | ||
|
|
2ae5c92df2 | ||
|
|
3c02f8c3e1 | ||
|
|
4c4282162f | ||
|
|
0beeb8a935 | ||
|
|
8d0ad7b085 |
No files matched your search
@@ -9,19 +9,22 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
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 +34,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,37 +42,49 @@ 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());
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, Clock.systemUTC());
|
||||
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(
|
||||
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
|
||||
dynamoDbClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
|
||||
|
||||
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) {
|
||||
return phoneNumberIdentifiers
|
||||
.getPhoneNumberIdentifier(phoneNumber)
|
||||
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password))
|
||||
.thenRun(Util.NOOP);
|
||||
public void populateRecoveryPassword(final String phoneNumber, final byte[] password) {
|
||||
try {
|
||||
final UUID pni = phoneNumberIdentifiers
|
||||
.getPhoneNumberIdentifier(phoneNumber).get(5, TimeUnit.SECONDS);
|
||||
registrationRecoveryPasswordsManager.store(pni, password);
|
||||
} catch (ExecutionException | InterruptedException | TimeoutException e) {
|
||||
throw new RuntimeException("failed to get pni", e);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
return verificationSessionManager.findForId(sessionId)
|
||||
.thenApply(maybeSession -> maybeSession.map(VerificationSession::pushChallenge));
|
||||
public Optional<String> peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
return verificationSessionManager.findForId(sessionId).map(VerificationSession::pushChallenge);
|
||||
}
|
||||
|
||||
public void clearChangeNumberWaitingPeriod(TestUser user) {
|
||||
changeNumberWaitingPeriods.delete(user.aciUuid());
|
||||
}
|
||||
}
|
||||
@@ -117,17 +117,21 @@ public final class Operations {
|
||||
}
|
||||
|
||||
public static String peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
return INTEGRATION_TOOLS.peekVerificationSessionPushChallenge(sessionId).join()
|
||||
return INTEGRATION_TOOLS.peekVerificationSessionPushChallenge(sessionId)
|
||||
.orElseThrow(() -> new RuntimeException("push challenge not found for the verification session"));
|
||||
}
|
||||
|
||||
public static byte[] populateRandomRecoveryPassword(final String number) {
|
||||
final byte[] recoveryPassword = randomBytes(32);
|
||||
INTEGRATION_TOOLS.populateRecoveryPassword(number, recoveryPassword).join();
|
||||
INTEGRATION_TOOLS.populateRecoveryPassword(number, recoveryPassword);
|
||||
|
||||
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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -92,6 +92,8 @@ dynamoDbTables:
|
||||
tableName: Example_AppleDeviceCheckPublicKeys
|
||||
backups:
|
||||
tableName: Example_Backups
|
||||
changeNumberWaitingPeriods:
|
||||
tableName: Example_ChangeNumberWaitingPeriods
|
||||
clientReleases:
|
||||
tableName: Example_ClientReleases
|
||||
deletedAccounts:
|
||||
@@ -146,8 +148,6 @@ dynamoDbTables:
|
||||
expiration: P7D
|
||||
subscriptions:
|
||||
tableName: Example_Subscriptions
|
||||
clientPublicKeys:
|
||||
tableName: Example_ClientPublicKeys
|
||||
verificationSessions:
|
||||
tableName: Example_VerificationSessions
|
||||
|
||||
@@ -517,6 +517,7 @@ idlePrimaryDeviceReminder:
|
||||
|
||||
grpc:
|
||||
port: 50051
|
||||
websocketPort: 8080
|
||||
|
||||
asnTable:
|
||||
s3Region: a-region
|
||||
|
||||
+53
-4
@@ -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,17 +446,59 @@
|
||||
<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>
|
||||
<classifier>linux-x86_64</classifier>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-testsuite-common</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>${netty.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-core</artifactId>
|
||||
|
||||
@@ -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;
|
||||
@@ -164,7 +170,10 @@ 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;
|
||||
@@ -193,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;
|
||||
@@ -226,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;
|
||||
@@ -314,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> {
|
||||
|
||||
@@ -504,10 +516,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbAsyncClient,
|
||||
dynamoDbClient,
|
||||
clock);
|
||||
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(dynamoDbAsyncClient,
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(dynamoDbClient,
|
||||
config.getDynamoDbTables().getVerificationSessions().getTableName(), clock);
|
||||
|
||||
final ClientResources sharedClientResources = ClientResources.builder()
|
||||
@@ -617,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)
|
||||
@@ -696,15 +707,19 @@ 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);
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
|
||||
apnSender, fcmSender, accountsManager, 0, 0, retryExecutor);
|
||||
@@ -722,10 +737,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbAsyncClient);
|
||||
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
|
||||
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
|
||||
dynamoDbAsyncClient,
|
||||
dynamoDbClient,
|
||||
config.getDynamoDbTables().getRedeemedReceipts().getExpiration());
|
||||
Subscriptions subscriptions = new Subscriptions(
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient);
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient);
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
|
||||
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
|
||||
CallQualitySurveyManager callQualitySurveyManager = new CallQualitySurveyManager(asnInfoProviderSupplier,
|
||||
@@ -1013,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(),
|
||||
@@ -1048,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,
|
||||
@@ -1097,7 +1124,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
config.getChangeNumber().postRegistrationWaitingPeriod(), Clock.systemUTC());
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
@@ -1134,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(),
|
||||
@@ -1143,7 +1170,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
|
||||
dynamicConfigurationManager, clock)
|
||||
dynamicConfigurationManager, experimentEnrollmentManager, clock)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
@@ -1174,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,
|
||||
|
||||
+2
-3
@@ -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;
|
||||
|
||||
+4
-2
@@ -15,6 +15,7 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -129,10 +130,11 @@ public class PhoneVerificationTokenManager {
|
||||
}
|
||||
|
||||
try {
|
||||
final boolean verified = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
|
||||
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword))
|
||||
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
|
||||
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
|
||||
|
||||
if (!verified) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
}
|
||||
|
||||
+1
-1
@@ -152,7 +152,7 @@ public class RegistrationLockVerificationManager {
|
||||
// This allows users to re-register via registration recovery password
|
||||
// instead of always being forced to fall back to SMS verification.
|
||||
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
|
||||
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI)).join();
|
||||
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
|
||||
}
|
||||
|
||||
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
|
||||
+1
-2
@@ -266,8 +266,7 @@ public class BackupAuthManager {
|
||||
}
|
||||
|
||||
boolean receiptAllowed = redeemedReceiptsManager
|
||||
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
|
||||
.join();
|
||||
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid());
|
||||
if (!receiptAllowed) {
|
||||
throw new BackupBadReceiptException("receipt serial is already redeemed");
|
||||
}
|
||||
|
||||
+9
-9
@@ -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;
|
||||
@@ -78,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,
|
||||
@@ -106,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;
|
||||
@@ -145,6 +145,12 @@ public class DynamoDbTables {
|
||||
return appleDeviceChecks;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getChangeNumberWaitingPeriods() {
|
||||
return changeNumberWaitingPeriods;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getAppleDeviceCheckPublicKeys() {
|
||||
@@ -157,12 +163,6 @@ public class DynamoDbTables {
|
||||
return backups;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getClientPublicKeys() {
|
||||
return clientPublicKeys;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getClientReleases() {
|
||||
|
||||
+23
-1
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -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) {
|
||||
}
|
||||
+1
-2
@@ -244,8 +244,7 @@ public class AccountController {
|
||||
// if registration recovery password was sent to us, store it (or refresh its expiration)
|
||||
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> {
|
||||
final boolean rrpCreated = registrationRecoveryPasswordsManager
|
||||
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
|
||||
.join();
|
||||
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword);
|
||||
Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("outcome", rrpCreated ? "created" : "updated")))
|
||||
|
||||
+1
-1
@@ -117,7 +117,7 @@ public class DonationController {
|
||||
}
|
||||
|
||||
final boolean receiptMatched = redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier()).join();
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier());
|
||||
if (!receiptMatched) {
|
||||
return Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt serial is already redeemed")
|
||||
|
||||
+3
-3
@@ -216,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) {
|
||||
@@ -436,7 +436,7 @@ public class ProfileController {
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
|
||||
|
||||
if (account.getCurrentProfileVersion().map(version::equals).orElse(false)) {
|
||||
if (account.getCurrentProfileVersion().map(v -> HexFormat.of().formatHex(v).equals(version)).orElse(false)) {
|
||||
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
|
||||
.map(profile -> {
|
||||
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
|
||||
@@ -488,7 +488,7 @@ public class ProfileController {
|
||||
// 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(p.version())).orElse(true))
|
||||
.filter(p -> account.getCurrentProfileVersion().map(v -> HexFormat.of().formatHex(v).equals(p.version())).orElse(true))
|
||||
.map(VersionedProfileV1::paymentAddress)
|
||||
.orElse(null);
|
||||
|
||||
|
||||
+1
-6
@@ -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;
|
||||
}
|
||||
|
||||
+20
-20
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
@@ -60,7 +61,6 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.slf4j.Logger;
|
||||
@@ -74,7 +74,9 @@ import org.whispersystems.textsecuregcm.entities.SubmitVerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
|
||||
@@ -113,7 +115,6 @@ public class VerificationController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VerificationController.class);
|
||||
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
private static final Duration DYNAMODB_TIMEOUT = Duration.ofSeconds(5);
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
@@ -133,6 +134,9 @@ public class VerificationController {
|
||||
private static final String EXISTING_ACCOUNT_PLATFORM = "existingAccountPlatform";
|
||||
private static final String EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME = "existingAccountRecentlySeen";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME = "verificationCodePushNotification";
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final VerificationSessionManager verificationSessionManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
@@ -144,6 +148,7 @@ public class VerificationController {
|
||||
private final CarrierDataProvider carrierDataProvider;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final Clock clock;
|
||||
|
||||
public VerificationController(final RegistrationServiceClient registrationServiceClient,
|
||||
@@ -157,6 +162,7 @@ public class VerificationController {
|
||||
final CarrierDataProvider carrierDataProvider,
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final Clock clock) {
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
@@ -169,6 +175,7 @@ public class VerificationController {
|
||||
this.carrierDataProvider = carrierDataProvider;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -255,7 +262,7 @@ public class VerificationController {
|
||||
// if a push challenge sent in `handlePushToken` doesn't arrive in time
|
||||
verificationSession.requestedInformation().add(VerificationSession.Information.CAPTCHA);
|
||||
|
||||
storeVerificationSession(verificationSession);
|
||||
verificationSessionManager.insert(verificationSession);
|
||||
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
@@ -328,24 +335,12 @@ public class VerificationController {
|
||||
} finally {
|
||||
// Each of the handle* methods may update requestedInformation, submittedInformation, and allowedToRequestCode,
|
||||
// and we want to be sure to store a changes, even if a later method throws
|
||||
updateStoredVerificationSession(verificationSession);
|
||||
verificationSessionManager.update(verificationSession);
|
||||
}
|
||||
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
private void storeVerificationSession(final VerificationSession verificationSession) {
|
||||
verificationSessionManager.insert(verificationSession)
|
||||
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
|
||||
.join();
|
||||
}
|
||||
|
||||
private void updateStoredVerificationSession(final VerificationSession verificationSession) {
|
||||
verificationSessionManager.update(verificationSession)
|
||||
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
|
||||
.join();
|
||||
}
|
||||
|
||||
/**
|
||||
* If {@code pushTokenAndType} values are not {@code null}, sends a push challenge. If there is no existing push
|
||||
* challenge in the session, one will be created, set on the returned session record, and
|
||||
@@ -656,6 +651,12 @@ public class VerificationController {
|
||||
acceptLanguage.orElse(null),
|
||||
senderOverride,
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
|
||||
accountsManager.getByE164(registrationServiceSession.number())
|
||||
.filter(existingAccount ->
|
||||
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
.ifPresent(existingAccount ->
|
||||
pushNotificationManager.trySendVerificationCodeRequestedNotifications(existingAccount, clock.instant()));
|
||||
} catch (final CancellationException e) {
|
||||
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
@@ -792,7 +793,7 @@ public class VerificationController {
|
||||
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
|
||||
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
|
||||
// can always just fallback to session-based verification.
|
||||
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
|
||||
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
Optional<Account> maybeExistingAccount;
|
||||
@@ -868,7 +869,7 @@ public class VerificationController {
|
||||
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
|
||||
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
|
||||
// can always just fallback to session-based verification.
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
return registrationServiceSession;
|
||||
@@ -892,8 +893,7 @@ public class VerificationController {
|
||||
private VerificationSession retrieveVerificationSession(final RegistrationServiceSession registrationServiceSession) {
|
||||
|
||||
return verificationSessionManager.findForId(registrationServiceSession.encodedSessionId())
|
||||
.orTimeout(5, TimeUnit.SECONDS)
|
||||
.join().orElseThrow(NotFoundException::new);
|
||||
.orElseThrow(NotFoundException::new);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
-45
@@ -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());
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
-4
@@ -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 {
|
||||
|
||||
+71
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -263,8 +263,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
@Override
|
||||
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
|
||||
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
|
||||
request.getRegistrationRecoveryPassword().toByteArray())
|
||||
.join();
|
||||
request.getRegistrationRecoveryPassword().toByteArray());
|
||||
|
||||
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ public class ProfileGrpcHelper {
|
||||
|
||||
// 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 -> v.equals(HexFormat.of().formatHex(requestVersion))).orElse(true)) {
|
||||
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()) {
|
||||
|
||||
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.time.Clock;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -107,11 +108,8 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
validateRequest(request);
|
||||
|
||||
final String expectedCurrentVersionHex = HexFormat.of().formatHex(request.getExpectedCurrentVersion().toByteArray());
|
||||
|
||||
final boolean currentVersionMatchesExpected = account.getCurrentProfileVersion().isEmpty()
|
||||
? request.getExpectedCurrentVersion().isEmpty()
|
||||
: account.getCurrentProfileVersion().get().equals(expectedCurrentVersionHex);
|
||||
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()
|
||||
@@ -177,7 +175,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
}
|
||||
|
||||
try {
|
||||
accountsManager.updateCurrentProfileVersion(account.getIdentifier(IdentityType.ACI), version, expectedCurrentVersionHex, a -> {
|
||||
accountsManager.updateCurrentProfileVersion(account.getIdentifier(IdentityType.ACI), version, expectedCurrentVersion, a -> {
|
||||
|
||||
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
|
||||
|
||||
+2
@@ -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 {
|
||||
|
||||
+91
@@ -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();
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.netty4.NettyEventExecutorMetrics;
|
||||
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 start() {
|
||||
new NettyEventExecutorMetrics(eventLoopGroup).bindTo(Metrics.globalRegistry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() throws Exception {
|
||||
this.eventLoopGroup.shutdownGracefully().await();
|
||||
}
|
||||
|
||||
public T getEventLoopGroup() {
|
||||
return eventLoopGroup;
|
||||
}
|
||||
}
|
||||
-16
@@ -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();
|
||||
}
|
||||
}
|
||||
+38
@@ -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);
|
||||
}
|
||||
}
|
||||
+55
@@ -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,167 @@
|
||||
/*
|
||||
* 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");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+230
@@ -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;
|
||||
}
|
||||
}
|
||||
+42
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
-2
@@ -40,8 +40,6 @@ public class JettyHttpConfigurationCustomizer implements Container.Listener, Lif
|
||||
httpConfiguration.setNotifyRemoteAsyncErrors(false);
|
||||
}
|
||||
}
|
||||
|
||||
c.addBean(new JettyConnectionMetrics(Metrics.globalRegistry));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -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);
|
||||
}
|
||||
|
||||
-226
@@ -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—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";
|
||||
}
|
||||
}
|
||||
+280
@@ -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";
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -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)
|
||||
|
||||
@@ -14,11 +14,14 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jetty.JettySslHandshakeMetrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
|
||||
import io.micrometer.core.instrument.binder.netty4.NettyAllocatorMetrics;
|
||||
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
|
||||
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
import io.netty.buffer.ByteBufAllocator;
|
||||
import io.netty.buffer.ByteBufAllocatorMetricProvider;
|
||||
import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter;
|
||||
import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender;
|
||||
import io.opentelemetry.sdk.OpenTelemetrySdk;
|
||||
@@ -171,6 +174,10 @@ public class MetricsUtil {
|
||||
new JvmMemoryMetrics().bindTo(Metrics.globalRegistry);
|
||||
new JvmThreadMetrics().bindTo(Metrics.globalRegistry);
|
||||
|
||||
if (ByteBufAllocator.DEFAULT instanceof ByteBufAllocatorMetricProvider alloc) {
|
||||
new NettyAllocatorMetrics(alloc).bindTo(Metrics.globalRegistry);
|
||||
}
|
||||
|
||||
GarbageCollectionGauges.registerMetrics();
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -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) {
|
||||
|
||||
@@ -21,8 +21,10 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -31,6 +33,8 @@ import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
public class APNSender implements Managed, PushNotificationSender {
|
||||
|
||||
private final ExecutorService executor;
|
||||
private final Clock clock;
|
||||
|
||||
private final String bundleId;
|
||||
private final ApnsClient apnsClient;
|
||||
|
||||
@@ -45,17 +49,19 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
.setContentAvailable(true)
|
||||
.build();
|
||||
|
||||
// See https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns
|
||||
@VisibleForTesting
|
||||
static final Instant MAX_EXPIRATION = Instant.ofEpochMilli(Integer.MAX_VALUE * 1000L);
|
||||
static final Duration DEFAULT_TTL = Duration.ofDays(30);
|
||||
|
||||
private static final String APNS_CA_FILENAME = "apns-certificates.pem";
|
||||
|
||||
private static final Timer SEND_NOTIFICATION_TIMER = Metrics.timer(name(APNSender.class, "sendNotification"));
|
||||
|
||||
public APNSender(ExecutorService executor, ApnConfiguration configuration)
|
||||
public APNSender(final ExecutorService executor, final Clock clock, final ApnConfiguration configuration)
|
||||
throws IOException, NoSuchAlgorithmException, InvalidKeyException
|
||||
{
|
||||
this.executor = executor;
|
||||
this.clock = clock;
|
||||
this.bundleId = configuration.bundleId();
|
||||
this.apnsClient = new ApnsClientBuilder().setSigningKey(
|
||||
ApnsSigningKey.loadFromInputStream(new ByteArrayInputStream(configuration.signingKey().value().getBytes()),
|
||||
@@ -66,8 +72,9 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public APNSender(ExecutorService executor, ApnsClient apnsClient, String bundleId) {
|
||||
public APNSender(final ExecutorService executor, final ApnsClient apnsClient, final String bundleId, final Clock clock) {
|
||||
this.executor = executor;
|
||||
this.clock = clock;
|
||||
this.apnsClient = apnsClient;
|
||||
this.bundleId = bundleId;
|
||||
}
|
||||
@@ -92,11 +99,23 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
.setContentAvailable(true)
|
||||
.addCustomProperty("rateLimitChallenge", notification.data())
|
||||
.build();
|
||||
|
||||
case VERIFICATION_CODE_REQUESTED -> {
|
||||
if (!(notification.data() instanceof VerificationCodeRequestData(long timestamp))) {
|
||||
throw new IllegalArgumentException("Notification did not have VerificationCodeRequestData");
|
||||
}
|
||||
|
||||
yield new SimpleApnsPayloadBuilder()
|
||||
.setMutableContent(true)
|
||||
.setLocalizedAlertMessage("APN_Message")
|
||||
.addCustomProperty("verificationCodeRequested", Map.of("timestamp", timestamp))
|
||||
.build();
|
||||
}
|
||||
};
|
||||
|
||||
final PushType pushType = switch (notification.notificationType()) {
|
||||
case NOTIFICATION -> notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
|
||||
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> PushType.ALERT;
|
||||
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, VERIFICATION_CODE_REQUESTED -> PushType.ALERT;
|
||||
case CHALLENGE, RATE_LIMIT_CHALLENGE -> PushType.BACKGROUND;
|
||||
};
|
||||
|
||||
@@ -117,7 +136,7 @@ public class APNSender implements Managed, PushNotificationSender {
|
||||
return apnsClient.sendNotification(new SimpleApnsPushNotification(notification.deviceToken(),
|
||||
bundleId,
|
||||
payload,
|
||||
MAX_EXPIRATION,
|
||||
clock.instant().plus(notification.ttl() != null ? notification.ttl() : DEFAULT_TTL),
|
||||
deliveryPriority,
|
||||
pushType,
|
||||
collapseId))
|
||||
|
||||
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.auth.oauth2.GoogleCredentials;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.util.concurrent.ThreadFactoryBuilder;
|
||||
@@ -22,7 +23,9 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -31,12 +34,16 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
public class FcmSender implements PushNotificationSender {
|
||||
|
||||
private final ExecutorService executor;
|
||||
private final FirebaseMessaging firebaseMessagingClient;
|
||||
|
||||
// See https://firebase.google.com/docs/cloud-messaging/customize-messages/setting-message-lifespan
|
||||
private static final long DEFAULT_TTL_MILLIS = Duration.ofDays(28).toMillis();
|
||||
|
||||
private static final Timer SEND_NOTIFICATION_TIMER = Metrics.timer(name(FcmSender.class, "sendNotification"));
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FcmSender.class);
|
||||
@@ -82,6 +89,7 @@ public class FcmSender implements PushNotificationSender {
|
||||
.setToken(pushNotification.deviceToken())
|
||||
.setAndroidConfig(AndroidConfig.builder()
|
||||
.setPriority(pushNotification.urgent() ? AndroidConfig.Priority.HIGH : AndroidConfig.Priority.NORMAL)
|
||||
.setTtl(pushNotification.ttl() != null ? pushNotification.ttl().toMillis() : DEFAULT_TTL_MILLIS)
|
||||
.build());
|
||||
|
||||
final String key = switch (pushNotification.notificationType()) {
|
||||
@@ -89,9 +97,25 @@ public class FcmSender implements PushNotificationSender {
|
||||
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> "attemptLoginContext";
|
||||
case CHALLENGE -> "challenge";
|
||||
case RATE_LIMIT_CHALLENGE -> "rateLimitChallenge";
|
||||
case VERIFICATION_CODE_REQUESTED -> "verificationCodeRequested";
|
||||
};
|
||||
|
||||
builder.putData(key, pushNotification.data() != null ? pushNotification.data() : "");
|
||||
final String data = switch (pushNotification.notificationType()) {
|
||||
case VERIFICATION_CODE_REQUESTED -> {
|
||||
if (!(pushNotification.data() instanceof VerificationCodeRequestData)) {
|
||||
throw new IllegalArgumentException("Notification did not have VerificationCodeRequestData");
|
||||
}
|
||||
|
||||
try {
|
||||
yield SystemMapper.jsonMapper().writeValueAsString(pushNotification.data());
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
default -> pushNotification.data() != null ? pushNotification.data().toString() : "";
|
||||
};
|
||||
|
||||
builder.putData(key, data);
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
|
||||
@@ -63,7 +63,6 @@ public class MessageSender {
|
||||
|
||||
// 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");
|
||||
|
||||
@@ -77,9 +76,7 @@ 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;
|
||||
@@ -375,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)),
|
||||
|
||||
@@ -5,27 +5,42 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import java.time.Duration;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public record PushNotification(String deviceToken,
|
||||
TokenType tokenType,
|
||||
NotificationType notificationType,
|
||||
@Nullable String data,
|
||||
@Nullable Object data,
|
||||
@Nullable Account destination,
|
||||
@Nullable Device destinationDevice,
|
||||
boolean urgent) {
|
||||
boolean urgent,
|
||||
@Nullable Duration ttl) {
|
||||
|
||||
// APNs allows up to 30 days, but FCM allows a max of 28. See:
|
||||
//
|
||||
// - https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns
|
||||
// - https://firebase.google.com/docs/cloud-messaging/customize-messages/setting-message-lifespan
|
||||
private static final Duration MAX_TTL = Duration.ofDays(28);
|
||||
|
||||
public enum NotificationType {
|
||||
NOTIFICATION,
|
||||
ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
|
||||
CHALLENGE,
|
||||
RATE_LIMIT_CHALLENGE
|
||||
RATE_LIMIT_CHALLENGE,
|
||||
VERIFICATION_CODE_REQUESTED
|
||||
}
|
||||
|
||||
public enum TokenType {
|
||||
FCM,
|
||||
APN
|
||||
}
|
||||
|
||||
public PushNotification {
|
||||
if (ttl != null && ttl.compareTo(MAX_TTL) > 0) {
|
||||
throw new IllegalArgumentException("TTL must not be longer than " + MAX_TTL);
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
-4
@@ -10,7 +10,10 @@ 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.Tags;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
@@ -30,6 +33,8 @@ public class PushNotificationManager {
|
||||
private final FcmSender fcmSender;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
|
||||
private static final Duration VERIFICATION_CODE_TTL = Duration.ofMinutes(10);
|
||||
|
||||
private static final String SENT_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "sentPushNotification");
|
||||
private static final String FAILED_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "failedPushNotification");
|
||||
private static final String DEVICE_TOKEN_UNREGISTERED_COUNTER_NAME = name(PushNotificationManager.class, "deviceTokenUnregistered");
|
||||
@@ -52,11 +57,12 @@ public class PushNotificationManager {
|
||||
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
|
||||
|
||||
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent));
|
||||
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent, null));
|
||||
}
|
||||
|
||||
public CompletableFuture<SendPushNotificationResult> sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
|
||||
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true))
|
||||
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true,
|
||||
null))
|
||||
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
|
||||
}
|
||||
|
||||
@@ -67,7 +73,7 @@ public class PushNotificationManager {
|
||||
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
|
||||
|
||||
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true))
|
||||
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true, null))
|
||||
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
|
||||
}
|
||||
|
||||
@@ -77,10 +83,32 @@ public class PushNotificationManager {
|
||||
|
||||
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
|
||||
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
|
||||
context, destination, device, true))
|
||||
context, destination, device, true, null))
|
||||
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> trySendVerificationCodeRequestedNotifications(final Account destination, final Instant requestTimestamp) {
|
||||
final List<CompletableFuture<?>> sendNotificationFutures = new ArrayList<>();
|
||||
|
||||
for (final Device device : destination.getDevices()) {
|
||||
try {
|
||||
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
|
||||
|
||||
sendNotificationFutures.add(sendNotification(new PushNotification(tokenAndType.first(),
|
||||
tokenAndType.second(),
|
||||
PushNotification.NotificationType.VERIFICATION_CODE_REQUESTED,
|
||||
new VerificationCodeRequestData(requestTimestamp.toEpochMilli()),
|
||||
destination,
|
||||
device,
|
||||
true,
|
||||
VERIFICATION_CODE_TTL)));
|
||||
} catch (final NotPushRegisteredException _) {
|
||||
}
|
||||
}
|
||||
|
||||
return CompletableFuture.allOf(sendNotificationFutures.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
public void handleMessagesRetrieved(final Account account, final Device device, final String userAgent) {
|
||||
pushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
|
||||
}
|
||||
|
||||
+2
-2
@@ -311,7 +311,7 @@ public class PushNotificationScheduler implements Managed {
|
||||
return pushSchedulingCluster.withCluster(connection -> connection.async().set(
|
||||
getLastBackgroundNotificationTimestampKey(account, device),
|
||||
String.valueOf(clock.millis()), new SetArgs().ex(BACKGROUND_NOTIFICATION_PERIOD)))
|
||||
.thenCompose(ignored -> sender.sendNotification(new PushNotification(pushToken, tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, false)))
|
||||
.thenCompose(ignored -> sender.sendNotification(new PushNotification(pushToken, tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, false, null)))
|
||||
.thenAccept(response -> Metrics.counter(BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME,
|
||||
ACCEPTED_TAG, String.valueOf(response.accepted()))
|
||||
.increment())
|
||||
@@ -333,7 +333,7 @@ public class PushNotificationScheduler implements Managed {
|
||||
null,
|
||||
account,
|
||||
device,
|
||||
true);
|
||||
true, null);
|
||||
|
||||
final PushNotificationSender pushNotificationSender = isApnsDevice ? apnSender : fcmSender;
|
||||
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
record VerificationCodeRequestData(long timestamp) {
|
||||
}
|
||||
+2
-11
@@ -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)
|
||||
|
||||
+6
-17
@@ -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,8 @@ public class Account {
|
||||
private IdentityKey phoneNumberIdentityKey;
|
||||
|
||||
@JsonProperty("cpv")
|
||||
private String currentProfileVersion;
|
||||
@JsonDeserialize(using = ProfileVersionAdapter.Deserializing.class)
|
||||
private byte[] currentProfileVersion;
|
||||
|
||||
@JsonProperty
|
||||
private List<AccountBadge> badges = new ArrayList<>();
|
||||
@@ -323,13 +337,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 +578,21 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-12
@@ -37,7 +37,6 @@ import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -129,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;
|
||||
@@ -210,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,
|
||||
@@ -227,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;
|
||||
@@ -412,10 +413,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
final boolean rrpCreated = accountAttributes.recoveryPassword().map(registrationRecoveryPassword ->
|
||||
registrationRecoveryPasswordsManager
|
||||
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
|
||||
.join())
|
||||
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword))
|
||||
.orElse(false);
|
||||
|
||||
changeNumberWaitingPeriodManager.handleAccountCreated(account.getUuid(), clock.instant());
|
||||
|
||||
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("type", accountCreationType),
|
||||
@@ -964,7 +965,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
///
|
||||
/// @throws WriteConflictException if the expected current version does not match the current version
|
||||
public Account updateCurrentProfileVersion(final UUID accountIdentifier, final byte[] newVersion,
|
||||
final String expectedCurrentVersion, final Consumer<Account> updater) throws WriteConflictException {
|
||||
final byte[] expectedCurrentVersion, final Consumer<Account> updater) throws WriteConflictException {
|
||||
|
||||
Objects.requireNonNull(expectedCurrentVersion, "expectedCurrentVersion");
|
||||
|
||||
@@ -972,22 +973,20 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
final String newVersionHex = HexFormat.of().formatHex(newVersion);
|
||||
|
||||
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
|
||||
final Account maybeUpdatedAccount = update(accountIdentifier, a -> {
|
||||
if (!a.getCurrentProfileVersion().orElse("").equals(expectedCurrentVersion)) {
|
||||
if (!a.getCurrentProfileVersion().orElse(new byte[0]).equals(expectedCurrentVersion)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
a.setCurrentProfileVersion(newVersionHex);
|
||||
a.setCurrentProfileVersion(newVersion);
|
||||
|
||||
updater.accept(a);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> v.equals(newVersionHex)).orElse(false)) {
|
||||
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> v.equals(newVersion)).orElse(false)) {
|
||||
throw new WriteConflictException();
|
||||
}
|
||||
|
||||
@@ -1214,10 +1213,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
keysManager.deleteSingleUsePreKeys(account.getUuid()),
|
||||
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
|
||||
messagesManager.clear(account.getUuid()),
|
||||
profilesManager.deleteAll(account.getUuid(), true),
|
||||
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
|
||||
profilesManager.deleteAll(account.getUuid(), true))
|
||||
.join();
|
||||
|
||||
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI));
|
||||
|
||||
accounts.delete(account.getUuid(), additionalWriteItems);
|
||||
redisDelete(account);
|
||||
|
||||
|
||||
+6
-8
@@ -13,7 +13,6 @@ import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -48,7 +47,7 @@ public class ChangeNumberManager {
|
||||
private final AccountsManager accountsManager;
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final Duration postRegistrationWaitingPeriod;
|
||||
private final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final Clock clock;
|
||||
|
||||
@@ -66,7 +65,7 @@ public class ChangeNumberManager {
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final Duration postRegistrationWaitingPeriod,
|
||||
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager,
|
||||
final Clock clock) {
|
||||
|
||||
this.messageSender = messageSender;
|
||||
@@ -74,7 +73,7 @@ public class ChangeNumberManager {
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.postRegistrationWaitingPeriod = postRegistrationWaitingPeriod;
|
||||
this.changeNumberWaitingPeriodManager = changeNumberWaitingPeriodManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -101,11 +100,10 @@ public class ChangeNumberManager {
|
||||
// Only verify and check reglock if there's a data change to be made...
|
||||
if (!account.getNumber().equals(number)) {
|
||||
|
||||
final Instant registration = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
|
||||
final Duration waitingPeriodRemaining = Duration.between(clock.instant().minus(postRegistrationWaitingPeriod), registration);
|
||||
if (waitingPeriodRemaining.isPositive()) {
|
||||
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);
|
||||
throw new RateLimitExceededException(waitingPeriodRemaining.get());
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
+43
@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
+69
@@ -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());
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -11,15 +11,15 @@ import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
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.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class RedeemedReceiptsManager {
|
||||
|
||||
@@ -32,13 +32,13 @@ public class RedeemedReceiptsManager {
|
||||
|
||||
private final Clock clock;
|
||||
private final String table;
|
||||
private final DynamoDbAsyncClient client;
|
||||
private final DynamoDbClient client;
|
||||
private final Duration expirationTime;
|
||||
|
||||
public RedeemedReceiptsManager(
|
||||
@Nonnull final Clock clock,
|
||||
@Nonnull final String table,
|
||||
@Nonnull final DynamoDbAsyncClient client,
|
||||
@Nonnull final DynamoDbClient client,
|
||||
@Nonnull final Duration expirationTime) {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.table = Objects.requireNonNull(table);
|
||||
@@ -51,7 +51,7 @@ public class RedeemedReceiptsManager {
|
||||
* receiptLevel}, and {@code accountUuid} provided or if an existing entry already exists with the same values thereby
|
||||
* allowing idempotent request processing.
|
||||
*/
|
||||
public CompletableFuture<Boolean> put(
|
||||
public boolean put(
|
||||
@Nonnull final ReceiptSerial receiptSerial,
|
||||
final long receiptExpiration,
|
||||
final long receiptLevel,
|
||||
@@ -87,13 +87,13 @@ public class RedeemedReceiptsManager {
|
||||
":account_uuid", AttributeValues.b(accountUuid),
|
||||
":redemption_time", AttributeValues.n(now.getEpochSecond())))
|
||||
.build();
|
||||
return client.updateItem(updateItemRequest).thenApply(updateItemResponse -> {
|
||||
final UpdateItemResponse updateItemResponse = client.updateItem(updateItemRequest);
|
||||
|
||||
final Map<String, AttributeValue> attributes = updateItemResponse.attributes();
|
||||
final long ddbReceiptExpiration = Long.parseLong(attributes.get(KEY_RECEIPT_EXPIRATION).n());
|
||||
final long ddbReceiptLevel = Long.parseLong(attributes.get(KEY_RECEIPT_LEVEL).n());
|
||||
final UUID ddbAccountUuid = UUIDUtil.fromByteBuffer(attributes.get(KEY_ACCOUNT_UUID).b().asByteBuffer());
|
||||
return ddbReceiptExpiration == receiptExpiration && ddbReceiptLevel == receiptLevel &&
|
||||
Objects.equals(ddbAccountUuid, accountUuid);
|
||||
});
|
||||
}
|
||||
}
|
||||
+38
-34
@@ -13,15 +13,16 @@ import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
|
||||
public class RegistrationRecoveryPasswords {
|
||||
@@ -36,31 +37,32 @@ public class RegistrationRecoveryPasswords {
|
||||
|
||||
private final Duration expiration;
|
||||
|
||||
private final DynamoDbAsyncClient asyncClient;
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
public RegistrationRecoveryPasswords(
|
||||
final String tableName,
|
||||
final Duration expiration,
|
||||
final DynamoDbAsyncClient asyncClient,
|
||||
final DynamoDbClient dynamoDbClient,
|
||||
final Clock clock) {
|
||||
this.tableName = requireNonNull(tableName);
|
||||
this.expiration = requireNonNull(expiration);
|
||||
this.asyncClient = requireNonNull(asyncClient);
|
||||
this.dynamoDbClient = requireNonNull(dynamoDbClient);
|
||||
this.clock = requireNonNull(clock);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final UUID phoneNumberIdentifier) {
|
||||
return asyncClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.thenApply(getItemResponse -> Optional.ofNullable(getItemResponse.item())
|
||||
.filter(item -> item.containsKey(ATTR_SALT))
|
||||
.filter(item -> item.containsKey(ATTR_HASH))
|
||||
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem));
|
||||
public Optional<SaltedTokenHash> lookup(final UUID phoneNumberIdentifier) {
|
||||
final GetItemResponse getItemResponse = dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.consistentRead(true)
|
||||
.build());
|
||||
|
||||
return Optional.ofNullable(getItemResponse.item())
|
||||
.filter(item -> item.containsKey(ATTR_SALT))
|
||||
.filter(item -> item.containsKey(ATTR_HASH))
|
||||
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem);
|
||||
}
|
||||
|
||||
/// Add a PNI -> RRP mapping, or replace the current one if it already exists
|
||||
@@ -68,31 +70,33 @@ public class RegistrationRecoveryPasswords {
|
||||
/// @param phoneNumberIdentifier The PNI to associate the salted RRP with
|
||||
/// @param data The salted registration recovery password
|
||||
/// @return true if a new mapping was added, false if an existing mapping was updated
|
||||
public CompletableFuture<Boolean> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
|
||||
public boolean addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
|
||||
final long expirationSeconds = expirationSeconds();
|
||||
|
||||
return asyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.item(Map.of(
|
||||
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
|
||||
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
|
||||
ATTR_SALT, AttributeValues.fromString(data.salt()),
|
||||
ATTR_HASH, AttributeValues.fromString(data.hash())))
|
||||
.build())
|
||||
.thenApply(response -> response.attributes() == null || response.attributes().isEmpty());
|
||||
final PutItemResponse response = dynamoDbClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.item(Map.of(
|
||||
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
|
||||
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
|
||||
ATTR_SALT, AttributeValues.fromString(data.salt()),
|
||||
ATTR_HASH, AttributeValues.fromString(data.hash())))
|
||||
.build());
|
||||
|
||||
return response.attributes() == null || response.attributes().isEmpty();
|
||||
}
|
||||
|
||||
/// Remove the entry associated with the provided PNI
|
||||
///
|
||||
/// @return true if an entry was removed, false if no entry existed
|
||||
public CompletableFuture<Boolean> removeEntry(final UUID phoneNumberIdentifier) {
|
||||
return asyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.build())
|
||||
.thenApply(response -> response.attributes() != null && !response.attributes().isEmpty());
|
||||
public boolean removeEntry(final UUID phoneNumberIdentifier) {
|
||||
final DeleteItemResponse response = dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
|
||||
.build());
|
||||
|
||||
return response.attributes() != null && !response.attributes().isEmpty();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+6
-30
@@ -7,56 +7,32 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
|
||||
|
||||
public class RegistrationRecoveryPasswordsManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
|
||||
|
||||
private final RegistrationRecoveryPasswords registrationRecoveryPasswords;
|
||||
|
||||
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords) {
|
||||
this.registrationRecoveryPasswords = requireNonNull(registrationRecoveryPasswords);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> verify(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
public boolean verify(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
return registrationRecoveryPasswords.lookup(phoneNumberIdentifier)
|
||||
.thenApply(maybeHash -> maybeHash.filter(hash -> hash.verify(bytesToString(password))))
|
||||
.whenComplete((_, error) -> {
|
||||
if (error != null) {
|
||||
logger.warn("Failed to lookup Registration Recovery Password", error);
|
||||
}
|
||||
})
|
||||
.thenApply(Optional::isPresent);
|
||||
.filter(hash -> hash.verify(bytesToString(password))).isPresent();
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> store(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
public boolean store(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
final String token = bytesToString(password);
|
||||
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
|
||||
|
||||
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash)
|
||||
.whenComplete((_, error) -> {
|
||||
if (error != null) {
|
||||
logger.warn("Failed to store Registration Recovery Password", error);
|
||||
}
|
||||
});
|
||||
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> remove(final UUID phoneNumberIdentifier) {
|
||||
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier)
|
||||
.whenComplete((_, error) -> {
|
||||
if (error != null) {
|
||||
logger.warn("Failed to remove Registration Recovery Password", error);
|
||||
}
|
||||
});
|
||||
public boolean remove(final UUID phoneNumberIdentifier) {
|
||||
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier);
|
||||
}
|
||||
|
||||
private static String bytesToString(final byte[] bytes) {
|
||||
|
||||
+28
-35
@@ -14,16 +14,16 @@ import java.time.Clock;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
|
||||
public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
@@ -34,7 +34,7 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
long getExpirationEpochSeconds();
|
||||
}
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbClient;
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final String tableName;
|
||||
private final Clock clock;
|
||||
private final Class<T> deserializationTargetClass;
|
||||
@@ -47,7 +47,7 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(getClass());
|
||||
|
||||
public SerializedExpireableJsonDynamoStore(final DynamoDbAsyncClient dynamoDbClient, final String tableName,
|
||||
public SerializedExpireableJsonDynamoStore(final DynamoDbClient dynamoDbClient, final String tableName,
|
||||
final Clock clock) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.tableName = tableName;
|
||||
@@ -67,18 +67,16 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> insert(final String key, final T v) {
|
||||
return put(key, v, builder -> builder.expressionAttributeNames(Map.of(
|
||||
"#key", KEY_KEY
|
||||
)).conditionExpression("attribute_not_exists(#key)"));
|
||||
public void insert(final String key, final T v) {
|
||||
put(key, v, builder -> builder.expressionAttributeNames(Map.of("#key", KEY_KEY))
|
||||
.conditionExpression("attribute_not_exists(#key)"));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> update(final String key, final T v) {
|
||||
return put(key, v, ignored -> {
|
||||
});
|
||||
public void update(final String key, final T v) {
|
||||
put(key, v, _ -> {});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> put(final String key, final T v,
|
||||
private void put(final String key, final T v,
|
||||
final Consumer<PutItemRequest.Builder> putRequestCustomizer) {
|
||||
try {
|
||||
final Map<String, AttributeValue> attributeValueMap = new HashMap<>(Map.of(
|
||||
@@ -93,9 +91,7 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
.item(attributeValueMap);
|
||||
putRequestCustomizer.accept(builder);
|
||||
|
||||
return dynamoDbClient.putItem(builder.build())
|
||||
.thenRun(() -> {
|
||||
});
|
||||
dynamoDbClient.putItem(builder.build());
|
||||
} catch (final JsonProcessingException e) {
|
||||
// This should never happen when writing directly to a string except in cases of serious misconfiguration, which
|
||||
// would be caught by tests.
|
||||
@@ -107,24 +103,23 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
return v.getExpirationEpochSeconds();
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<T>> findForKey(final String key) {
|
||||
return dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
public Optional<T> findForKey(final String key) {
|
||||
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.key(Map.of(KEY_KEY, AttributeValues.fromString(key)))
|
||||
.build())
|
||||
.thenApply(response -> {
|
||||
try {
|
||||
return response.hasItem()
|
||||
? filterMaybeExpiredValue(
|
||||
SystemMapper.jsonMapper()
|
||||
.readValue(response.item().get(ATTR_SERIALIZED_VALUE).s(), deserializationTargetClass))
|
||||
: Optional.empty();
|
||||
} catch (final JsonProcessingException e) {
|
||||
log.error("Failed to parse stored value", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
.build());
|
||||
|
||||
try {
|
||||
return response.hasItem()
|
||||
? filterMaybeExpiredValue(
|
||||
SystemMapper.jsonMapper()
|
||||
.readValue(response.item().get(ATTR_SERIALIZED_VALUE).s(), deserializationTargetClass))
|
||||
: Optional.empty();
|
||||
} catch (final JsonProcessingException e) {
|
||||
log.error("Failed to parse stored value", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<T> filterMaybeExpiredValue(T v) {
|
||||
@@ -139,13 +134,11 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
|
||||
return Optional.of(v);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> remove(final String key) {
|
||||
return dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
public void remove(final String key) {
|
||||
dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_KEY, AttributeValues.fromString(key)))
|
||||
.build())
|
||||
.thenRun(() -> {
|
||||
});
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
+10
-11
@@ -79,7 +79,7 @@ public class SubscriptionManager {
|
||||
public void deleteSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
|
||||
if (getResult == Subscriptions.GetResult.NOT_STORED
|
||||
|| getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
@@ -90,7 +90,7 @@ public class SubscriptionManager {
|
||||
final ProcessorCustomer processorCustomer = getResult.record.getProcessorCustomer().get();
|
||||
getProcessor(processorCustomer.processor()).cancelAllActiveSubscriptions(processorCustomer.customerId());
|
||||
}
|
||||
subscriptions.setCanceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()).join();
|
||||
subscriptions.setCanceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,7 +105,7 @@ public class SubscriptionManager {
|
||||
public void updateSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionForbiddenException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
|
||||
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
@@ -113,13 +113,13 @@ public class SubscriptionManager {
|
||||
// create a customer and write it to ddb
|
||||
final Subscriptions.Record updatedRecord = subscriptions.create(subscriberCredentials.subscriberUser(),
|
||||
subscriberCredentials.hmac(),
|
||||
subscriberCredentials.now()).join();
|
||||
subscriberCredentials.now());
|
||||
if (updatedRecord == null) {
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
}
|
||||
} else {
|
||||
// already exists so just touch access time and return
|
||||
subscriptions.accessedAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()).join();
|
||||
subscriptions.accessedAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ public class SubscriptionManager {
|
||||
public Subscriptions.Record getSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
@@ -198,8 +198,7 @@ public class SubscriptionManager {
|
||||
final SubscriptionPaymentProcessor manager = getProcessor(processor);
|
||||
final SubscriptionPaymentProcessor.ReceiptItem receipt = manager.getReceiptItem(record.subscriptionId);
|
||||
issuedReceiptsManager
|
||||
.recordIssuance(receipt.itemId(), manager.getProvider(), receiptCredentialRequest, subscriberCredentials.now())
|
||||
.join();
|
||||
.recordIssuance(receipt.itemId(), manager.getProvider(), receiptCredentialRequest, subscriberCredentials.now());
|
||||
ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
@@ -250,7 +249,7 @@ public class SubscriptionManager {
|
||||
.createCustomer(subscriberCredentials.subscriberUser(), clientPlatform);
|
||||
record = subscriptions.setProcessorAndCustomerId(record,
|
||||
new ProcessorCustomer(pc.customerId(), subscriptionPaymentProcessor.getProvider()),
|
||||
Instant.now()).join();
|
||||
Instant.now());
|
||||
}
|
||||
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("processor must now exist")));
|
||||
@@ -330,7 +329,7 @@ public class SubscriptionManager {
|
||||
subscriptions.subscriptionLevelChanged(subscriberCredentials.subscriberUser(),
|
||||
subscriberCredentials.now(),
|
||||
level,
|
||||
updatedSubscriptionId.id()).join();
|
||||
updatedSubscriptionId.id());
|
||||
} else {
|
||||
// Otherwise, we don't have a subscription yet so create it and then record the subscription id
|
||||
long lastSubscriptionCreatedAt = record.subscriptionCreatedAt != null
|
||||
@@ -437,7 +436,7 @@ public class SubscriptionManager {
|
||||
final ProcessorCustomer pc = new ProcessorCustomer(originalTransactionId, PaymentProvider.APPLE_APP_STORE);
|
||||
|
||||
final Long level = appleAppStoreManager.validateTransaction(originalTransactionId);
|
||||
subscriptions.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now()).join();
|
||||
subscriptions.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now());
|
||||
return level;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Throwables;
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -19,8 +18,6 @@ import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
@@ -28,15 +25,16 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
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.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class Subscriptions {
|
||||
|
||||
@@ -161,11 +159,11 @@ public class Subscriptions {
|
||||
}
|
||||
|
||||
private final String table;
|
||||
private final DynamoDbAsyncClient client;
|
||||
private final DynamoDbClient client;
|
||||
|
||||
public Subscriptions(
|
||||
@Nonnull String table,
|
||||
@Nonnull DynamoDbAsyncClient client) {
|
||||
@Nonnull DynamoDbClient client) {
|
||||
this.table = Objects.requireNonNull(table);
|
||||
this.client = Objects.requireNonNull(client);
|
||||
}
|
||||
@@ -173,7 +171,7 @@ public class Subscriptions {
|
||||
/**
|
||||
* Looks in the GSI for a record with the given customer id and returns the user id.
|
||||
*/
|
||||
public CompletableFuture<byte[]> getSubscriberUserByProcessorCustomer(ProcessorCustomer processorCustomer) {
|
||||
public byte[] getSubscriberUserByProcessorCustomer(ProcessorCustomer processorCustomer) {
|
||||
QueryRequest query = QueryRequest.builder()
|
||||
.tableName(table)
|
||||
.indexName(INDEX_NAME)
|
||||
@@ -185,20 +183,20 @@ public class Subscriptions {
|
||||
.expressionAttributeValues(Map.of(
|
||||
":processor_customer_id", b(processorCustomer.toDynamoBytes())))
|
||||
.build();
|
||||
return client.query(query).thenApply(queryResponse -> {
|
||||
int count = queryResponse.count();
|
||||
if (count == 0) {
|
||||
return null;
|
||||
} else if (count > 1) {
|
||||
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {} ({})",
|
||||
processorCustomer.customerId(), processorCustomer.processor());
|
||||
throw new IllegalStateException(
|
||||
"expected invariant of 1-1 subscriber-customer violated for customer " + processorCustomer);
|
||||
} else {
|
||||
Map<String, AttributeValue> result = queryResponse.items().getFirst();
|
||||
return result.get(KEY_USER).b().asByteArray();
|
||||
}
|
||||
});
|
||||
final QueryResponse queryResponse = client.query(query);
|
||||
|
||||
int count = queryResponse.count();
|
||||
if (count == 0) {
|
||||
return null;
|
||||
} else if (count > 1) {
|
||||
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {} ({})",
|
||||
processorCustomer.customerId(), processorCustomer.processor());
|
||||
throw new IllegalStateException(
|
||||
"expected invariant of 1-1 subscriber-customer violated for customer " + processorCustomer);
|
||||
} else {
|
||||
Map<String, AttributeValue> result = queryResponse.items().getFirst();
|
||||
return result.get(KEY_USER).b().asByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static class GetResult {
|
||||
@@ -228,21 +226,22 @@ public class Subscriptions {
|
||||
/**
|
||||
* Looks up a record with the given {@code user} and validates the {@code hmac} before returning it.
|
||||
*/
|
||||
public CompletableFuture<GetResult> get(byte[] user, byte[] hmac) {
|
||||
return getUser(user).thenApply(getItemResponse -> {
|
||||
if (!getItemResponse.hasItem()) {
|
||||
return GetResult.NOT_STORED;
|
||||
}
|
||||
public GetResult get(byte[] user, byte[] hmac) {
|
||||
final GetItemResponse getItemResponse = getUser(user);
|
||||
|
||||
Record record = Record.from(user, getItemResponse.item());
|
||||
if (!MessageDigest.isEqual(hmac, record.password)) {
|
||||
return GetResult.PASSWORD_MISMATCH;
|
||||
}
|
||||
return GetResult.found(record);
|
||||
});
|
||||
if (!getItemResponse.hasItem()) {
|
||||
|
||||
return GetResult.NOT_STORED;
|
||||
}
|
||||
|
||||
Record record = Record.from(user, getItemResponse.item());
|
||||
if (!MessageDigest.isEqual(hmac, record.password)) {
|
||||
return GetResult.PASSWORD_MISMATCH;
|
||||
}
|
||||
return GetResult.found(record);
|
||||
}
|
||||
|
||||
private CompletableFuture<GetItemResponse> getUser(byte[] user) {
|
||||
private GetItemResponse getUser(byte[] user) {
|
||||
checkUserLength(user);
|
||||
|
||||
GetItemRequest request = GetItemRequest.builder()
|
||||
@@ -254,10 +253,11 @@ public class Subscriptions {
|
||||
return client.getItem(request);
|
||||
}
|
||||
|
||||
public CompletableFuture<Record> create(byte[] user, byte[] password, Instant createdAt) {
|
||||
@Nullable
|
||||
public Record create(byte[] user, byte[] password, Instant createdAt) {
|
||||
checkUserLength(user);
|
||||
|
||||
UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
final UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_USER, b(user)))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
@@ -279,17 +279,13 @@ public class Subscriptions {
|
||||
":accessed_at", n(createdAt.getEpochSecond()))
|
||||
)
|
||||
.build();
|
||||
return client.updateItem(request).handle((updateItemResponse, throwable) -> {
|
||||
if (throwable != null) {
|
||||
if (Throwables.getRootCause(throwable) instanceof ConditionalCheckFailedException) {
|
||||
return null;
|
||||
}
|
||||
Throwables.throwIfUnchecked(throwable);
|
||||
throw new CompletionException(throwable);
|
||||
}
|
||||
try {
|
||||
final UpdateItemResponse updateItemResponse = client.updateItem(request);
|
||||
|
||||
return Record.from(user, updateItemResponse.attributes());
|
||||
});
|
||||
} catch (ConditionalCheckFailedException _) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -297,10 +293,10 @@ public class Subscriptions {
|
||||
*
|
||||
* @return the user record.
|
||||
*/
|
||||
public CompletableFuture<Record> setProcessorAndCustomerId(Record userRecord,
|
||||
public Record setProcessorAndCustomerId(Record userRecord,
|
||||
ProcessorCustomer activeProcessorCustomer, Instant updatedAt) {
|
||||
|
||||
UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
final UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_USER, b(userRecord.user)))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
@@ -318,15 +314,13 @@ public class Subscriptions {
|
||||
":processor_customer_id", b(activeProcessorCustomer.toDynamoBytes())
|
||||
)).build();
|
||||
|
||||
return client.updateItem(request)
|
||||
.thenApply(updateItemResponse -> Record.from(userRecord.user, updateItemResponse.attributes()))
|
||||
.exceptionallyCompose(throwable -> {
|
||||
if (Throwables.getRootCause(throwable) instanceof ConditionalCheckFailedException) {
|
||||
throw new ClientErrorException(Response.Status.CONFLICT);
|
||||
}
|
||||
Throwables.throwIfUnchecked(throwable);
|
||||
throw new CompletionException(throwable);
|
||||
});
|
||||
try {
|
||||
final UpdateItemResponse updateItemResponse = client.updateItem(request);
|
||||
|
||||
return Record.from(userRecord.user, updateItemResponse.attributes());
|
||||
} catch (ConditionalCheckFailedException _) {
|
||||
throw new ClientErrorException(Response.Status.CONFLICT);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -345,7 +339,7 @@ public class Subscriptions {
|
||||
* @param updatedAt The time of this update
|
||||
* @return A stage that completes once the record has been updated
|
||||
*/
|
||||
public CompletableFuture<Void> setIapPurchase(
|
||||
public void setIapPurchase(
|
||||
final Record record,
|
||||
final ProcessorCustomer processorCustomer,
|
||||
final String subscriptionId,
|
||||
@@ -390,21 +384,17 @@ public class Subscriptions {
|
||||
":subscription_level_changed_at", n(updatedAt.getEpochSecond())))
|
||||
.build();
|
||||
|
||||
return client.updateItem(request)
|
||||
.exceptionallyCompose(throwable -> {
|
||||
if (Throwables.getRootCause(throwable) instanceof ConditionalCheckFailedException) {
|
||||
throw new ClientErrorException(Response.Status.CONFLICT);
|
||||
}
|
||||
Throwables.throwIfUnchecked(throwable);
|
||||
throw new CompletionException(throwable);
|
||||
})
|
||||
.thenRun(Util.NOOP);
|
||||
try {
|
||||
client.updateItem(request);
|
||||
} catch (ConditionalCheckFailedException _) {
|
||||
throw new ClientErrorException(Response.Status.CONFLICT);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> accessedAt(byte[] user, Instant accessedAt) {
|
||||
public void accessedAt(byte[] user, Instant accessedAt) {
|
||||
checkUserLength(user);
|
||||
|
||||
UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
final UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_USER, b(user)))
|
||||
.returnValues(ReturnValue.NONE)
|
||||
@@ -412,13 +402,13 @@ public class Subscriptions {
|
||||
.expressionAttributeNames(Map.of("#accessed_at", KEY_ACCESSED_AT))
|
||||
.expressionAttributeValues(Map.of(":accessed_at", n(accessedAt.getEpochSecond())))
|
||||
.build();
|
||||
return client.updateItem(request).thenApply(updateItemResponse -> null);
|
||||
client.updateItem(request);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> setCanceledAt(byte[] user, Instant canceledAt) {
|
||||
public void setCanceledAt(byte[] user, Instant canceledAt) {
|
||||
checkUserLength(user);
|
||||
|
||||
UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
final UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_USER, b(user)))
|
||||
.returnValues(ReturnValue.NONE)
|
||||
@@ -434,14 +424,14 @@ public class Subscriptions {
|
||||
":accessed_at", n(canceledAt.getEpochSecond()),
|
||||
":canceled_at", n(canceledAt.getEpochSecond())))
|
||||
.build();
|
||||
return client.updateItem(request).thenApply(updateItemResponse -> null);
|
||||
client.updateItem(request);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> subscriptionCreated(
|
||||
public void subscriptionCreated(
|
||||
byte[] user, String subscriptionId, Instant subscriptionCreatedAt, long level) {
|
||||
checkUserLength(user);
|
||||
|
||||
UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
final UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_USER, b(user)))
|
||||
.returnValues(ReturnValue.NONE)
|
||||
@@ -466,14 +456,14 @@ public class Subscriptions {
|
||||
":subscription_level", n(level),
|
||||
":subscription_level_changed_at", n(subscriptionCreatedAt.getEpochSecond())))
|
||||
.build();
|
||||
return client.updateItem(request).thenApply(updateItemResponse -> null);
|
||||
client.updateItem(request);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> subscriptionLevelChanged(
|
||||
public void subscriptionLevelChanged(
|
||||
byte[] user, Instant subscriptionLevelChangedAt, long level, String subscriptionId) {
|
||||
checkUserLength(user);
|
||||
|
||||
UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
final UpdateItemRequest request = UpdateItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_USER, b(user)))
|
||||
.returnValues(ReturnValue.NONE)
|
||||
@@ -495,7 +485,7 @@ public class Subscriptions {
|
||||
":subscription_level", n(level),
|
||||
":subscription_level_changed_at", n(subscriptionLevelChangedAt.getEpochSecond())))
|
||||
.build();
|
||||
return client.updateItem(request).thenApply(updateItemResponse -> null);
|
||||
client.updateItem(request);
|
||||
}
|
||||
|
||||
private static byte[] checkUserLength(final byte[] user) {
|
||||
|
||||
+5
-6
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public class VerificationSessionManager {
|
||||
@@ -17,15 +16,15 @@ public class VerificationSessionManager {
|
||||
this.verificationSessions = verificationSessions;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> insert(final VerificationSession verificationSession) {
|
||||
return verificationSessions.insert(verificationSession.sessionId(), verificationSession);
|
||||
public void insert(final VerificationSession verificationSession) {
|
||||
verificationSessions.insert(verificationSession.sessionId(), verificationSession);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> update(final VerificationSession verificationSession) {
|
||||
return verificationSessions.update(verificationSession.sessionId(), verificationSession);
|
||||
public void update(final VerificationSession verificationSession) {
|
||||
verificationSessions.update(verificationSession.sessionId(), verificationSession);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<VerificationSession>> findForId(final String encodedSessionId) {
|
||||
public Optional<VerificationSession> findForId(final String encodedSessionId) {
|
||||
return verificationSessions.findForKey(encodedSessionId);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.time.Clock;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class VerificationSessions extends SerializedExpireableJsonDynamoStore<VerificationSession> {
|
||||
|
||||
public VerificationSessions(final DynamoDbAsyncClient dynamoDbClient, final String tableName, final Clock clock) {
|
||||
public VerificationSessions(final DynamoDbClient dynamoDbClient, final String tableName, final Clock clock) {
|
||||
super(dynamoDbClient, tableName, clock);
|
||||
}
|
||||
}
|
||||
+47
-47
@@ -4,29 +4,26 @@ import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
class FoundationDbMessagePublisher {
|
||||
|
||||
private final Database database;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
|
||||
@@ -76,14 +73,17 @@ class FoundationDbMessagePublisher {
|
||||
@Nullable private final byte[] messagesAvailableWatchKey;
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
private final Flux<MessageStreamEntry.Envelope> messagePublisher;
|
||||
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
|
||||
/// is started for the page fetch operations.
|
||||
private final Supplier<Consumer<Transaction>> beforePageFetch;
|
||||
|
||||
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
|
||||
private State state = State.MESSAGES_AVAILABLE;
|
||||
/// Reference to the sink we publishes messages to.
|
||||
private volatile FluxSink<MessageStreamEntry.Envelope> emitter;
|
||||
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
@@ -93,19 +93,19 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener) {
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.database = database;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.beforePageFetch = beforePageFetch;
|
||||
this.messagePublisher = Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
@@ -121,16 +121,16 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan) {
|
||||
final int maxMessagesPerScan,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
messageGuidCodec,
|
||||
maxMessagesPerScan,
|
||||
null,
|
||||
null);
|
||||
null,
|
||||
beforePageFetch);
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
|
||||
@@ -140,17 +140,17 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
messageGuidCodec,
|
||||
maxMessagesPerScan,
|
||||
messagesAvailableWatchKey,
|
||||
null);
|
||||
null,
|
||||
beforePageFetch);
|
||||
}
|
||||
|
||||
private synchronized void setState(final State newState, final Event event) {
|
||||
@@ -238,25 +238,32 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
|
||||
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
|
||||
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// a watch for new messages. Execute the function supplied by [#beforePageFetch] in the context of the transaction.
|
||||
/// Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans
|
||||
///
|
||||
/// @return a future of a list of [MessageStreamEntry] with a max size of [#maxMessagesPerScan]
|
||||
private CompletableFuture<List<MessageStreamEntry.Envelope>> getMessagesBatch() {
|
||||
return database.runAsync(transaction -> getItemsInRange(transaction, messageGuidCodec, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first().ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
|
||||
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
|
||||
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
|
||||
return database.runAsync(transaction -> {
|
||||
doBeforePageFetch.accept(transaction);
|
||||
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first()
|
||||
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
|
||||
final List<MessageStreamEntry.Envelope> items = lastKeyReadAndItems.second();
|
||||
if (items.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
if (!terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
})
|
||||
final List<FoundationDbMessageStreamEntry.Message> items = lastKeyReadAndItems.second();
|
||||
if (items.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
if (!terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
});
|
||||
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -267,9 +274,8 @@ class FoundationDbMessagePublisher {
|
||||
/// @param endExclusive the range end key (exclusive)
|
||||
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
|
||||
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
|
||||
private static CompletableFuture<Pair<Optional<byte[]>, List<MessageStreamEntry.Envelope>>> getItemsInRange(
|
||||
private CompletableFuture<Pair<Optional<byte[]>, List<FoundationDbMessageStreamEntry.Message>>> getItemsInRange(
|
||||
final Transaction transaction,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final KeySelector beginInclusive,
|
||||
final KeySelector endExclusive,
|
||||
final int maxMessagesPerScan) {
|
||||
@@ -278,16 +284,10 @@ class FoundationDbMessagePublisher {
|
||||
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
|
||||
? Optional.empty()
|
||||
: Optional.of(keyValues.getLast().getKey());
|
||||
final List<MessageStreamEntry.Envelope> messages = keyValues.stream()
|
||||
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
|
||||
.map(keyValue -> {
|
||||
try {
|
||||
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(keyValue.getValue())
|
||||
.toBuilder()
|
||||
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()))))
|
||||
.build());
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp, keyValue.getValue());
|
||||
})
|
||||
.toList();
|
||||
return new Pair<>(lastKeyRead, messages);
|
||||
@@ -317,7 +317,7 @@ class FoundationDbMessagePublisher {
|
||||
/// Get the stream of messages.
|
||||
///
|
||||
/// @return [Flux] of messages
|
||||
public Flux<MessageStreamEntry.Envelope> getMessages() {
|
||||
public Flux<FoundationDbMessageStreamEntry.Message> getMessages() {
|
||||
return this.messagePublisher;
|
||||
}
|
||||
|
||||
|
||||
+7
-3
@@ -25,6 +25,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
///
|
||||
@@ -261,16 +262,19 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
|
||||
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN);
|
||||
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice, final int maxMessagesPerScan) {
|
||||
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice,
|
||||
final int maxMessagesPerScan, final Runnable doAfterCleanup) {
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
getShardForAci(aci),
|
||||
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
|
||||
maxMessagesPerScan);
|
||||
maxMessagesPerScan,
|
||||
doAfterCleanup);
|
||||
}
|
||||
|
||||
static Versionstamp getVersionstamp(final byte[] messageKey) {
|
||||
|
||||
+152
-26
@@ -3,14 +3,30 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableMap;
|
||||
import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import com.apple.foundationdb.tuple.ByteArrayUtil;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -25,14 +41,21 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
private final Runnable doAfterCleanup;
|
||||
|
||||
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
|
||||
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
|
||||
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Database database,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan) {
|
||||
final int maxMessagesPerScan,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
@@ -40,6 +63,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
this.doAfterCleanup = doAfterCleanup;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -47,44 +71,62 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
return this.messageStreamPublisher;
|
||||
}
|
||||
|
||||
/// Create a message publisher
|
||||
///
|
||||
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
|
||||
/// @implNote The message publisher is stitched together by concatenating:
|
||||
/// 1. **A finite message publisher**: On initial request, we record the current end-of-queue key in the device mailbox.
|
||||
/// Then, we fetch all messages in order until the recorded key and finally complete the stream
|
||||
/// 2. **A queue-empty signal** is emitted
|
||||
/// 3. **An infinite message publisher**: We start reading from where the finite publisher left off. When all messages
|
||||
/// are read, we wait for new messages, publish them, then wait again in a loop forever (until the flux is canceled
|
||||
/// explicitly or due to an error). This is accomplished by setting a FoundationDB [watch](https://github.com/apple/foundationdb/wiki/An-Overview-how-Watches-Work)
|
||||
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
|
||||
/// See [FoundationDbMessageStore] for more details on the message insert process.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
|
||||
/// Create a message publisher
|
||||
///
|
||||
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
|
||||
/// @implNote turns the stream of [FoundationDbMessageStreamEntry] into [MessageStreamEntry], but taps into the stream
|
||||
/// first to keep track of versionstamps sent to the client.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
return createFoundationDbMessagePublisher()
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
|
||||
onVersionstampSent(message.versionstamp());
|
||||
}
|
||||
})
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
|
||||
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
|
||||
}
|
||||
|
||||
/// Create a message publisher that fetches messages from FoundationDB
|
||||
///
|
||||
/// @return a Flux of [FoundationDbMessageStreamEntry] fetched from FoundationDB
|
||||
/// @implNote The message publisher is stitched together by concatenating:
|
||||
/// 1. **A finite message publisher**: On initial request, we record the current end-of-queue key in the device mailbox.
|
||||
/// Then, we fetch all messages in order until the recorded key and finally complete the stream
|
||||
/// 2. **A queue-empty signal** is emitted
|
||||
/// 3. **An infinite message publisher**: We start reading from where the finite publisher left off. When all messages
|
||||
/// are read, we wait for new messages, publish them, then wait again in a loop forever (until the flux is canceled
|
||||
/// explicitly or due to an error). This is accomplished by setting a FoundationDB [watch](https://github.com/apple/foundationdb/wiki/An-Overview-how-Watches-Work)
|
||||
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
|
||||
/// See [FoundationDbMessageStore] for more details on the message insert process.
|
||||
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
|
||||
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
|
||||
.flatMapMany(maybeEndOfQueueKeyExclusive -> {
|
||||
final Flux<MessageStreamEntry.Envelope> finitePublisher = maybeEndOfQueueKeyExclusive
|
||||
final Flux<FoundationDbMessageStreamEntry.Message> finitePublisher = maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive, database, messageGuidCodec, maxMessagesPerScan).getMessages())
|
||||
endOfQueueKeyExclusive, database, maxMessagesPerScan, this::clearAcknowledgedMessages).getMessages())
|
||||
.orElseGet(Flux::empty);
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
|
||||
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
final Flux<MessageStreamEntry.Envelope> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
final Flux<FoundationDbMessageStreamEntry.Message> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
infinitePublisherBeginKey, KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
database, messageGuidCodec, maxMessagesPerScan, messagesAvailableWatchKey).getMessages();
|
||||
database, maxMessagesPerScan, messagesAvailableWatchKey, this::clearAcknowledgedMessages).getMessages();
|
||||
return Flux.concat(
|
||||
finitePublisher,
|
||||
Mono.just(new MessageStreamEntry.QueueEmpty()),
|
||||
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()),
|
||||
infinitePublisher
|
||||
);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows
|
||||
/// us to query keys up to and including the greatest key, and sets us up to begin reading from the next key in
|
||||
/// a subsequent scan.
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
|
||||
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows us
|
||||
/// to query keys up to and including the greatest key, and sets us up to begin reading from the next key in a
|
||||
/// subsequent scan.
|
||||
///
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
|
||||
return database.runAsync(
|
||||
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
|
||||
.thenApply(items -> {
|
||||
@@ -98,6 +140,90 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
|
||||
throw new UnsupportedOperationException("Not implemented");
|
||||
handleAcknowledged(messageGuidCodec.decodeMessageGuid(UUIDUtil.fromByteString(message.getServerGuidBinary())));
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void handleAcknowledged(final Versionstamp versionstamp) {
|
||||
// If we don't know about this versionstamp, or it's already acknowledged, there's nothing to do
|
||||
if (!sentVersionstamps.containsKey(versionstamp) || sentVersionstamps.get(versionstamp)) {
|
||||
return;
|
||||
}
|
||||
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void onVersionstampSent(final Versionstamp versionstamp) {
|
||||
sentVersionstamps.put(versionstamp, false);
|
||||
}
|
||||
|
||||
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
|
||||
///
|
||||
/// @param transaction The FoundationDB transaction in which to perform the range clear
|
||||
/// @param startInclusive The starting versionstamp of the range to be cleared (inclusive)
|
||||
/// @param endInclusive The ending versionstamp of the range to be cleared (inclusive)
|
||||
private void clearRange(final Transaction transaction, final Versionstamp startInclusive, final Versionstamp endInclusive) {
|
||||
final byte[] startKeyInclusive = deviceQueueSubspace.pack(Tuple.from(startInclusive));
|
||||
final byte[] endKeyExclusive = ByteArrayUtil.keyAfter(deviceQueueSubspace.pack(Tuple.from(endInclusive)));
|
||||
transaction.clear(startKeyInclusive, endKeyExclusive);
|
||||
}
|
||||
|
||||
/// Clear all outstanding acknowledged messages. Called when the stream ends
|
||||
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
|
||||
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages();
|
||||
return database.runAsync(transaction -> {
|
||||
clearAllAcknowlegedMessagedConsumer.accept(transaction);
|
||||
return CompletableFuture.completedFuture((Void) null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear acknowledged messages", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private synchronized Consumer<Transaction> clearAcknowledgedMessages() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
|
||||
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
|
||||
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
@VisibleForTesting
|
||||
synchronized List<Pair<Versionstamp, Versionstamp>> computeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = new ArrayList<>();
|
||||
Versionstamp startInclusive = null;
|
||||
Versionstamp endInclusive = null;
|
||||
|
||||
for (final Map.Entry<Versionstamp, Boolean> entry : sentVersionstamps.entrySet()) {
|
||||
if (entry.getValue()) {
|
||||
// Message is acknowledged, so we can either start tracking a new range if we aren't already, or extend our
|
||||
// current range
|
||||
if (startInclusive == null) {
|
||||
startInclusive = entry.getKey();
|
||||
}
|
||||
endInclusive = entry.getKey();
|
||||
} else {
|
||||
// Message is un-acknowledged, which means either it is a "range-breaker" or we never started tracking an
|
||||
// acknowledged range. Mark the currently tracked range flushable, if it exists.
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
startInclusive = null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
}
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
sealed interface FoundationDbMessageStreamEntry permits FoundationDbMessageStreamEntry.Message,
|
||||
FoundationDbMessageStreamEntry.QueueEmpty {
|
||||
|
||||
record Message(Versionstamp versionstamp, byte[] payload) implements FoundationDbMessageStreamEntry {}
|
||||
|
||||
record QueueEmpty() implements FoundationDbMessageStreamEntry {}
|
||||
|
||||
default MessageStreamEntry toMessageStreamEntry(final MessageGuidCodec messageGuidCodec) {
|
||||
return switch (this) {
|
||||
case Message(final Versionstamp versionstamp, final byte[] payload): {
|
||||
try {
|
||||
yield new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(payload)
|
||||
.toBuilder()
|
||||
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp)))
|
||||
.build());
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
case QueueEmpty():
|
||||
yield new MessageStreamEntry.QueueEmpty();
|
||||
};
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -14,7 +14,6 @@ import com.google.api.services.androidpublisher.AndroidPublisherRequest;
|
||||
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
|
||||
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
|
||||
import com.google.api.services.androidpublisher.model.Money;
|
||||
import com.google.api.services.androidpublisher.model.OfferDetails;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseLineItem;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseV2;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchasesAcknowledgeRequest;
|
||||
@@ -335,9 +334,14 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
if (e.getStatusCode() == Response.Status.TOO_MANY_REQUESTS.getStatusCode()) {
|
||||
throw new RateLimitExceededException(null);
|
||||
}
|
||||
final String details = e instanceof GoogleJsonResponseException
|
||||
? ((GoogleJsonResponseException) e).getDetails().toString()
|
||||
: "";
|
||||
|
||||
final String details;
|
||||
|
||||
if (e instanceof GoogleJsonResponseException googleJsonResponseException && googleJsonResponseException.getDetails() != null) {
|
||||
details = googleJsonResponseException.getDetails().toString();
|
||||
} else {
|
||||
details = "";
|
||||
}
|
||||
|
||||
final String message =
|
||||
String.format("Unexpected HTTP status code %s from androidpublisher: %s", e.getStatusCode(), details);
|
||||
|
||||
@@ -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();
|
||||
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -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);
|
||||
|
||||
+10
-4
@@ -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;
|
||||
@@ -206,7 +208,7 @@ public record CommandDependencies(
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
configuration.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbAsyncClient,
|
||||
dynamoDbClient,
|
||||
clock);
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
@@ -281,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);
|
||||
@@ -338,12 +344,12 @@ public record CommandDependencies(
|
||||
configuration.getAppleAppStore().subscriptionGroupId(),
|
||||
configuration.getAppleAppStore().productIdToLevel());
|
||||
final SubscriptionManager subscriptionManager = new SubscriptionManager(
|
||||
new Subscriptions(configuration.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient),
|
||||
new Subscriptions(configuration.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient),
|
||||
List.of(googlePlayBillingManager, appleAppStoreManager),
|
||||
zkReceiptOperations,
|
||||
issuedReceiptsManager);
|
||||
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, configuration.getApnConfiguration());
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), configuration.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, configuration.getFcmConfiguration().credentials().value());
|
||||
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
|
||||
apnSender, fcmSender, accountsManager, 0, 0, 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
|
||||
|
||||
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+14
-16
@@ -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
-14
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+89
-14
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -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;
|
||||
|
||||
+9
-12
@@ -45,6 +45,7 @@ class PhoneVerificationTokenManagerTest {
|
||||
private RegistrationServiceClient registrationServiceClient;
|
||||
private RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private RegistrationRecoveryChecker registrationRecoveryChecker;
|
||||
private PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
|
||||
private PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
|
||||
@@ -55,7 +56,7 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(PHONE_NUMBER))
|
||||
.thenReturn(CompletableFuture.completedFuture(PHONE_NUMBER_IDENTIFIER));
|
||||
|
||||
@@ -166,7 +167,7 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(true);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
.thenReturn(true);
|
||||
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
@@ -183,7 +184,7 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(false);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
.thenReturn(true);
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
@@ -200,7 +201,7 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(true);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
.thenReturn(false);
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
@@ -210,8 +211,7 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void verifyRecoveryPasswordManagerException(final Throwable recoveryPasswordManagerException)
|
||||
throws ExecutionException, InterruptedException, TimeoutException {
|
||||
void verifyPhoneNumberIdentifiersException(final Throwable phoneNumberIdentifiersException) {
|
||||
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
@@ -219,11 +219,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);
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(PHONE_NUMBER))
|
||||
.thenReturn(CompletableFuture.failedFuture(phoneNumberIdentifiersException));
|
||||
|
||||
assertThrows(ServerErrorException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
PHONE_NUMBER,
|
||||
@@ -231,7 +228,7 @@ class PhoneVerificationTokenManagerTest {
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
private static List<Throwable> verifyRecoveryPasswordManagerException() {
|
||||
private static List<Throwable> verifyPhoneNumberIdentifiersException() {
|
||||
return List.of(new ExecutionException(new RuntimeException()), new TimeoutException());
|
||||
}
|
||||
}
|
||||
|
||||
-3
@@ -22,7 +22,6 @@ import static org.mockito.Mockito.when;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -99,8 +98,6 @@ class RegistrationLockVerificationManagerTest {
|
||||
when(account.hasLockedCredentials()).thenReturn(alreadyLocked);
|
||||
doThrow(new NotPushRegisteredException()).when(pushNotificationManager).sendAttemptLoginNotification(any(), any());
|
||||
|
||||
when(registrationRecoveryPasswordsManager.remove(any())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
final Pair<Class<? extends Exception>, Consumer<Exception>> exceptionType = switch (error) {
|
||||
case MISMATCH -> {
|
||||
when(existingRegistrationLock.verify(clientRegistrationLock)).thenReturn(false);
|
||||
|
||||
+4
-4
@@ -341,7 +341,7 @@ public class BackupAuthManagerTest {
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
|
||||
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
.thenReturn(true);
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, expirationTime));
|
||||
verify(accountsManager, times(1)).update(any(Account.class), any());
|
||||
}
|
||||
@@ -354,7 +354,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
.thenReturn(true);
|
||||
assertThatExceptionOfType(BackupMissingIdCommitmentException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)));
|
||||
}
|
||||
@@ -375,7 +375,7 @@ public class BackupAuthManagerTest {
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
|
||||
when(redeemedReceiptsManager.put(any(), eq(newExpirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
.thenReturn(true);
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, newExpirationTime));
|
||||
|
||||
final ArgumentCaptor<Consumer<Account>> updaterCaptor = ArgumentCaptor.captor();
|
||||
@@ -430,7 +430,7 @@ public class BackupAuthManagerTest {
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.update(any(Account.class), any())).thenReturn(account);
|
||||
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
.thenReturn(false);
|
||||
|
||||
assertThatExceptionOfType(BackupBadReceiptException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)));
|
||||
|
||||
-2
@@ -833,8 +833,6 @@ class AccountControllerTest {
|
||||
void testAccountsAttributesUpdateRecoveryPassword() {
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(32);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.store(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/attributes/")
|
||||
.request()
|
||||
|
||||
+2
-5
@@ -23,7 +23,6 @@ import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -114,8 +113,7 @@ class DonationControllerTest {
|
||||
when(receiptCredentialPresentation.getReceiptLevel()).thenReturn(receiptLevel);
|
||||
final long receiptExpiration = nowEpochSeconds + 86400 * 30;
|
||||
when(receiptCredentialPresentation.getReceiptExpirationTime()).thenReturn(receiptExpiration);
|
||||
when(redeemedReceiptsManager.put(same(receiptSerial), eq(receiptExpiration), eq(receiptLevel), eq(AuthHelper.VALID_UUID))).thenReturn(
|
||||
CompletableFuture.completedFuture(Boolean.TRUE));
|
||||
when(redeemedReceiptsManager.put(same(receiptSerial), eq(receiptExpiration), eq(receiptLevel), eq(AuthHelper.VALID_UUID))).thenReturn(true);
|
||||
when(accountsManager.getByAccountIdentifier(eq(AuthHelper.VALID_UUID)))
|
||||
.thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
@@ -138,8 +136,7 @@ class DonationControllerTest {
|
||||
when(receiptCredentialPresentation.getReceiptLevel()).thenReturn(receiptLevel);
|
||||
final long receiptExpiration = nowEpochSeconds + 86400 * 30;
|
||||
when(receiptCredentialPresentation.getReceiptExpirationTime()).thenReturn(receiptExpiration);
|
||||
when(redeemedReceiptsManager.put(same(receiptSerial), eq(receiptExpiration), eq(receiptLevel), eq(AuthHelper.VALID_UUID))).thenReturn(
|
||||
CompletableFuture.completedFuture(Boolean.FALSE));
|
||||
when(redeemedReceiptsManager.put(same(receiptSerial), eq(receiptExpiration), eq(receiptLevel), eq(AuthHelper.VALID_UUID))).thenReturn(false);
|
||||
when(accountsManager.getByAccountIdentifier(eq(AuthHelper.VALID_UUID)))
|
||||
.thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
|
||||
+41
-30
@@ -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.getV1(AuthHelper.VALID_UUID_TWO, version)).thenReturn(
|
||||
Optional.of(new VersionedProfileV1(version, 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.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();
|
||||
@@ -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.getV1(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();
|
||||
@@ -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.getV1(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();
|
||||
@@ -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.getV1(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));
|
||||
}
|
||||
}
|
||||
+2
-8
@@ -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
|
||||
|
||||
+29
-53
@@ -175,10 +175,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.get(eq(Arrays.copyOfRange(subscriberUserAndKey, 0, 16)), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
|
||||
when(SUBSCRIPTIONS.subscriptionCreated(any(), any(), any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -233,7 +230,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.get(eq(Arrays.copyOfRange(subscriberUserAndKey, 0, 16)), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final String level = String.valueOf(levelId);
|
||||
final String idempotencyKey = UUID.randomUUID().toString();
|
||||
@@ -260,7 +257,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.get(eq(Arrays.copyOfRange(subscriberUserAndKey, 0, 16)), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/create_payment_method", subscriberId))
|
||||
@@ -305,8 +302,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(CompletableFuture.completedFuture(
|
||||
Subscriptions.GetResult.NOT_STORED));
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED);
|
||||
|
||||
final Map<String, AttributeValue> dynamoItem = Map.of(Subscriptions.KEY_PASSWORD, b(new byte[16]),
|
||||
Subscriptions.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
|
||||
@@ -314,7 +310,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
);
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(record));
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(record);
|
||||
|
||||
final Response createResponse = RESOURCE_EXTENSION.target(String.format("/v1/subscription/%s", subscriberId))
|
||||
.request()
|
||||
@@ -322,9 +318,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
assertThat(createResponse.getStatus()).isEqualTo(200);
|
||||
|
||||
// creating should be idempotent
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(CompletableFuture.completedFuture(
|
||||
Subscriptions.GetResult.found(record)));
|
||||
when(SUBSCRIPTIONS.accessedAt(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final Response idempotentCreateResponse = RESOURCE_EXTENSION.target(
|
||||
String.format("/v1/subscription/%s", subscriberId))
|
||||
@@ -334,9 +328,8 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
|
||||
// when the manager returns `null`, it means there was a password mismatch from the storage layer `create`.
|
||||
// this could happen if there is a race between two concurrent `create` requests for the same user ID
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(CompletableFuture.completedFuture(
|
||||
Subscriptions.GetResult.NOT_STORED));
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED);
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(null);
|
||||
|
||||
final Response managerCreateNullResponse = RESOURCE_EXTENSION.target(
|
||||
String.format("/v1/subscription/%s", subscriberId))
|
||||
@@ -350,8 +343,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final String mismatchedSubscriberId = Base64.getEncoder().encodeToString(subscriberUserAndMismatchedKey);
|
||||
|
||||
// a password mismatch for an existing record
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(CompletableFuture.completedFuture(
|
||||
Subscriptions.GetResult.PASSWORD_MISMATCH));
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.PASSWORD_MISMATCH);
|
||||
|
||||
final Response passwordMismatchResponse = RESOURCE_EXTENSION.target(
|
||||
String.format("/v1/subscription/%s", mismatchedSubscriberId))
|
||||
@@ -380,8 +372,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(CompletableFuture.completedFuture(
|
||||
Subscriptions.GetResult.NOT_STORED));
|
||||
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED);
|
||||
|
||||
final Map<String, AttributeValue> dynamoItem = Map.of(Subscriptions.KEY_PASSWORD, b(new byte[16]),
|
||||
Subscriptions.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
|
||||
@@ -389,8 +380,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
);
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class))).thenReturn(record);
|
||||
|
||||
final Response createSubscriberResponse = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s", subscriberId))
|
||||
@@ -400,7 +390,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
assertThat(createSubscriberResponse.getStatus()).isEqualTo(200);
|
||||
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final String customerId = "some-customer-id";
|
||||
final ProcessorCustomer customer = new ProcessorCustomer(
|
||||
@@ -414,9 +404,8 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record recordWithCustomerId = Subscriptions.Record.from(record.user,
|
||||
dynamoItemWithProcessorCustomer);
|
||||
|
||||
when(SUBSCRIPTIONS.setProcessorAndCustomerId(any(Subscriptions.Record.class), any(),
|
||||
any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(recordWithCustomerId));
|
||||
when(SUBSCRIPTIONS.setProcessorAndCustomerId(any(Subscriptions.Record.class), any(), any(Instant.class)))
|
||||
.thenReturn(recordWithCustomerId);
|
||||
|
||||
final String clientSecret = "some-client-secret";
|
||||
when(STRIPE_MANAGER.createPaymentMethodSetupToken(customerId))
|
||||
@@ -447,12 +436,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
.thenReturn(record);
|
||||
|
||||
// set up mocks
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, 5, "usd", "abcd"))
|
||||
@@ -486,17 +475,15 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
.thenReturn(record);
|
||||
|
||||
// set up mocks
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
when(BRAINTREE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId("subscription"));
|
||||
when(SUBSCRIPTIONS.subscriptionCreated(any(), any(), any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, levelId, "usd", "abcd"))
|
||||
@@ -536,12 +523,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
.thenReturn(record);
|
||||
|
||||
// set up mocks
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final Object subscriptionObj = new Object();
|
||||
when(BRAINTREE_MANAGER.getSubscription(any())).thenReturn(subscriptionObj);
|
||||
@@ -552,8 +539,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
if (expectUpdate) {
|
||||
when(BRAINTREE_MANAGER.updateSubscription(any(), any(), anyLong(), anyString()))
|
||||
.thenReturn(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId(updatedSubscriptionId));
|
||||
when(SUBSCRIPTIONS.subscriptionLevelChanged(any(), any(), anyLong(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
|
||||
final String idempotencyKey = "abcd";
|
||||
@@ -609,11 +594,11 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
.thenReturn(record);
|
||||
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final Object subscriptionObj = new Object();
|
||||
when(BRAINTREE_MANAGER.getSubscription(any())).thenReturn(subscriptionObj);
|
||||
@@ -653,14 +638,11 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(user, dynamoItem);
|
||||
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
when(APPSTORE_MANAGER.validateTransaction(eq(originalTxId)))
|
||||
.thenReturn(99L);
|
||||
|
||||
when(SUBSCRIPTIONS.setIapPurchase(any(), any(), anyString(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/appstore/%s", subscriberId, originalTxId))
|
||||
.request()
|
||||
@@ -695,15 +677,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
);
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(user, dynamoItem);
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final GooglePlayBillingManager.ValidatedToken validatedToken = mock(GooglePlayBillingManager.ValidatedToken.class);
|
||||
when(validatedToken.getLevel()).thenReturn(99L);
|
||||
when(PLAY_MANAGER.validateToken(eq(purchaseToken))).thenReturn(validatedToken);
|
||||
|
||||
when(SUBSCRIPTIONS.setIapPurchase(any(), any(), anyString(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/playbilling/%s", subscriberId, purchaseToken))
|
||||
.request()
|
||||
@@ -739,16 +718,13 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
Subscriptions.KEY_PROCESSOR_ID_CUSTOMER_ID, b(oldPc.toDynamoBytes()));
|
||||
final Subscriptions.Record record = Subscriptions.Record.from(user, dynamoItem);
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
|
||||
final GooglePlayBillingManager.ValidatedToken validatedToken = mock(GooglePlayBillingManager.ValidatedToken.class);
|
||||
when(validatedToken.getLevel()).thenReturn(99L);
|
||||
|
||||
when(PLAY_MANAGER.validateToken(eq(newPurchaseToken))).thenReturn(validatedToken);
|
||||
|
||||
when(SUBSCRIPTIONS.setIapPurchase(any(), any(), anyString(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/playbilling/%s", subscriberId, newPurchaseToken))
|
||||
.request()
|
||||
@@ -776,14 +752,14 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(Subscriptions.Record.from(
|
||||
.thenReturn(Subscriptions.GetResult.found(Subscriptions.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16),
|
||||
Map.of(Subscriptions.KEY_PASSWORD, b(new byte[16]),
|
||||
Subscriptions.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
|
||||
Subscriptions.KEY_ACCESSED_AT, n(Instant.now().getEpochSecond()),
|
||||
Subscriptions.KEY_PROCESSOR_ID_CUSTOMER_ID,
|
||||
b(new ProcessorCustomer("customer", PaymentProvider.STRIPE).toDynamoBytes()),
|
||||
Subscriptions.KEY_SUBSCRIPTION_ID, s("subscriptionId"))))));
|
||||
Subscriptions.KEY_SUBSCRIPTION_ID, s("subscriptionId")))));
|
||||
when(STRIPE_MANAGER.getReceiptItem(any()))
|
||||
.thenThrow(new SubscriptionChargeFailurePaymentRequiredException(
|
||||
PaymentProvider.STRIPE,
|
||||
@@ -831,7 +807,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTIONS.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Subscriptions.GetResult.found(record)));
|
||||
.thenReturn(Subscriptions.GetResult.found(record));
|
||||
when(BRAINTREE_MANAGER.getReceiptItem(subscriptionId)).thenReturn(
|
||||
new CustomerAwareSubscriptionPaymentProcessor.ReceiptItem(
|
||||
"itemId",
|
||||
|
||||
+86
-126
@@ -16,6 +16,7 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -35,6 +36,7 @@ import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -55,6 +57,7 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
@@ -63,6 +66,8 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRegistrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
@@ -86,6 +91,7 @@ import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsMan
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
@@ -109,7 +115,8 @@ class VerificationControllerTest {
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final CarrierDataProvider carrierDataProvider = mock(CarrierDataProvider.class);
|
||||
private final Clock clock = Clock.systemUTC();
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
private final Clock clock = TestClock.pinned(Instant.now());
|
||||
|
||||
private final RateLimiter captchaLimiter = mock(RateLimiter.class);
|
||||
private final RateLimiter pushChallengeLimiter = mock(RateLimiter.class);
|
||||
@@ -130,7 +137,7 @@ class VerificationControllerTest {
|
||||
.addResource(
|
||||
new VerificationController(registrationServiceClient, verificationSessionManager, pushNotificationManager,
|
||||
registrationCaptchaManager, registrationRecoveryPasswordsManager, phoneNumberIdentifiers, rateLimiters, accountsManager,
|
||||
carrierDataProvider, RegistrationFraudChecker.noop(), dynamicConfigurationManager, clock))
|
||||
carrierDataProvider, RegistrationFraudChecker.noop(), dynamicConfigurationManager, experimentEnrollmentManager, clock))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -149,6 +156,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(dynamicConfiguration);
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(NUMBER))
|
||||
.thenReturn(CompletableFuture.completedFuture(PNI));
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(VerificationController.VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME)))
|
||||
.thenReturn(true);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -231,8 +240,6 @@ class VerificationControllerTest {
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
when(verificationSessionManager.insert(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session")
|
||||
@@ -272,8 +279,6 @@ class VerificationControllerTest {
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
when(verificationSessionManager.insert(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session")
|
||||
@@ -293,8 +298,6 @@ class VerificationControllerTest {
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
when(verificationSessionManager.insert(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session")
|
||||
@@ -328,8 +331,6 @@ class VerificationControllerTest {
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
|
||||
when(verificationSessionManager.insert(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(accountsManager.getByE164(NUMBER))
|
||||
.thenReturn(isReregistration ? Optional.of(mock(Account.class)) : Optional.empty());
|
||||
@@ -391,13 +392,9 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(
|
||||
.thenReturn(Optional.of(
|
||||
new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(),
|
||||
null, null, false, clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
null, null, false, clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -436,12 +433,8 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
doThrow(RateLimitExceededException.class)
|
||||
.when(captchaLimiter).validate(anyString());
|
||||
@@ -472,12 +465,8 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
doThrow(RateLimitExceededException.class)
|
||||
.when(pushChallengeLimiter).validate(anyString());
|
||||
@@ -508,12 +497,9 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(VerificationSession.Information.PUSH_CHALLENGE),
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(VerificationSession.Information.PUSH_CHALLENGE),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -542,17 +528,13 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(AssessmentResult.invalid()));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
.request()
|
||||
@@ -589,17 +571,14 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId,
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
|
||||
"challenge",
|
||||
null,
|
||||
List.of(VerificationSession.Information.CAPTCHA),
|
||||
List.of(VerificationSession.Information.PUSH_CHALLENGE),
|
||||
null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
.request()
|
||||
@@ -636,14 +615,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(), List.of(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(registrationRecoveryPasswordsManager.remove(PNI))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(), List.of(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -674,15 +647,12 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId,
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
|
||||
"challenge",
|
||||
null,
|
||||
List.of(VerificationSession.Information.PUSH_CHALLENGE, VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -720,16 +690,13 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(AssessmentResult.alwaysValid()));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -767,19 +734,16 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId,
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
|
||||
"challenge",
|
||||
null,
|
||||
List.of(VerificationSession.Information.CAPTCHA, VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(AssessmentResult.alwaysValid()));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -816,19 +780,16 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId,
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId,
|
||||
null,
|
||||
null,
|
||||
List.of(VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
|
||||
.thenThrow(new IOException("expected service error"));
|
||||
|
||||
when(verificationSessionManager.update(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -883,7 +844,7 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
when(verificationSessionManager.findForId(encodeSessionId(SESSION_ID)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodeSessionId(SESSION_ID))
|
||||
@@ -931,7 +892,7 @@ class VerificationControllerTest {
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS))));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(mock(VerificationSession.class))));
|
||||
.thenReturn(Optional.of(mock(VerificationSession.class)));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -953,9 +914,7 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(mock(VerificationSession.class))));
|
||||
when(registrationRecoveryPasswordsManager.remove(PNI))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
.thenReturn(Optional.of(mock(VerificationSession.class)));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId)
|
||||
@@ -977,12 +936,10 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(registrationServiceSession));
|
||||
when(registrationRecoveryPasswordsManager.remove(PNI)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId + "/code")
|
||||
@@ -1009,9 +966,9 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(new VerificationSession(encodedSessionId, null, null,
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null,
|
||||
List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId + "/code")
|
||||
@@ -1040,9 +997,8 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId + "/code")
|
||||
@@ -1068,9 +1024,8 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(
|
||||
new CompletionException(new VerificationSessionRateLimitExceededException(registrationServiceSession,
|
||||
@@ -1100,9 +1055,8 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(
|
||||
new CompletionException(new TransportNotAllowedException(registrationServiceSession))));
|
||||
@@ -1123,8 +1077,9 @@ class VerificationControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestVerificationCodeSuccess() {
|
||||
@CartesianTest
|
||||
void requestVerificationCodeSuccess(@CartesianTest.Values(booleans = {true, false}) final boolean accountExistsWithNumber,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean enrolledInExperiment) {
|
||||
final String encodedSessionId = encodeSessionId(SESSION_ID);
|
||||
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
|
||||
false, null, null,
|
||||
@@ -1132,16 +1087,27 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(registrationServiceSession));
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account existingAccount = mock(Account.class);
|
||||
when(existingAccount.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
|
||||
when(accountsManager.getByE164(any()))
|
||||
.thenReturn(accountExistsWithNumber ? Optional.of(existingAccount) : Optional.empty());
|
||||
|
||||
when(experimentEnrollmentManager.isEnrolled(accountIdentifier, VerificationController.VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
.thenReturn(enrolledInExperiment);
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId + "/code")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
|
||||
|
||||
try (Response response = request.post(Entity.json(requestVerificationCodeJson("sms", "android")))) {
|
||||
assertEquals(HttpStatus.SC_OK, response.getStatus());
|
||||
|
||||
@@ -1150,6 +1116,12 @@ class VerificationControllerTest {
|
||||
|
||||
assertTrue(verificationSessionResponse.allowedToRequestCode());
|
||||
assertTrue(verificationSessionResponse.requestedInformation().isEmpty());
|
||||
|
||||
if (accountExistsWithNumber && enrolledInExperiment) {
|
||||
verify(pushNotificationManager).trySendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
|
||||
} else {
|
||||
verify(pushNotificationManager, never()).trySendVerificationCodeRequestedNotifications(any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1165,9 +1137,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(
|
||||
@@ -1209,9 +1180,8 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.getSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new CompletionException(
|
||||
@@ -1243,9 +1213,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new CompletionException(new RuntimeException())));
|
||||
@@ -1270,11 +1239,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(registrationRecoveryPasswordsManager.remove(PNI))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session/" + encodedSessionId + "/code")
|
||||
@@ -1307,9 +1273,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
// There is no explicit indication in the exception that no code has been sent, but we treat all RegistrationServiceExceptions
|
||||
// in which the response has a session object as conflicted state
|
||||
@@ -1344,9 +1309,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new CompletionException(new RegistrationServiceException(null))));
|
||||
@@ -1370,9 +1334,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(
|
||||
new CompletionException(new VerificationSessionRateLimitExceededException(registrationServiceSession,
|
||||
@@ -1402,11 +1365,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(registrationRecoveryPasswordsManager.remove(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
.thenReturn(Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration())));
|
||||
|
||||
final RegistrationServiceSession verifiedSession = new RegistrationServiceSession(SESSION_ID, NUMBER, true, null,
|
||||
null, 0L,
|
||||
|
||||
+15
-24
@@ -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());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+136
@@ -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);
|
||||
}
|
||||
}
|
||||
-4
@@ -26,7 +26,6 @@ import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -106,9 +105,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
when(rateLimiters.getSetZkCredentialKeyLimiter()).thenReturn(rateLimiter);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.store(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
return new AccountsGrpcService(accountsManager,
|
||||
rateLimiters,
|
||||
usernameHashZkProofVerifier,
|
||||
|
||||
+3
-5
@@ -372,7 +372,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
|
||||
final Optional<VersionedProfileV1> profile = Optional.of(new VersionedProfileV1(HexFormat.of().formatHex(requestVersion), name, avatar, emoji, about, paymentAddress, phoneNumberSharing, new byte[0]));
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v)));
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
|
||||
@@ -428,10 +428,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
@@ -472,10 +471,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
|
||||
+4
-6
@@ -304,7 +304,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final byte[] validPhoneNumberSharing = new byte[29];
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(
|
||||
Optional.of(HexFormat.of().formatHex(TestRandomUtil.nextBytes(32))));
|
||||
Optional.of(TestRandomUtil.nextBytes(32)));
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
@@ -715,7 +715,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setVersion(ByteString.copyFrom(requestVersion))
|
||||
.build();
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v)));
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(profile);
|
||||
|
||||
@@ -757,7 +757,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
|
||||
final UUID targetAci = UUID.randomUUID();
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
@@ -766,7 +765,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci)))
|
||||
.thenReturn(Optional.of(targetAccount));
|
||||
when(targetAccount.getUuid()).thenReturn(targetAci);
|
||||
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
|
||||
when(profilesManager.get(eq(targetAci), aryEq(version))).thenReturn(Optional.of(v2Profile));
|
||||
@@ -801,7 +800,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
|
||||
final UUID targetAci = UUID.randomUUID();
|
||||
@@ -810,7 +808,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(targetAccount));
|
||||
|
||||
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(profilesManager.get(targetAci, version)).thenReturn(Optional.of(v2Profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.netty.channel.WriteBufferWaterMark;
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import io.netty.util.test.LeakPresenceExtension;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
|
||||
@ExtendWith(LeakPresenceExtension.class)
|
||||
class H2FrameProxyHandlerTest {
|
||||
@Test
|
||||
void proxyWritabilityChanged() {
|
||||
final EmbeddedChannel target = new EmbeddedChannel();
|
||||
final EmbeddedChannel source = new EmbeddedChannel(new H2FrameProxyHandler(target, "test"));
|
||||
|
||||
// Set a tiny watermark to guarantee an unflushed write sets to unwritable, and then buffer some data
|
||||
final byte[] bufferedData = "8 bytes!".getBytes(StandardCharsets.UTF_8);
|
||||
target.config().setWriteBufferWaterMark(new WriteBufferWaterMark(4, 8));
|
||||
target.write(bufferedData);
|
||||
|
||||
assertNull(target.readOutbound(), "nothing should be written without a flush");
|
||||
assertFalse(target.isWritable(), "target should be unwritable because we've buffered more than the high watermark");
|
||||
assertFalse(source.config().isAutoRead(), "source should not read because the target is unwritable");
|
||||
|
||||
target.flush();
|
||||
assertTrue(target.isWritable(), "after a flush, the target should be writable");
|
||||
assertTrue(source.config().isAutoRead(), "after the target becomes writable, autoRead should be enabled");
|
||||
}
|
||||
}
|
||||
+641
@@ -0,0 +1,641 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.Channel;
|
||||
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.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioChannelOption;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.haproxy.HAProxyCommand;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessage;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessageEncoder;
|
||||
import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
|
||||
import io.netty.handler.codec.haproxy.HAProxyProxiedProtocol;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
|
||||
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.Http2DataFrame;
|
||||
import io.netty.handler.codec.http2.Http2Error;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2Headers;
|
||||
import io.netty.handler.codec.http2.Http2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.handler.codec.http2.Http2ResetFrame;
|
||||
import io.netty.handler.codec.http2.Http2Settings;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannel;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
|
||||
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.handler.ssl.util.InsecureTrustManagerFactory;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.test.LeakPresenceExtension;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.net.ssl.SSLException;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
|
||||
@ExtendWith(LeakPresenceExtension.class)
|
||||
class OmnibusH2ServerTest {
|
||||
private static final String KEYSTORE_PASSWORD = "password";
|
||||
|
||||
// Paths that start with PREFIX should go to the prefix backend, everything else to default.
|
||||
private static final String PREFIX_BACKEND_IDENTITY = "prefix-backend";
|
||||
private static final String PREFIX = "/v1/prefix";
|
||||
private static final String DEFAULT_BACKEND_IDENTITY = "default-backend";
|
||||
|
||||
private final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
|
||||
private final DefaultEventLoopGroup localEventLoopGroup = new DefaultEventLoopGroup();
|
||||
|
||||
private List<Channel> backendChannelsToShutDown;
|
||||
private List<OmnibusH2Server> omnibusH2ServersToShutDown;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
backendChannelsToShutDown = new ArrayList<>();
|
||||
omnibusH2ServersToShutDown = new ArrayList<>();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
omnibusH2ServersToShutDown.forEach(OmnibusH2Server::stop);
|
||||
backendChannelsToShutDown.forEach(c -> c.close().syncUninterruptibly());
|
||||
localEventLoopGroup.shutdownGracefully(1, 1000, TimeUnit.MILLISECONDS).sync();
|
||||
nioEventLoopGroup.shutdownGracefully(1, 1000, TimeUnit.MILLISECONDS).sync();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void defaultBackend(final boolean localChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PREFIX, startBackendServer(localChannel, PREFIX_BACKEND_IDENTITY)),
|
||||
startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), "/a/different/path");
|
||||
assertEquals(DEFAULT_BACKEND_IDENTITY, response);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void forwardedForHeader(final boolean usePpv2) throws Exception {
|
||||
final String expectedSource = usePpv2 ? "127.0.0.123" : "127.0.0.1";
|
||||
final HAProxyMessage proxyMessage = usePpv2
|
||||
? new HAProxyMessage(HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4, expectedSource, "127.0.0.2", 1234, 5678)
|
||||
: null;
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final Channel h2Connection = connectToOmnibus(server, proxyMessage);
|
||||
final String xForwardedFor = sendRequestThroughOmnibus(h2Connection, "/forwarded-for");
|
||||
assertEquals(expectedSource, xForwardedFor);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void prefixBackend(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(strings = {"/v1/prefix", "/v1/prefix/", "/v1/prefix/other"}) final String path) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PREFIX, startBackendServer(localChannel, PREFIX_BACKEND_IDENTITY)),
|
||||
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), path);
|
||||
assertEquals(PREFIX_BACKEND_IDENTITY, response);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void multipleStreamsOnSameConnection(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean defaultLocalChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean prefixLocalChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PREFIX, startBackendServer(prefixLocalChannel, PREFIX_BACKEND_IDENTITY)),
|
||||
startBackendServer(defaultLocalChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final int numStreams = 10;
|
||||
|
||||
// Create concurrent streams to both backends on the same connection simultaneously
|
||||
@SuppressWarnings("rawtypes")
|
||||
final CompletableFuture[] futures = IntStream.range(0, numStreams)
|
||||
.mapToObj(i -> CompletableFuture.supplyAsync(() ->
|
||||
sendRequestThroughOmnibus(
|
||||
h2Connection,
|
||||
i % 2 == 0 ? PREFIX : "/v1/other")))
|
||||
.toArray(CompletableFuture[]::new);
|
||||
|
||||
// Ensure we get the response from the correct backend for each stream
|
||||
CompletableFuture.allOf(futures).join();
|
||||
for (int i = 0; i < numStreams; i++) {
|
||||
assertEquals(
|
||||
i % 2 == 0 ? PREFIX_BACKEND_IDENTITY : DEFAULT_BACKEND_IDENTITY,
|
||||
futures[i].resultNow());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void backendDownStreamReset(final boolean localChannel) throws Exception {
|
||||
final Channel backend = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY);
|
||||
final OmnibusH2Server server = startOmnibusServer(backend);
|
||||
|
||||
// Kill the default backend so connection attempts from the omnibus fail
|
||||
backend.close().syncUninterruptibly();
|
||||
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final CompletableFuture<Http2HeadersFrame> headersFuture = new CompletableFuture<>();
|
||||
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
|
||||
.handler(new HeadersCollectorHandler(headersFuture))
|
||||
.open()
|
||||
.syncUninterruptibly()
|
||||
.getNow();
|
||||
|
||||
final Http2Headers headers = new DefaultHttp2Headers()
|
||||
.method("POST")
|
||||
.path("/test")
|
||||
.scheme("https")
|
||||
.authority("localhost");
|
||||
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, true));
|
||||
final Http2HeadersFrame responseHeaders = headersFuture.join();
|
||||
assertEquals("502", responseHeaders.headers().status().toString());
|
||||
|
||||
// Stream is dead, but connection should stay alive
|
||||
assertFalse(
|
||||
h2Connection.closeFuture().awaitUninterruptibly(5, TimeUnit.MILLISECONDS),
|
||||
"connection should stay open");
|
||||
assertTrue(h2Connection.isOpen());
|
||||
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void backendCloseClosesClientStream(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(strings = {"/goaway", "/reset"}) final String path) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final CompletableFuture<Http2ResetFrame> resetFuture = new CompletableFuture<>();
|
||||
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
|
||||
.handler(new RstCollectorHandler(resetFuture))
|
||||
.open()
|
||||
.syncUninterruptibly()
|
||||
.getNow();
|
||||
|
||||
final Http2Headers headers = new DefaultHttp2Headers()
|
||||
.method("POST")
|
||||
// Triggers the server stream handler to either GOAWAY+close or send an RST based on the path
|
||||
.path(path)
|
||||
.scheme("https")
|
||||
.authority("localhost");
|
||||
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, true));
|
||||
assertEquals(Http2Error.CANCEL.code(), resetFuture.join().errorCode());
|
||||
|
||||
// client<->omnibus h2 connection stays open after a backend close/rst
|
||||
assertTrue(h2Connection.isActive());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void queuedDataFrames(final boolean localChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final CompletableFuture<String> responseFuture = new CompletableFuture<>();
|
||||
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
|
||||
.handler(new ResponseCollectorHandler(responseFuture))
|
||||
.open()
|
||||
.syncUninterruptibly()
|
||||
.getNow();
|
||||
|
||||
final Http2Headers headers = new DefaultHttp2Headers()
|
||||
.method("POST")
|
||||
.path("/test")
|
||||
.scheme("https")
|
||||
.authority("localhost");
|
||||
|
||||
final int numFrames = 64;
|
||||
|
||||
// Omnibus should handle queueing up frames while connecting to the backend if we blast all the frames right away
|
||||
stream.write(new DefaultHttp2HeadersFrame(headers, false));
|
||||
final StringBuilder expectedBuilder = new StringBuilder();
|
||||
for (int i = 0; i < numFrames; i++) {
|
||||
final String chunk = String.format("chunk-%03d;", i);
|
||||
expectedBuilder.append(chunk);
|
||||
final boolean endStream = (i == numFrames - 1);
|
||||
stream.write(new DefaultHttp2DataFrame(
|
||||
Unpooled.copiedBuffer(chunk, StandardCharsets.UTF_8), endStream));
|
||||
}
|
||||
stream.flush();
|
||||
final String expected = expectedBuilder.toString();
|
||||
|
||||
final String response = responseFuture.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(expected, response);
|
||||
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void clientDisconnectClosesBackendConnections(final boolean localChannel) throws Exception {
|
||||
final CompletableFuture<Channel> backendH2Connection = new CompletableFuture<>();
|
||||
final Channel backendServerChannel = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY, backendH2Connection::complete, _ -> {});
|
||||
final OmnibusH2Server server = startOmnibusServer(backendServerChannel);
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
|
||||
final Http2StreamChannel stream = streamBootstrap
|
||||
.handler(new ResponseCollectorHandler(new CompletableFuture<>()))
|
||||
.open()
|
||||
.syncUninterruptibly()
|
||||
.getNow();
|
||||
|
||||
// Write an endStream=false header so the stream stays open
|
||||
final Http2Headers headers = new DefaultHttp2Headers()
|
||||
.method("POST")
|
||||
.path("/test")
|
||||
.scheme("https")
|
||||
.authority("localhost");
|
||||
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false)).syncUninterruptibly();
|
||||
|
||||
assertFalse(
|
||||
backendH2Connection.join().closeFuture().awaitUninterruptibly(10, TimeUnit.MILLISECONDS),
|
||||
"Channel should be open");
|
||||
|
||||
// All backend connections the omnibus opened on behalf of this client should close if we disconnect the client
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
assertTrue(backendH2Connection.join().closeFuture().await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void backpressure(final boolean localChannel) throws Exception {
|
||||
final AtomicReference<Channel> backendStreamChannel = new AtomicReference<>();
|
||||
final Channel backendServer = startBackendServer(localChannel, "backpressure", _ -> {
|
||||
}, ch -> {
|
||||
ch.config().setAutoRead(false);
|
||||
backendStreamChannel.set(ch);
|
||||
});
|
||||
final OmnibusH2Server omnibusH2Server = startOmnibusServer(backendServer);
|
||||
final Channel h2Connection = connectToOmnibus(omnibusH2Server, null);
|
||||
|
||||
// We'll take the client channel becoming unwritable as backpressure signal
|
||||
final AtomicBoolean isWritable = new AtomicBoolean(true);
|
||||
final CompletableFuture<Http2HeadersFrame> response = new CompletableFuture<>();
|
||||
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
|
||||
.handler(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelWritabilityChanged(ChannelHandlerContext ctx) {
|
||||
isWritable.set(ctx.channel().isWritable());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) {
|
||||
try {
|
||||
if (msg instanceof Http2HeadersFrame headers) {
|
||||
response.complete(headers);
|
||||
}
|
||||
} finally {
|
||||
ReferenceCountUtil.release(msg);
|
||||
}
|
||||
}
|
||||
})
|
||||
.open()
|
||||
.syncUninterruptibly()
|
||||
.getNow();
|
||||
|
||||
final Http2Headers headers = new DefaultHttp2Headers().method("POST").path("/test");
|
||||
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false)).syncUninterruptibly();
|
||||
|
||||
final long startNanos = System.nanoTime();
|
||||
final byte[] chunk = new byte[16384];
|
||||
do {
|
||||
// Write data until our own client hits the high watermark
|
||||
while (isWritable.get()) {
|
||||
// Try to wait until the write finishes but if it can't that's fine: we're trying to induce backpressure
|
||||
stream
|
||||
.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.wrappedBuffer(chunk), false))
|
||||
.awaitUninterruptibly(100, TimeUnit.MILLISECONDS);
|
||||
Thread.yield();
|
||||
}
|
||||
|
||||
// Make sure our channel is still unwritable for a bit since we haven't re-enabled auto-read yet. If we become
|
||||
// writable it means we are hitting a lower watermark somewhere earlier in the stack, so we can try writing some
|
||||
// more. Eventually all intermediate channels should flush and we should be stuck on the backend channel which
|
||||
// will never make progress (because auto-read is disabled)
|
||||
Thread.sleep(100);
|
||||
|
||||
assertTrue(Duration.ofNanos(System.nanoTime() - startNanos).compareTo(Duration.ofSeconds(10)) < 0,
|
||||
"Failed to persistently introduce backpressure after 5 seconds. client bytesBeforeUnwritable: "
|
||||
+ stream.bytesBeforeUnwritable() +
|
||||
" backend bytesBeforeUnwritable: " + backendStreamChannel.get().bytesBeforeUnwritable());
|
||||
} while (isWritable.get());
|
||||
stream.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.wrappedBuffer(chunk), true));
|
||||
|
||||
// Now re-enable reads on the backend, which should eventually unblock our writes
|
||||
backendStreamChannel.get().config().setAutoRead(true);
|
||||
// Now we should eventually be able to send the last (endStream=true) write and get a response
|
||||
assertEquals("200", response.get(5, TimeUnit.SECONDS).headers().status().toString());
|
||||
assertTrue(isWritable.get());
|
||||
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void idleTest(final boolean localChannel) throws Exception {
|
||||
final Duration timeout = Duration.ofMillis(500);
|
||||
final OmnibusH2Server timeoutServer =
|
||||
startOmnibusServer(Collections.emptyMap(), startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY), timeout);
|
||||
final Channel channel = connectToOmnibus(timeoutServer, null);
|
||||
|
||||
// Send a request to make sure idleTimeouts work even after a stream / backend connection has been established
|
||||
sendRequestThroughOmnibus(channel, "/a/different/path");
|
||||
|
||||
// The server should eventually close this idle connection
|
||||
assertTrue(channel.closeFuture().awaitUninterruptibly(timeout.toMillis() * 5, TimeUnit.MILLISECONDS));
|
||||
|
||||
timeoutServer.stop();
|
||||
}
|
||||
|
||||
/// Start an OmnibusH2Server. The returned server and provided backends will be torn down in [#tearDown()]
|
||||
///
|
||||
/// @param routes A map of prefixes and the corresponding backend server channels the omnibus will target
|
||||
/// @param defaultBackend The target backend if no prefix routes match the request path
|
||||
/// @param timeout The omnibus idle timeout
|
||||
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend, final Duration timeout) throws Exception {
|
||||
// self-signed TLS context for the frontend loaded from test keyStore
|
||||
final InputStream keyStore = OmnibusH2ServerTest.class.getResourceAsStream("omnibus-h2-server-test-keystore.p12");
|
||||
|
||||
backendChannelsToShutDown.addAll(routes.values());
|
||||
backendChannelsToShutDown.add(defaultBackend);
|
||||
|
||||
final OmnibusH2Server server = new OmnibusH2Server(
|
||||
SniMapper.buildSniMapping(keyStore, KEYSTORE_PASSWORD),
|
||||
nioEventLoopGroup,
|
||||
localEventLoopGroup,
|
||||
new InetSocketAddress("127.0.0.1", 0),
|
||||
new OmnibusRouter(
|
||||
routes.entrySet().stream().map(entry -> new OmnibusRouter.OmnibusRoute(entry.getKey(), entry.getValue().localAddress())).toList(),
|
||||
defaultBackend.localAddress()),
|
||||
timeout);
|
||||
server.start();
|
||||
omnibusH2ServersToShutDown.add(server);
|
||||
return server;
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(final Channel defaultBackend) throws Exception {
|
||||
return startOmnibusServer(Collections.emptyMap(), defaultBackend, Duration.ofMinutes(1));
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend) throws Exception {
|
||||
return startOmnibusServer(routes, defaultBackend, Duration.ofMinutes(1));
|
||||
}
|
||||
|
||||
/// Start a h2c server that can be used as a target of the omnibus
|
||||
///
|
||||
/// @param localChannel whether the omnibus should target this backend via a LocalChannel or an NioChannel
|
||||
/// @param identity how the backend should respond to identity requests
|
||||
/// @param h2ChannelInit a Consumer that will be called every time a new HTTP/2 connection is made to this server
|
||||
/// @param h2StreamInit a Consumer that will be called every time a new HTTP/2 stream is created on this server
|
||||
private Channel startBackendServer(final boolean localChannel, final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
|
||||
final EventLoopGroup eventLoopGroup = localChannel ? localEventLoopGroup : nioEventLoopGroup;
|
||||
return new ServerBootstrap()
|
||||
.group(eventLoopGroup, eventLoopGroup)
|
||||
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
h2ChannelInit.accept(ch);
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
h2StreamInit.accept(ch);
|
||||
ch.pipeline().addLast(new TestHandler(identity));
|
||||
}
|
||||
}));
|
||||
}
|
||||
})
|
||||
.bind(localChannel ? new LocalAddress(identity) : new InetSocketAddress("127.0.0.1", 0))
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
}
|
||||
|
||||
private Channel startBackendServer(final boolean localChannel, final String identity) {
|
||||
return startBackendServer(localChannel, identity, _ -> {}, _ -> {});
|
||||
}
|
||||
|
||||
/// Makes an H2 connection to the omnibus at [this#server] on which new H2 streams can be opened
|
||||
private Channel connectToOmnibus(final OmnibusH2Server server, @Nullable final HAProxyMessage proxyHeader) {
|
||||
final SslContext clientSsl;
|
||||
try {
|
||||
clientSsl = SslContextBuilder.forClient()
|
||||
.trustManager(InsecureTrustManagerFactory.INSTANCE)
|
||||
.applicationProtocolConfig(new ApplicationProtocolConfig(
|
||||
ApplicationProtocolConfig.Protocol.ALPN,
|
||||
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
|
||||
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
|
||||
ApplicationProtocolNames.HTTP_2))
|
||||
.build();
|
||||
} catch (SSLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
final Bootstrap clientBootstrap = new Bootstrap()
|
||||
.group(nioEventLoopGroup)
|
||||
.channel(NioSocketChannel.class)
|
||||
// Limit size of kernel TCP buffers to make it easier to hit backpressure in tests
|
||||
.option(NioChannelOption.SO_RCVBUF, 8192)
|
||||
.option(NioChannelOption.SO_SNDBUF, 8192)
|
||||
.handler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final SocketChannel ch) {
|
||||
ch.pipeline().addLast(HAProxyMessageEncoder.INSTANCE);
|
||||
}
|
||||
});
|
||||
final Channel ch = clientBootstrap.connect(server.getLocalAddress())
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
if (proxyHeader != null) {
|
||||
ch.writeAndFlush(proxyHeader).syncUninterruptibly();
|
||||
}
|
||||
ch.pipeline().remove(HAProxyMessageEncoder.INSTANCE);
|
||||
ch.pipeline().addLast(clientSsl.newHandler(ch.alloc(), server.getLocalAddress().getHostName(), server.getLocalAddress().getPort()));
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forClient()
|
||||
.initialSettings(Http2Settings.defaultSettings())
|
||||
.build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
|
||||
return ch;
|
||||
}
|
||||
|
||||
private Channel connectToOmnibus(final OmnibusH2Server server) {
|
||||
return connectToOmnibus(server, null);
|
||||
}
|
||||
|
||||
private String sendRequestThroughOmnibus(final Channel h2Connection, final String path) {
|
||||
final CompletableFuture<String> responseFuture = new CompletableFuture<>();
|
||||
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
|
||||
final Http2StreamChannel stream = streamBootstrap
|
||||
.handler(new ResponseCollectorHandler(responseFuture))
|
||||
.open()
|
||||
.syncUninterruptibly()
|
||||
.getNow();
|
||||
|
||||
final Http2Headers headers = new DefaultHttp2Headers()
|
||||
.method("POST")
|
||||
.path(path)
|
||||
.scheme("https")
|
||||
.authority("localhost");
|
||||
|
||||
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, true));
|
||||
|
||||
return responseFuture.join();
|
||||
}
|
||||
|
||||
/// A backend that either echos the request body, returns an identity, or disconnects based on the request
|
||||
private static class TestHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
// Returned if request has no body
|
||||
private final String identity;
|
||||
private final ByteBuf accumulated = Unpooled.buffer();
|
||||
|
||||
private TestHandler(final String identity) {
|
||||
this.identity = identity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
|
||||
if (msg instanceof Http2HeadersFrame headers) {
|
||||
final String path = headers.headers().path().toString();
|
||||
if (path.contains("reset")) {
|
||||
ctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.NO_ERROR))
|
||||
.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
|
||||
} else if (path.contains("goaway")) {
|
||||
ctx.channel().parent()
|
||||
.writeAndFlush(new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
} else if (path.contains("forwarded-for")) {
|
||||
final String xForwardedFor = Optional
|
||||
.ofNullable(headers.headers().get("x-forwarded-for"))
|
||||
.map(CharSequence::toString)
|
||||
.orElse("");
|
||||
writeResponse(ctx, Unpooled.copiedBuffer(xForwardedFor, StandardCharsets.UTF_8));
|
||||
} else if (headers.isEndStream()) {
|
||||
writeResponse(ctx, Unpooled.copiedBuffer(identity, StandardCharsets.UTF_8));
|
||||
}
|
||||
} else if (msg instanceof Http2DataFrame dataFrame) {
|
||||
accumulated.writeBytes(dataFrame.content());
|
||||
if (dataFrame.isEndStream()) {
|
||||
writeResponse(ctx, accumulated);
|
||||
}
|
||||
}
|
||||
ReferenceCountUtil.release(msg);
|
||||
}
|
||||
|
||||
private void writeResponse(final ChannelHandlerContext ctx, final ByteBuf body) {
|
||||
final Http2Headers responseHeaders = new DefaultHttp2Headers().status("200");
|
||||
ctx.write(new DefaultHttp2HeadersFrame(responseHeaders, false));
|
||||
ctx.writeAndFlush(new DefaultHttp2DataFrame(body, true));
|
||||
}
|
||||
}
|
||||
|
||||
/// Completes the provided future with the first [Http2DataFrame] received
|
||||
private static class ResponseCollectorHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final CompletableFuture<String> responseFuture;
|
||||
|
||||
ResponseCollectorHandler(final CompletableFuture<String> responseFuture) {
|
||||
this.responseFuture = responseFuture;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
|
||||
if (msg instanceof Http2DataFrame dataFrame) {
|
||||
responseFuture.complete(dataFrame.content().toString(StandardCharsets.UTF_8));
|
||||
}
|
||||
ReferenceCountUtil.release(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
|
||||
responseFuture.completeExceptionally(cause);
|
||||
}
|
||||
}
|
||||
|
||||
/// Completes the provided future with the first [Http2HeadersFrame] received
|
||||
private static class HeadersCollectorHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final CompletableFuture<Http2HeadersFrame> responseFuture;
|
||||
|
||||
HeadersCollectorHandler(final CompletableFuture<Http2HeadersFrame> responseFuture) {
|
||||
this.responseFuture = responseFuture;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
|
||||
if (msg instanceof Http2HeadersFrame headers) {
|
||||
responseFuture.complete(headers);
|
||||
}
|
||||
ReferenceCountUtil.release(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
|
||||
responseFuture.completeExceptionally(cause);
|
||||
}
|
||||
}
|
||||
|
||||
/// Completes the provided future when an RST frame is received or errors if we don't get one
|
||||
private static class RstCollectorHandler extends SimpleUserEventChannelHandler<Http2ResetFrame> {
|
||||
|
||||
private final CompletableFuture<Http2ResetFrame> resetFuture;
|
||||
|
||||
private RstCollectorHandler(final CompletableFuture<Http2ResetFrame> resetFuture) {
|
||||
this.resetFuture = resetFuture;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void eventReceived(final ChannelHandlerContext ctx, final Http2ResetFrame evt) {
|
||||
resetFuture.complete(evt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelInactive(final ChannelHandlerContext ctx) {
|
||||
if (!resetFuture.isDone()) {
|
||||
resetFuture.completeExceptionally(new IllegalStateException("Channel went inactive without RST"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import io.netty.handler.codec.haproxy.HAProxyCommand;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessage;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessageEncoder;
|
||||
import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
|
||||
import io.netty.handler.codec.haproxy.HAProxyProxiedProtocol;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.test.LeakPresenceExtension;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
|
||||
@ExtendWith(LeakPresenceExtension.class)
|
||||
class ProxyProtocolHandlerTest {
|
||||
|
||||
private static final HAProxyProtocolVersion PROTOCOL_VERSION = HAProxyProtocolVersion.V2;
|
||||
private static final String SOURCE_ADDRESS = "10.0.0.1";
|
||||
private static final String DESTINATION_ADDRESS = "10.0.0.2";
|
||||
|
||||
private static HAProxyMessage proxyMessage() {
|
||||
return new HAProxyMessage(
|
||||
PROTOCOL_VERSION, HAProxyCommand.PROXY,
|
||||
HAProxyProxiedProtocol.TCP4, SOURCE_ADDRESS, DESTINATION_ADDRESS, 1234, 5678);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendHeader() {
|
||||
final HAProxyMessage proxyMessage = proxyMessage();
|
||||
final EmbeddedChannel encoder = new EmbeddedChannel(HAProxyMessageEncoder.INSTANCE);
|
||||
encoder.writeOutbound(proxyMessage);
|
||||
final ByteBuf ppv2Bytes = encoder.readOutbound();
|
||||
|
||||
final EmbeddedChannel ch = new EmbeddedChannel(new ProxyProtocolHandler());
|
||||
ch.writeInbound(ppv2Bytes);
|
||||
final HAProxyMessage actual = ch.readInbound();
|
||||
try {
|
||||
assertEquals(PROTOCOL_VERSION, actual.protocolVersion());
|
||||
assertEquals(SOURCE_ADDRESS, actual.sourceAddress());
|
||||
} finally {
|
||||
ReferenceCountUtil.release(actual);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendHeaderSlowly() {
|
||||
final HAProxyMessage proxyMessage = proxyMessage();
|
||||
final EmbeddedChannel encoder = new EmbeddedChannel(HAProxyMessageEncoder.INSTANCE);
|
||||
encoder.writeOutbound(proxyMessage);
|
||||
|
||||
final EmbeddedChannel ch = new EmbeddedChannel(new ProxyProtocolHandler());
|
||||
final ByteBuf ppv2Bytes = encoder.readOutbound();
|
||||
try {
|
||||
while (ppv2Bytes.isReadable()) {
|
||||
assertNull(ch.readInbound());
|
||||
ch.writeInbound(ppv2Bytes.readBytes(1));
|
||||
}
|
||||
} finally {
|
||||
ReferenceCountUtil.release(ppv2Bytes);
|
||||
}
|
||||
|
||||
final HAProxyMessage actual = ch.readInbound();
|
||||
try {
|
||||
assertEquals(PROTOCOL_VERSION, actual.protocolVersion());
|
||||
assertEquals(SOURCE_ADDRESS, actual.sourceAddress());
|
||||
} finally {
|
||||
ReferenceCountUtil.release(actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user