mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:16:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95e83c52fa | ||
|
|
be377dcda8 | ||
|
|
88a68e883e | ||
|
|
2ad5d33251 | ||
|
|
4e5dd914dd | ||
|
|
2adf1e5017 | ||
|
|
55ca4e93c4 | ||
|
|
d1d03f45c5 | ||
|
|
436bd891bd | ||
|
|
a7c28fe5ed | ||
|
|
60814d1ff0 | ||
|
|
d018efe2a5 | ||
|
|
6fd0cba06a | ||
|
|
86f9322036 | ||
|
|
12c6af23ee | ||
|
|
69330f47fd | ||
|
|
4f40c128bf | ||
|
|
30b5ad1515 | ||
|
|
665a26d164 | ||
|
|
a5774bf6ff | ||
|
|
d2716fe5cf | ||
|
|
279f877bf2 | ||
|
|
d51e6a43e7 | ||
|
|
6a96756c87 | ||
|
|
df69d9f195 | ||
|
|
26ffa19f36 | ||
|
|
29ef3f0b41 | ||
|
|
106d5e54c7 | ||
|
|
6ac2460eb0 | ||
|
|
79c030b138 | ||
|
|
c8d649e8c2 | ||
|
|
1fdf82dd6c | ||
|
|
4aa4246695 | ||
|
|
1bebceb29c | ||
|
|
a2139ee236 | ||
|
|
8c55f39cdf | ||
|
|
0329184c94 | ||
|
|
cd64390141 | ||
|
|
3e12a8780d | ||
|
|
11e6ff1bbe | ||
|
|
36f85fc97e | ||
|
|
9040cfd200 | ||
|
|
757da3b15a | ||
|
|
d162590a32 | ||
|
|
f41e1716c6 | ||
|
|
4dce0f1b9d |
No files matched your search
@@ -286,6 +286,11 @@
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.39.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal.forks</groupId>
|
||||
<artifactId>noise-java</artifactId>
|
||||
<version>0.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-bom</artifactId>
|
||||
@@ -323,16 +328,6 @@
|
||||
<artifactId>wiremock-standalone</artifactId>
|
||||
<version>3.3.1</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
|
||||
@@ -40,8 +40,6 @@ metrics:
|
||||
- ^lettuce\..+$
|
||||
reportOnStop: true
|
||||
|
||||
grpcPort: 8080
|
||||
|
||||
tlsKeyStore:
|
||||
password: secret://tlsKeyStore.password
|
||||
|
||||
|
||||
+13
-22
@@ -21,13 +21,6 @@
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-jaxrs2</artifactId>
|
||||
<version>${swagger.version}</version>
|
||||
<exclusions>
|
||||
<!-- org.yaml:snakeyaml is causing a dependency convergence error -->
|
||||
<exclusion>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
@@ -52,6 +45,11 @@
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.signal.forks</groupId>
|
||||
<artifactId>noise-java</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
<artifactId>dropwizard-core</artifactId>
|
||||
@@ -207,7 +205,7 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
<version>1.24.0</version>
|
||||
<version>1.26.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -242,8 +240,7 @@
|
||||
|
||||
<dependency>
|
||||
<groupId>io.grpc</groupId>
|
||||
<artifactId>grpc-netty-shaded</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<artifactId>grpc-netty</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.grpc</groupId>
|
||||
@@ -334,12 +331,6 @@
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>dynamodb-lock-client</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -385,17 +376,17 @@
|
||||
<groupId>org.glassfish.jersey.test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-core</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
||||
@@ -298,11 +298,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private TusConfiguration tus;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private int grpcPort;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -539,10 +534,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return tus;
|
||||
}
|
||||
|
||||
public int getGrpcPort() {
|
||||
return grpcPort;
|
||||
}
|
||||
|
||||
public ClientReleaseConfiguration getClientReleaseConfiguration() {
|
||||
return clientRelease;
|
||||
}
|
||||
|
||||
@@ -21,13 +21,13 @@ import io.dropwizard.core.setup.Bootstrap;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.jetty.HttpsConnectorFactory;
|
||||
import io.grpc.ServerBuilder;
|
||||
import io.grpc.ServerInterceptors;
|
||||
import io.lettuce.core.metrics.MicrometerCommandLatencyRecorder;
|
||||
import io.lettuce.core.metrics.MicrometerOptions;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.grpc.MetricCollectingServerInterceptor;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -134,13 +134,14 @@ import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcServerManagedWrapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.UserAgentInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedDefaultEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedLocalGrpcServer;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
@@ -180,14 +181,13 @@ import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.PushChallengeConfigProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThresholdProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.SenderOverrideProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamFilter;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountPrincipalSupplier;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
@@ -752,20 +752,67 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final BasicCredentialAuthenticationInterceptor basicCredentialAuthenticationInterceptor =
|
||||
new BasicCredentialAuthenticationInterceptor(new AccountAuthenticator(accountsManager));
|
||||
|
||||
final ServerBuilder<?> grpcServer = ServerBuilder.forPort(config.getGrpcPort())
|
||||
.addService(ServerInterceptors.intercept(new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager), basicCredentialAuthenticationInterceptor))
|
||||
.addService(new AccountsAnonymousGrpcService(accountsManager, rateLimiters))
|
||||
.addService(ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters))
|
||||
.addService(ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
|
||||
.addService(ServerInterceptors.intercept(new KeysGrpcService(accountsManager, keysManager, rateLimiters), basicCredentialAuthenticationInterceptor))
|
||||
.addService(new KeysAnonymousGrpcService(accountsManager, keysManager))
|
||||
.addService(new PaymentsGrpcService(currencyManager))
|
||||
.addService(ServerInterceptors.intercept(new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
config.getBadges(), asyncCdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters, zkProfileOperations, config.getCdnConfiguration().bucket()), basicCredentialAuthenticationInterceptor))
|
||||
.addService(new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkProfileOperations));
|
||||
final ManagedDefaultEventLoopGroup localEventLoopGroup = new ManagedDefaultEventLoopGroup();
|
||||
|
||||
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
final MetricCollectingServerInterceptor metricCollectingServerInterceptor =
|
||||
new MetricCollectingServerInterceptor(Metrics.globalRegistry);
|
||||
|
||||
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
|
||||
final AcceptLanguageInterceptor acceptLanguageInterceptor = new AcceptLanguageInterceptor();
|
||||
final UserAgentInterceptor userAgentInterceptor = new UserAgentInterceptor();
|
||||
|
||||
final LocalAddress anonymousGrpcServerAddress = new LocalAddress("grpc-anonymous");
|
||||
final LocalAddress authenticatedGrpcServerAddress = new LocalAddress("grpc-authenticated");
|
||||
|
||||
final ManagedLocalGrpcServer anonymousGrpcServer = new ManagedLocalGrpcServer(anonymousGrpcServerAddress, localEventLoopGroup) {
|
||||
@Override
|
||||
protected void configureServer(final ServerBuilder<?> serverBuilder) {
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
|
||||
serverBuilder
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(metricCollectingServerInterceptor)
|
||||
.intercept(errorMappingInterceptor)
|
||||
.intercept(acceptLanguageInterceptor)
|
||||
.intercept(remoteDeprecationFilter)
|
||||
.intercept(userAgentInterceptor)
|
||||
.addService(new AccountsAnonymousGrpcService(accountsManager, rateLimiters))
|
||||
.addService(new KeysAnonymousGrpcService(accountsManager, keysManager))
|
||||
.addService(new PaymentsGrpcService(currencyManager))
|
||||
.addService(ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
|
||||
.addService(new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkProfileOperations));
|
||||
}
|
||||
};
|
||||
|
||||
final ManagedLocalGrpcServer authenticatedGrpcServer = new ManagedLocalGrpcServer(authenticatedGrpcServerAddress, localEventLoopGroup) {
|
||||
@Override
|
||||
protected void configureServer(final ServerBuilder<?> serverBuilder) {
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
|
||||
serverBuilder
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(metricCollectingServerInterceptor)
|
||||
.intercept(errorMappingInterceptor)
|
||||
.intercept(acceptLanguageInterceptor)
|
||||
.intercept(remoteDeprecationFilter)
|
||||
.intercept(userAgentInterceptor)
|
||||
.intercept(new BasicCredentialAuthenticationInterceptor(new AccountAuthenticator(accountsManager)))
|
||||
.addService(new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager))
|
||||
.addService(ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters))
|
||||
.addService(new KeysGrpcService(accountsManager, keysManager, rateLimiters))
|
||||
.addService(new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
config.getBadges(), asyncCdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters, zkProfileOperations, config.getCdnConfiguration().bucket()));
|
||||
}
|
||||
};
|
||||
|
||||
environment.lifecycle().manage(localEventLoopGroup);
|
||||
environment.lifecycle().manage(anonymousGrpcServer);
|
||||
environment.lifecycle().manage(authenticatedGrpcServer);
|
||||
|
||||
final List<Filter> filters = new ArrayList<>();
|
||||
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
filters.add(remoteDeprecationFilter);
|
||||
filters.add(new RemoteAddressFilter(useRemoteAddress));
|
||||
|
||||
@@ -775,19 +822,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
|
||||
}
|
||||
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
|
||||
grpcServer
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(new MetricCollectingServerInterceptor(Metrics.globalRegistry))
|
||||
.intercept(new ErrorMappingInterceptor())
|
||||
.intercept(new AcceptLanguageInterceptor())
|
||||
.intercept(remoteDeprecationFilter)
|
||||
.intercept(new UserAgentInterceptor());
|
||||
|
||||
environment.lifecycle().manage(new GrpcServerManagedWrapper(grpcServer.build()));
|
||||
|
||||
final AuthFilter<BasicCredentials, AuthenticatedAccount> accountAuthFilter =
|
||||
new BasicCredentialAuthFilter.Builder<AuthenticatedAccount>()
|
||||
.setAuthenticator(accountAuthenticator)
|
||||
@@ -803,7 +837,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new MetricsApplicationEventListener(TrafficSource.HTTP, clientReleaseManager));
|
||||
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
|
||||
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthenticatedAccount.class));
|
||||
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
@@ -813,7 +846,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment = new WebSocketEnvironment<>(environment,
|
||||
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
|
||||
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider("managed-async-websocket-virtual-thread-"));
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator, new AccountPrincipalSupplier(accountsManager)));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(receiptSender, messagesManager, pushNotificationManager,
|
||||
clientPresenceManager, websocketScheduledExecutor, messageDeliveryScheduler, clientReleaseManager));
|
||||
@@ -827,7 +860,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
.map(ServiceLoader.Provider::get)
|
||||
.filter(s -> s.getClass().isAnnotationPresent(FilterSpam.class))
|
||||
.flatMap(filter -> {
|
||||
try {
|
||||
filter.configure(config.getSpamFilterConfiguration().getEnvironment());
|
||||
@@ -857,6 +889,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
log.warn("No spam-checkers found; using default (no-op) provider as a default");
|
||||
return SpamChecker.noop();
|
||||
});
|
||||
final ChallengeConstraintChecker challengeConstraintChecker = spamFilter
|
||||
.map(SpamFilter::getChallengeConstraintChecker)
|
||||
.orElseGet(() -> {
|
||||
log.warn("No challenge-constraint-checkers found; using default (no-op) provider as a default");
|
||||
return ChallengeConstraintChecker.noop();
|
||||
});
|
||||
final RegistrationFraudChecker registrationFraudChecker = spamFilter
|
||||
.map(SpamFilter::getRegistrationFraudChecker)
|
||||
.orElseGet(() -> {
|
||||
log.warn("No registration-fraud-checkers found; using default (no-op) provider as a default");
|
||||
return RegistrationFraudChecker.noop();
|
||||
});
|
||||
|
||||
|
||||
spamFilter.map(SpamFilter::getReportedMessageListener).ifPresent(reportMessageManager::addListener);
|
||||
|
||||
final RateLimitChallengeManager rateLimitChallengeManager = new RateLimitChallengeManager(pushChallengeManager,
|
||||
@@ -864,9 +910,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
spamFilter.ifPresent(filter -> {
|
||||
environment.lifecycle().manage(filter);
|
||||
environment.jersey().register(filter);
|
||||
webSocketEnvironment.jersey().register(filter);
|
||||
|
||||
log.info("Registered spam filter: {}", filter.getClass().getName());
|
||||
});
|
||||
|
||||
@@ -888,7 +931,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
|
||||
zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new ChallengeController(rateLimitChallengeManager),
|
||||
new ChallengeController(rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(config.getLinkDeviceSecretConfiguration().secret().value(), accountsManager,
|
||||
rateLimiters, rateLimitersCluster, config.getMaxDevices(), clock),
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
@@ -915,7 +958,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdnConfiguration().bucket()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters,
|
||||
accountsManager, dynamicConfigurationManager, clock)
|
||||
accountsManager, registrationFraudChecker, dynamicConfigurationManager, clock)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
@@ -937,7 +980,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
registerCorsFilter(environment);
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
registerProviders(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
|
||||
environment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
webSocketEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
@@ -963,26 +1005,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.admin().addTask(new SetRequestLoggingEnabledTask());
|
||||
|
||||
// healthcheck, admin port
|
||||
environment.healthChecks().register("cacheCluster", new RedisClusterHealthCheck(cacheCluster));
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
}
|
||||
|
||||
|
||||
private void registerProviders(Environment environment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment) {
|
||||
List.of(
|
||||
ScoreThresholdProvider.ScoreThresholdFeature.class,
|
||||
SenderOverrideProvider.SenderOverrideFeature.class,
|
||||
PushChallengeConfigProvider.PushChallengeConfigFeature.class)
|
||||
.forEach(feature -> {
|
||||
environment.jersey().register(feature);
|
||||
webSocketEnvironment.jersey().register(feature);
|
||||
provisioningEnvironment.jersey().register(feature);
|
||||
});
|
||||
}
|
||||
|
||||
private void registerExceptionMappers(Environment environment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment,
|
||||
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment) {
|
||||
|
||||
+1
-3
@@ -21,7 +21,6 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RefreshingAccountAndDeviceSupplier;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -108,8 +107,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
|
||||
device.get(),
|
||||
SaltedTokenHash.generateFor(basicCredentials.getPassword())); // new credentials have current version
|
||||
}
|
||||
return Optional.of(new AuthenticatedAccount(
|
||||
new RefreshingAccountAndDeviceSupplier(authenticatedAccount, device.get().getId(), accountsManager)));
|
||||
return Optional.of(new AuthenticatedAccount(authenticatedAccount, device.get()));
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
|
||||
+26
-25
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -45,10 +44,6 @@ public class AuthEnablementRefreshRequirementProvider implements WebsocketRefres
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Map<Byte, Boolean> buildDevicesEnabledMap(final Account account) {
|
||||
return account.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::isEnabled));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleRequestFiltered(final RequestEvent requestEvent) {
|
||||
@@ -60,10 +55,13 @@ public class AuthEnablementRefreshRequirementProvider implements WebsocketRefres
|
||||
setAccount(requestEvent.getContainerRequest(), account));
|
||||
}
|
||||
}
|
||||
|
||||
public static void setAccount(final ContainerRequest containerRequest, final Account account) {
|
||||
containerRequest.setProperty(ACCOUNT_UUID, account.getUuid());
|
||||
containerRequest.setProperty(DEVICES_ENABLED, buildDevicesEnabledMap(account));
|
||||
setAccount(containerRequest, ContainerRequestUtil.AccountInfo.fromAccount(account));
|
||||
}
|
||||
|
||||
private static void setAccount(final ContainerRequest containerRequest, final ContainerRequestUtil.AccountInfo info) {
|
||||
containerRequest.setProperty(ACCOUNT_UUID, info.accountId());
|
||||
containerRequest.setProperty(DEVICES_ENABLED, info.devicesEnabled());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -75,25 +73,28 @@ public class AuthEnablementRefreshRequirementProvider implements WebsocketRefres
|
||||
@SuppressWarnings("unchecked") final Map<Byte, Boolean> initialDevicesEnabled =
|
||||
(Map<Byte, Boolean>) requestEvent.getContainerRequest().getProperty(DEVICES_ENABLED);
|
||||
|
||||
return accountsManager.getByAccountIdentifier((UUID) requestEvent.getContainerRequest().getProperty(ACCOUNT_UUID)).map(account -> {
|
||||
final Set<Byte> deviceIdsToDisplace;
|
||||
final Map<Byte, Boolean> currentDevicesEnabled = buildDevicesEnabledMap(account);
|
||||
return accountsManager.getByAccountIdentifier((UUID) requestEvent.getContainerRequest().getProperty(ACCOUNT_UUID))
|
||||
.map(ContainerRequestUtil.AccountInfo::fromAccount)
|
||||
.map(account -> {
|
||||
final Set<Byte> deviceIdsToDisplace;
|
||||
final Map<Byte, Boolean> currentDevicesEnabled = account.devicesEnabled();
|
||||
|
||||
if (!initialDevicesEnabled.equals(currentDevicesEnabled)) {
|
||||
deviceIdsToDisplace = new HashSet<>(initialDevicesEnabled.keySet());
|
||||
deviceIdsToDisplace.addAll(currentDevicesEnabled.keySet());
|
||||
} else {
|
||||
deviceIdsToDisplace = Collections.emptySet();
|
||||
}
|
||||
if (!initialDevicesEnabled.equals(currentDevicesEnabled)) {
|
||||
deviceIdsToDisplace = new HashSet<>(initialDevicesEnabled.keySet());
|
||||
deviceIdsToDisplace.addAll(currentDevicesEnabled.keySet());
|
||||
} else {
|
||||
deviceIdsToDisplace = Collections.emptySet();
|
||||
}
|
||||
|
||||
return deviceIdsToDisplace.stream()
|
||||
.map(deviceId -> new Pair<>(account.getUuid(), deviceId))
|
||||
.collect(Collectors.toList());
|
||||
}).orElseGet(() -> {
|
||||
logger.error("Request had account, but it is no longer present");
|
||||
return Collections.emptyList();
|
||||
});
|
||||
} else
|
||||
return deviceIdsToDisplace.stream()
|
||||
.map(deviceId -> new Pair<>(account.accountId(), deviceId))
|
||||
.collect(Collectors.toList());
|
||||
}).orElseGet(() -> {
|
||||
logger.error("Request had account, but it is no longer present");
|
||||
return Collections.emptyList();
|
||||
});
|
||||
} else {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -10,24 +10,24 @@ import java.util.function.Supplier;
|
||||
import javax.security.auth.Subject;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
public class AuthenticatedAccount implements Principal, AccountAndAuthenticatedDeviceHolder {
|
||||
private final Account account;
|
||||
private final Device device;
|
||||
|
||||
private final Supplier<Pair<Account, Device>> accountAndDevice;
|
||||
|
||||
public AuthenticatedAccount(final Supplier<Pair<Account, Device>> accountAndDevice) {
|
||||
this.accountAndDevice = accountAndDevice;
|
||||
public AuthenticatedAccount(final Account account, final Device device) {
|
||||
this.account = account;
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Account getAccount() {
|
||||
return accountAndDevice.get().first();
|
||||
return account;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getAuthenticatedDevice() {
|
||||
return accountAndDevice.get().second();
|
||||
return device;
|
||||
}
|
||||
|
||||
// Principal implementation
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Indicates that an endpoint changes the phone number and PNI keys associated with an account, and that
|
||||
* any websockets associated with the account may need to be refreshed after a call to that endpoint.
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ChangesPhoneNumber {
|
||||
}
|
||||
+30
-3
@@ -7,15 +7,42 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import javax.ws.rs.core.SecurityContext;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class ContainerRequestUtil {
|
||||
|
||||
static Optional<Account> getAuthenticatedAccount(final ContainerRequest request) {
|
||||
private static Map<Byte, Boolean> buildDevicesEnabledMap(final Account account) {
|
||||
return account.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::isEnabled));
|
||||
}
|
||||
|
||||
/**
|
||||
* A read-only subset of the authenticated Account object, to enforce that filter-based consumers do not perform
|
||||
* account modifying operations.
|
||||
*/
|
||||
record AccountInfo(UUID accountId, String e164, Map<Byte, Boolean> devicesEnabled) {
|
||||
|
||||
static AccountInfo fromAccount(final Account account) {
|
||||
return new AccountInfo(
|
||||
account.getUuid(),
|
||||
account.getNumber(),
|
||||
buildDevicesEnabledMap(account));
|
||||
}
|
||||
}
|
||||
|
||||
static Optional<AccountInfo> getAuthenticatedAccount(final ContainerRequest request) {
|
||||
return Optional.ofNullable(request.getSecurityContext())
|
||||
.map(SecurityContext::getUserPrincipal)
|
||||
.map(principal -> principal instanceof AccountAndAuthenticatedDeviceHolder
|
||||
? ((AccountAndAuthenticatedDeviceHolder) principal).getAccount() : null);
|
||||
.map(principal -> {
|
||||
if (principal instanceof AccountAndAuthenticatedDeviceHolder aaadh) {
|
||||
return aaadh.getAccount();
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.map(AccountInfo::fromAccount);
|
||||
}
|
||||
}
|
||||
+24
-14
@@ -7,40 +7,50 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
public class PhoneNumberChangeRefreshRequirementProvider implements WebsocketRefreshRequirementProvider {
|
||||
|
||||
private static final String ACCOUNT_UUID =
|
||||
PhoneNumberChangeRefreshRequirementProvider.class.getName() + ".accountUuid";
|
||||
|
||||
private static final String INITIAL_NUMBER_KEY =
|
||||
PhoneNumberChangeRefreshRequirementProvider.class.getName() + ".initialNumber";
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
public PhoneNumberChangeRefreshRequirementProvider(final AccountsManager accountsManager) {
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleRequestFiltered(final RequestEvent requestEvent) {
|
||||
if (requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod()
|
||||
.getAnnotation(ChangesPhoneNumber.class) == null) {
|
||||
return;
|
||||
}
|
||||
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest())
|
||||
.ifPresent(account -> requestEvent.getContainerRequest().setProperty(INITIAL_NUMBER_KEY, account.getNumber()));
|
||||
.ifPresent(account -> {
|
||||
requestEvent.getContainerRequest().setProperty(INITIAL_NUMBER_KEY, account.e164());
|
||||
requestEvent.getContainerRequest().setProperty(ACCOUNT_UUID, account.accountId());
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Pair<UUID, Byte>> handleRequestFinished(final RequestEvent requestEvent) {
|
||||
final String initialNumber = (String) requestEvent.getContainerRequest().getProperty(INITIAL_NUMBER_KEY);
|
||||
|
||||
if (initialNumber != null) {
|
||||
final Optional<Account> maybeAuthenticatedAccount =
|
||||
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest());
|
||||
|
||||
return maybeAuthenticatedAccount
|
||||
.filter(account -> !initialNumber.equals(account.getNumber()))
|
||||
.map(account -> account.getDevices().stream()
|
||||
.map(device -> new Pair<>(account.getUuid(), device.getId()))
|
||||
.collect(Collectors.toList()))
|
||||
.orElse(Collections.emptyList());
|
||||
} else {
|
||||
if (initialNumber == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return accountsManager.getByAccountIdentifier((UUID) requestEvent.getContainerRequest().getProperty(ACCOUNT_UUID))
|
||||
.filter(account -> !initialNumber.equals(account.getNumber()))
|
||||
.map(account -> account.getDevices().stream()
|
||||
.map(device -> new Pair<>(account.getUuid(), device.getId()))
|
||||
.collect(Collectors.toList()))
|
||||
.orElse(Collections.emptyList());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -24,7 +24,7 @@ public class WebsocketRefreshApplicationEventListener implements ApplicationEven
|
||||
|
||||
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(clientPresenceManager,
|
||||
new AuthEnablementRefreshRequirementProvider(accountsManager),
|
||||
new PhoneNumberChangeRefreshRequirementProvider());
|
||||
new PhoneNumberChangeRefreshRequirementProvider(accountsManager));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+5
-1
@@ -134,7 +134,11 @@ public class TurnCallRouter {
|
||||
ipv4Selection = ipv4Selection.stream().limit(limit - ipv6Selection.size()).toList();
|
||||
}
|
||||
|
||||
return Stream.concat(ipv4Selection.stream(), ipv6Selection.stream()).map(InetAddress::getHostAddress).toList();
|
||||
return Stream.concat(
|
||||
ipv4Selection.stream().map(InetAddress::getHostAddress),
|
||||
// map ipv6 to RFC3986 format i.e. surrounded by brackets
|
||||
ipv6Selection.stream().map(i -> String.format("[%s]", i.getHostAddress()))
|
||||
).toList();
|
||||
}
|
||||
|
||||
private static List<String> getUrlsForInstances(List<String> instanceIps) {
|
||||
|
||||
+22
-20
@@ -65,6 +65,8 @@ import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/accounts")
|
||||
@@ -97,7 +99,7 @@ public class AccountController {
|
||||
@GET
|
||||
@Path("/turn/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public TurnToken getTurnToken(@Auth AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
public TurnToken getTurnToken(@ReadOnly @Auth AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
rateLimiters.getTurnLimiter().validate(auth.getAccount().getUuid());
|
||||
return turnTokenGenerator.generate(auth.getAccount().getUuid());
|
||||
}
|
||||
@@ -107,7 +109,7 @@ public class AccountController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ChangesDeviceEnabledState
|
||||
public void setGcmRegistrationId(@Auth AuthenticatedAccount auth,
|
||||
public void setGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
|
||||
@NotNull @Valid GcmRegistrationId registrationId) {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
@@ -128,7 +130,7 @@ public class AccountController {
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
@ChangesDeviceEnabledState
|
||||
public void deleteGcmRegistrationId(@Auth AuthenticatedAccount auth) {
|
||||
public void deleteGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
|
||||
Account account = auth.getAccount();
|
||||
Device device = auth.getAuthenticatedDevice();
|
||||
|
||||
@@ -144,7 +146,7 @@ public class AccountController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ChangesDeviceEnabledState
|
||||
public void setApnRegistrationId(@Auth AuthenticatedAccount auth,
|
||||
public void setApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
|
||||
@NotNull @Valid ApnRegistrationId registrationId) {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
@@ -167,7 +169,7 @@ public class AccountController {
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
@ChangesDeviceEnabledState
|
||||
public void deleteApnRegistrationId(@Auth AuthenticatedAccount auth) {
|
||||
public void deleteApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
|
||||
Account account = auth.getAccount();
|
||||
Device device = auth.getAuthenticatedDevice();
|
||||
|
||||
@@ -186,7 +188,7 @@ public class AccountController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
public void setRegistrationLock(@Auth AuthenticatedAccount auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
public void setRegistrationLock(@Mutable @Auth AuthenticatedAccount auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.getRegistrationLock());
|
||||
|
||||
accounts.update(auth.getAccount(),
|
||||
@@ -195,13 +197,13 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/registration_lock")
|
||||
public void removeRegistrationLock(@Auth AuthenticatedAccount auth) {
|
||||
public void removeRegistrationLock(@Mutable @Auth AuthenticatedAccount auth) {
|
||||
accounts.update(auth.getAccount(), a -> a.setRegistrationLock(null, null));
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/name/")
|
||||
public void setName(@Auth AuthenticatedAccount auth, @NotNull @Valid DeviceName deviceName) {
|
||||
public void setName(@Mutable @Auth AuthenticatedAccount auth, @NotNull @Valid DeviceName deviceName) {
|
||||
Account account = auth.getAccount();
|
||||
Device device = auth.getAuthenticatedDevice();
|
||||
accounts.updateDevice(account, device.getId(), d -> d.setName(deviceName.getDeviceName()));
|
||||
@@ -213,7 +215,7 @@ public class AccountController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ChangesDeviceEnabledState
|
||||
public void setAccountAttributes(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@Mutable @Auth AuthenticatedAccount auth,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String userAgent,
|
||||
@NotNull @Valid AccountAttributes attributes) {
|
||||
final Account account = auth.getAccount();
|
||||
@@ -243,14 +245,14 @@ public class AccountController {
|
||||
@Path("/me")
|
||||
@Deprecated() // use whoami
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse getMe(@Auth AuthenticatedAccount auth) {
|
||||
public AccountIdentityResponse getMe(@ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
return buildAccountIdentityResponse(auth);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/whoami")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse whoAmI(@Auth AuthenticatedAccount auth) {
|
||||
public AccountIdentityResponse whoAmI(@ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
return buildAccountIdentityResponse(auth);
|
||||
}
|
||||
|
||||
@@ -273,7 +275,7 @@ public class AccountController {
|
||||
)
|
||||
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public CompletableFuture<Response> deleteUsernameHash(@Auth final AuthenticatedAccount auth) {
|
||||
public CompletableFuture<Response> deleteUsernameHash(@Mutable @Auth final AuthenticatedAccount auth) {
|
||||
return accounts.clearUsernameHash(auth.getAccount())
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
@@ -295,7 +297,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public CompletableFuture<ReserveUsernameHashResponse> reserveUsernameHash(
|
||||
@Auth final AuthenticatedAccount auth,
|
||||
@Mutable @Auth final AuthenticatedAccount auth,
|
||||
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getUsernameReserveLimiter().validate(auth.getAccount().getUuid());
|
||||
@@ -335,7 +337,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public CompletableFuture<UsernameHashResponse> confirmUsernameHash(
|
||||
@Auth final AuthenticatedAccount auth,
|
||||
@Mutable @Auth final AuthenticatedAccount auth,
|
||||
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) {
|
||||
|
||||
try {
|
||||
@@ -380,7 +382,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "400", description = "Request must not be authenticated.")
|
||||
@ApiResponse(responseCode = "404", description = "Account not found for the given username.")
|
||||
public CompletableFuture<AccountIdentifierResponse> lookupUsernameHash(
|
||||
@Auth final Optional<AuthenticatedAccount> maybeAuthenticatedAccount,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> maybeAuthenticatedAccount,
|
||||
@PathParam("usernameHash") final String usernameHash) {
|
||||
|
||||
requireNotAuthenticated(maybeAuthenticatedAccount);
|
||||
@@ -419,7 +421,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public UsernameLinkHandle updateUsernameLink(
|
||||
@Auth final AuthenticatedAccount auth,
|
||||
@Mutable @Auth final AuthenticatedAccount auth,
|
||||
@NotNull @Valid final EncryptedUsername encryptedUsername) throws RateLimitExceededException {
|
||||
// check ratelimiter for username link operations
|
||||
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.getAccount().getUuid());
|
||||
@@ -453,7 +455,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Username Link successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public void deleteUsernameLink(@Auth final AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
public void deleteUsernameLink(@Mutable @Auth final AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
// check ratelimiter for username link operations
|
||||
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.getAccount().getUuid());
|
||||
clearUsernameLink(auth.getAccount());
|
||||
@@ -476,7 +478,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public CompletableFuture<EncryptedUsername> lookupUsernameLink(
|
||||
@Auth final Optional<AuthenticatedAccount> maybeAuthenticatedAccount,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> maybeAuthenticatedAccount,
|
||||
@PathParam("uuid") final UUID usernameLinkHandle) {
|
||||
|
||||
requireNotAuthenticated(maybeAuthenticatedAccount);
|
||||
@@ -502,7 +504,7 @@ public class AccountController {
|
||||
@Path("/account/{identifier}")
|
||||
@RateLimitedByIp(RateLimiters.For.CHECK_ACCOUNT_EXISTENCE)
|
||||
public Response accountExists(
|
||||
@Auth final Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
|
||||
@Parameter(description = "An ACI or PNI account identifier to check")
|
||||
@PathParam("identifier") final ServiceIdentifier accountIdentifier) {
|
||||
@@ -517,7 +519,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
public CompletableFuture<Response> deleteAccount(@Auth AuthenticatedAccount auth) {
|
||||
public CompletableFuture<Response> deleteAccount(@Mutable @Auth AuthenticatedAccount auth) {
|
||||
return accounts.delete(auth.getAccount(), AccountsManager.DeletionReason.USER_REQUEST).thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
|
||||
+9
-4
@@ -36,6 +36,7 @@ import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
@@ -57,6 +58,8 @@ import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v2/accounts")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Account")
|
||||
@@ -90,6 +93,7 @@ public class AccountControllerV2 {
|
||||
@Path("/number")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ChangesPhoneNumber
|
||||
@Operation(summary = "Change number", description = "Changes a phone number for an existing account.")
|
||||
@ApiResponse(responseCode = "200", description = "The phone number associated with the authenticated account was changed successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@@ -101,7 +105,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedAccount authenticatedAccount,
|
||||
public AccountIdentityResponse changeNumber(@Mutable @Auth final AuthenticatedAccount authenticatedAccount,
|
||||
@NotNull @Valid final ChangeNumberRequest request, @HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString)
|
||||
throws RateLimitExceededException, InterruptedException {
|
||||
|
||||
@@ -189,7 +193,8 @@ public class AccountControllerV2 {
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
|
||||
@ApiResponse(responseCode = "410", description = "The registration IDs provided for some devices do not match those stored on the server.",
|
||||
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
|
||||
public AccountIdentityResponse distributePhoneNumberIdentityKeys(@Auth final AuthenticatedAccount authenticatedAccount,
|
||||
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
|
||||
@Mutable @Auth final AuthenticatedAccount authenticatedAccount,
|
||||
@NotNull @Valid final PhoneNumberIdentityKeyDistributionRequest request) {
|
||||
|
||||
if (!authenticatedAccount.getAuthenticatedDevice().isPrimary()) {
|
||||
@@ -232,7 +237,7 @@ public class AccountControllerV2 {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public void setPhoneNumberDiscoverability(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@Mutable @Auth AuthenticatedAccount auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability
|
||||
) {
|
||||
accountsManager.update(auth.getAccount(), a -> a.setDiscoverableByPhoneNumber(
|
||||
@@ -246,7 +251,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "200",
|
||||
description = "Response with data report. A plain text representation is a field in the response.",
|
||||
useReturnTypeSchema = true)
|
||||
public AccountDataReportResponse getAccountDataReport(@Auth final AuthenticatedAccount auth) {
|
||||
public AccountDataReportResponse getAccountDataReport(@ReadOnly @Auth final AuthenticatedAccount auth) {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
|
||||
|
||||
+14
-11
@@ -62,6 +62,8 @@ import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@@ -108,7 +110,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "400", description = "The provided backup auth credential request was invalid")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited. Too many attempts to change the backup-id have been made")
|
||||
public CompletionStage<Response> setBackupId(
|
||||
@Auth final AuthenticatedAccount account,
|
||||
@Mutable @Auth final AuthenticatedAccount account,
|
||||
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest) throws RateLimitExceededException {
|
||||
return this.backupAuthManager
|
||||
.commitBackupId(account.getAccount(), setBackupIdRequest.backupAuthCredentialRequest)
|
||||
@@ -142,7 +144,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "404", description = "Could not find an existing blinded backup id")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<BackupAuthCredentialsResponse> getBackupZKCredentials(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@NotNull @QueryParam("redemptionStartSeconds") Long startSeconds,
|
||||
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) {
|
||||
|
||||
@@ -212,7 +214,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<ReadAuthResponse> readAuth(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -256,7 +258,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<BackupInfoResponse> backupInfo(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -300,7 +302,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "204", description = "The public key was set")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<Response> setPublicKey(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -337,7 +339,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<MessageBackupResponse> backup(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -425,7 +427,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "410", description = "The source object was not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<CopyMediaResponse> copyMedia(@Auth final Optional<AuthenticatedAccount> account,
|
||||
public CompletionStage<CopyMediaResponse> copyMedia(
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -533,7 +536,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> copyMedia(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -599,7 +602,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> refresh(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -656,7 +659,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<ListResponse> listMedia(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -709,7 +712,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> deleteMedia(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
@ReadOnly @Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
|
||||
+2
-1
@@ -17,6 +17,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/art")
|
||||
@Tag(name = "Art")
|
||||
@@ -42,7 +43,7 @@ public class ArtController {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(final @Auth AuthenticatedAccount auth)
|
||||
public ExternalServiceCredentials getAuth(final @ReadOnly @Auth AuthenticatedAccount auth)
|
||||
throws RateLimitExceededException {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validate(uuid);
|
||||
|
||||
+2
-1
@@ -29,6 +29,7 @@ import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v2/attachments")
|
||||
@Tag(name = "Attachments")
|
||||
@@ -51,7 +52,7 @@ public class AttachmentControllerV2 {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
public AttachmentDescriptorV2 getAttachmentUploadForm(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
rateLimiter.validate(auth.getAccount().getUuid());
|
||||
|
||||
+2
-1
@@ -23,6 +23,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v3/attachments")
|
||||
@Tag(name = "Attachments")
|
||||
@@ -47,7 +48,7 @@ public class AttachmentControllerV3 {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(@Auth AuthenticatedAccount auth)
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(@ReadOnly @Auth AuthenticatedAccount auth)
|
||||
throws RateLimitExceededException {
|
||||
rateLimiter.validate(auth.getAccount().getUuid());
|
||||
final String key = generateAttachmentKey();
|
||||
|
||||
+2
-1
@@ -26,6 +26,7 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
|
||||
/**
|
||||
@@ -76,7 +77,7 @@ public class AttachmentControllerV4 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(@Auth AuthenticatedAccount auth)
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(@ReadOnly @Auth AuthenticatedAccount auth)
|
||||
throws RateLimitExceededException {
|
||||
rateLimiter.validate(auth.getAccount().getUuid());
|
||||
final String key = generateAttachmentKey();
|
||||
|
||||
+2
-1
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateCallLinkCredential;
|
||||
import org.whispersystems.textsecuregcm.entities.GetCreateCallLinkCredentialsRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/call-link")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "CallLink")
|
||||
@@ -51,7 +52,7 @@ public class CallLinkController {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public CreateCallLinkCredential getCreateAuth(
|
||||
final @Auth AuthenticatedAccount auth,
|
||||
final @ReadOnly @Auth AuthenticatedAccount auth,
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request
|
||||
) throws RateLimitExceededException {
|
||||
|
||||
|
||||
+2
-1
@@ -25,6 +25,7 @@ import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
@@ -64,7 +65,7 @@ public class CallRoutingController {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public TurnToken getCallingRelays(
|
||||
final @Auth AuthenticatedAccount auth,
|
||||
final @ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@Context ContainerRequestContext requestContext
|
||||
) throws RateLimitExceededException {
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
|
||||
+3
-2
@@ -39,6 +39,7 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/certificate")
|
||||
@@ -69,7 +70,7 @@ public class CertificateController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/delivery")
|
||||
public DeliveryCertificate getDeliveryCertificate(@Auth AuthenticatedAccount auth,
|
||||
public DeliveryCertificate getDeliveryCertificate(@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164)
|
||||
throws InvalidKeyException {
|
||||
|
||||
@@ -88,7 +89,7 @@ public class CertificateController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/auth/group")
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds,
|
||||
@QueryParam("pniAsServiceId") boolean pniAsServiceId) {
|
||||
|
||||
+19
-15
@@ -38,23 +38,25 @@ import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.spam.Extract;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.PushChallengeConfig;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThreshold;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker.ChallengeConstraints;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/challenge")
|
||||
@Tag(name = "Challenge")
|
||||
@FilterSpam
|
||||
public class ChallengeController {
|
||||
|
||||
private final RateLimitChallengeManager rateLimitChallengeManager;
|
||||
private final ChallengeConstraintChecker challengeConstraintChecker;
|
||||
|
||||
private static final String CHALLENGE_RESPONSE_COUNTER_NAME = name(ChallengeController.class, "challengeResponse");
|
||||
private static final String CHALLENGE_TYPE_TAG = "type";
|
||||
|
||||
public ChallengeController(final RateLimitChallengeManager rateLimitChallengeManager) {
|
||||
public ChallengeController(
|
||||
final RateLimitChallengeManager rateLimitChallengeManager,
|
||||
final ChallengeConstraintChecker challengeConstraintChecker) {
|
||||
this.rateLimitChallengeManager = rateLimitChallengeManager;
|
||||
this.challengeConstraintChecker = challengeConstraintChecker;
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -77,20 +79,20 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public Response handleChallengeResponse(@Auth final AuthenticatedAccount auth,
|
||||
public Response handleChallengeResponse(@ReadOnly @Auth final AuthenticatedAccount auth,
|
||||
@Valid final AnswerChallengeRequest answerRequest,
|
||||
@Context ContainerRequestContext requestContext,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Extract final ScoreThreshold captchaScoreThreshold,
|
||||
@Extract final PushChallengeConfig pushChallengeConfig) throws RateLimitExceededException, IOException {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws RateLimitExceededException, IOException {
|
||||
|
||||
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
|
||||
final ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraints(
|
||||
requestContext, auth.getAccount());
|
||||
try {
|
||||
if (answerRequest instanceof final AnswerPushChallengeRequest pushChallengeRequest) {
|
||||
tags = tags.and(CHALLENGE_TYPE_TAG, "push");
|
||||
|
||||
if (!pushChallengeConfig.pushPermitted()) {
|
||||
if (!constraints.pushPermitted()) {
|
||||
return Response.status(429).build();
|
||||
}
|
||||
rateLimitChallengeManager.answerPushChallenge(auth.getAccount(), pushChallengeRequest.getChallenge());
|
||||
@@ -104,7 +106,7 @@ public class ChallengeController {
|
||||
recaptchaChallengeRequest.getCaptcha(),
|
||||
remoteAddress,
|
||||
userAgent,
|
||||
captchaScoreThreshold.getScoreThreshold());
|
||||
constraints.captchaScoreThreshold());
|
||||
|
||||
if (!success) {
|
||||
return Response.status(428).build();
|
||||
@@ -163,9 +165,11 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public Response requestPushChallenge(@Auth final AuthenticatedAccount auth,
|
||||
@Extract PushChallengeConfig pushChallengeConfig) {
|
||||
if (!pushChallengeConfig.pushPermitted()) {
|
||||
public Response requestPushChallenge(@ReadOnly @Auth final AuthenticatedAccount auth,
|
||||
@Context ContainerRequestContext requestContext) {
|
||||
final ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraints(
|
||||
requestContext, auth.getAccount());
|
||||
if (!constraints.pushPermitted()) {
|
||||
return Response.status(429).build();
|
||||
}
|
||||
try {
|
||||
|
||||
+7
-5
@@ -66,6 +66,8 @@ import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.util.VerificationCode;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/devices")
|
||||
@Tag(name = "Devices")
|
||||
@@ -111,7 +113,7 @@ public class DeviceController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public DeviceInfoList getDevices(@Auth AuthenticatedAccount auth) {
|
||||
public DeviceInfoList getDevices(@ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
List<DeviceInfo> devices = new LinkedList<>();
|
||||
|
||||
for (Device device : auth.getAccount().getDevices()) {
|
||||
@@ -126,7 +128,7 @@ public class DeviceController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{device_id}")
|
||||
@ChangesDeviceEnabledState
|
||||
public void removeDevice(@Auth AuthenticatedAccount auth, @PathParam("device_id") byte deviceId) {
|
||||
public void removeDevice(@Mutable @Auth AuthenticatedAccount auth, @PathParam("device_id") byte deviceId) {
|
||||
if (auth.getAuthenticatedDevice().getId() != Device.PRIMARY_ID) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
@@ -141,7 +143,7 @@ public class DeviceController {
|
||||
@GET
|
||||
@Path("/provisioning/code")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationCode createDeviceToken(@Auth AuthenticatedAccount auth)
|
||||
public VerificationCode createDeviceToken(@ReadOnly @Auth AuthenticatedAccount auth)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
@@ -258,7 +260,7 @@ public class DeviceController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/unauthenticated_delivery")
|
||||
public void setUnauthenticatedDelivery(@Auth AuthenticatedAccount auth) {
|
||||
public void setUnauthenticatedDelivery(@Mutable @Auth AuthenticatedAccount auth) {
|
||||
assert (auth.getAuthenticatedDevice() != null);
|
||||
// Deprecated
|
||||
}
|
||||
@@ -266,7 +268,7 @@ public class DeviceController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
public void setCapabilities(@Auth AuthenticatedAccount auth, @NotNull @Valid DeviceCapabilities capabilities) {
|
||||
public void setCapabilities(@Mutable @Auth AuthenticatedAccount auth, @NotNull @Valid DeviceCapabilities capabilities) {
|
||||
assert (auth.getAuthenticatedDevice() != null);
|
||||
final byte deviceId = auth.getAuthenticatedDevice().getId();
|
||||
accounts.updateDevice(auth.getAccount(), deviceId, d -> d.setCapabilities(capabilities));
|
||||
|
||||
+2
-1
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryV2ClientConfiguration;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v2/directory")
|
||||
@Tag(name = "Directory")
|
||||
@@ -47,7 +48,7 @@ public class DirectoryV2Controller {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAuthToken(final @Auth AuthenticatedAccount auth) {
|
||||
public Response getAuthToken(final @ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
final ExternalServiceCredentials credentials = directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
return Response.ok().entity(credentials).build();
|
||||
|
||||
+2
-1
@@ -36,6 +36,7 @@ import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
|
||||
@Path("/v1/donation")
|
||||
@Tag(name = "Donations")
|
||||
@@ -74,7 +75,7 @@ public class DonationController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
|
||||
public CompletionStage<Response> redeemReceipt(
|
||||
@Auth final AuthenticatedAccount auth,
|
||||
@Mutable @Auth final AuthenticatedAccount auth,
|
||||
@NotNull @Valid final RedeemReceiptRequest request) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
ReceiptCredentialPresentation receiptCredentialPresentation;
|
||||
|
||||
+2
-1
@@ -20,6 +20,7 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
@@ -40,7 +41,7 @@ public class KeepAliveController {
|
||||
}
|
||||
|
||||
@GET
|
||||
public Response getKeepAlive(@Auth Optional<AuthenticatedAccount> maybeAuth,
|
||||
public Response getKeepAlive(@ReadOnly @Auth Optional<AuthenticatedAccount> maybeAuth,
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
|
||||
+181
-23
@@ -6,7 +6,9 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -14,7 +16,11 @@ import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -26,6 +32,7 @@ import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
@@ -39,6 +46,7 @@ import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
|
||||
import org.whispersystems.textsecuregcm.entities.CheckKeysRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
@@ -60,19 +68,23 @@ import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v2/keys")
|
||||
@Tag(name = "Keys")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Keys")
|
||||
public class KeysController {
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private final KeysManager keysManager;
|
||||
private final AccountsManager accounts;
|
||||
|
||||
private static final String KEY_COUNT_DISTRIBUTION_NAME = MetricsUtil.name(KeysController.class, "getKeyCount");
|
||||
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
|
||||
private static final String ONE_TIME_EC_PRE_KEY_UNAVAILABLE_COUNTER_NAME =
|
||||
MetricsUtil.name(KeysController.class, "oneTimeEcPreKeyUnavailable");
|
||||
private static final String STORE_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "storeKeys");
|
||||
private static final String PRIMARY_DEVICE_TAG_NAME = "isPrimary";
|
||||
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
|
||||
private static final String KEY_TYPE_TAG_NAME = "keyType";
|
||||
|
||||
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture[0];
|
||||
|
||||
@@ -88,14 +100,37 @@ public class KeysController {
|
||||
description = "Gets the number of one-time prekeys uploaded for this device and still available")
|
||||
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public CompletableFuture<PreKeyCount> getStatus(@Auth final AuthenticatedAccount auth,
|
||||
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
|
||||
public CompletableFuture<PreKeyCount> getStatus(@ReadOnly @Auth final AuthenticatedAccount auth,
|
||||
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
|
||||
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
|
||||
final Tag primaryDeviceTag = Tag.of(PRIMARY_DEVICE_TAG_NAME, String.valueOf(auth.getAuthenticatedDevice().isPrimary()));
|
||||
final Tag identityTypeTag = Tag.of(IDENTITY_TYPE_TAG_NAME, identityType.name());
|
||||
|
||||
final CompletableFuture<Integer> ecCountFuture =
|
||||
keysManager.getEcCount(auth.getAccount().getIdentifier(identityType), auth.getAuthenticatedDevice().getId());
|
||||
keysManager.getEcCount(auth.getAccount().getIdentifier(identityType), auth.getAuthenticatedDevice().getId())
|
||||
.whenComplete((keyCount, throwable) -> {
|
||||
if (keyCount != null) {
|
||||
DistributionSummary.builder(KEY_COUNT_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "ec")))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(keyCount);
|
||||
}
|
||||
});
|
||||
|
||||
final CompletableFuture<Integer> pqCountFuture =
|
||||
keysManager.getPqCount(auth.getAccount().getIdentifier(identityType), auth.getAuthenticatedDevice().getId());
|
||||
keysManager.getPqCount(auth.getAccount().getIdentifier(identityType), auth.getAuthenticatedDevice().getId())
|
||||
.whenComplete((keyCount, throwable) -> {
|
||||
if (keyCount != null) {
|
||||
DistributionSummary.builder(KEY_COUNT_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "kyber")))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(keyCount);
|
||||
}
|
||||
});
|
||||
|
||||
return ecCountFuture.thenCombine(pqCountFuture, PreKeyCount::new);
|
||||
}
|
||||
@@ -108,7 +143,8 @@ public class KeysController {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "Attempt to change identity key from a non-primary device.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
public CompletableFuture<Response> setKeys(@Auth final AuthenticatedAccount auth,
|
||||
public CompletableFuture<Response> setKeys(
|
||||
@ReadOnly @Auth final AuthenticatedAccount auth,
|
||||
@RequestBody @NotNull @Valid final SetKeysRequest setKeysRequest,
|
||||
|
||||
@Parameter(allowEmptyValue=true)
|
||||
@@ -116,7 +152,8 @@ public class KeysController {
|
||||
allowableValues={"aci", "pni"},
|
||||
defaultValue="aci",
|
||||
description="whether this operation applies to the account (aci) or phone-number (pni) identity")
|
||||
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
|
||||
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
|
||||
final Account account = auth.getAccount();
|
||||
final Device device = auth.getAuthenticatedDevice();
|
||||
@@ -124,21 +161,41 @@ public class KeysController {
|
||||
|
||||
checkSignedPreKeySignatures(setKeysRequest, account.getIdentityKey(identityType));
|
||||
|
||||
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
|
||||
final Tag primaryDeviceTag = Tag.of(PRIMARY_DEVICE_TAG_NAME, String.valueOf(auth.getAuthenticatedDevice().isPrimary()));
|
||||
final Tag identityTypeTag = Tag.of(IDENTITY_TYPE_TAG_NAME, identityType.name());
|
||||
|
||||
final List<CompletableFuture<Void>> storeFutures = new ArrayList<>(4);
|
||||
|
||||
if (setKeysRequest.preKeys() != null && !setKeysRequest.preKeys().isEmpty()) {
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME,
|
||||
Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "ec")))
|
||||
.increment();
|
||||
|
||||
storeFutures.add(keysManager.storeEcOneTimePreKeys(identifier, device.getId(), setKeysRequest.preKeys()));
|
||||
}
|
||||
|
||||
if (setKeysRequest.signedPreKey() != null) {
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME,
|
||||
Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "ec-signed")))
|
||||
.increment();
|
||||
|
||||
storeFutures.add(keysManager.storeEcSignedPreKeys(identifier, device.getId(), setKeysRequest.signedPreKey()));
|
||||
}
|
||||
|
||||
if (setKeysRequest.pqPreKeys() != null && !setKeysRequest.pqPreKeys().isEmpty()) {
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME,
|
||||
Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "kyber")))
|
||||
.increment();
|
||||
|
||||
storeFutures.add(keysManager.storeKemOneTimePreKeys(identifier, device.getId(), setKeysRequest.pqPreKeys()));
|
||||
}
|
||||
|
||||
if (setKeysRequest.pqLastResortPreKey() != null) {
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME,
|
||||
Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "kyber-last-resort")))
|
||||
.increment();
|
||||
|
||||
storeFutures.add(keysManager.storePqLastResort(identifier, device.getId(), setKeysRequest.pqLastResortPreKey()));
|
||||
}
|
||||
|
||||
@@ -169,6 +226,97 @@ public class KeysController {
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Check keys", description = """
|
||||
Checks that client and server have consistent views of repeated-use keys. For a given identity type, clients
|
||||
submit a digest of their repeated-use key material. The digest is calculated as:
|
||||
|
||||
SHA256(identityKeyBytes || signedEcPreKeyId || signedEcPreKeyIdBytes || lastResortKeyId || lastResortKeyBytes)
|
||||
|
||||
…where the elements of the hash are:
|
||||
|
||||
- identityKeyBytes: the serialized form of the client's public identity key as produced by libsignal (i.e. one
|
||||
version byte followed by 32 bytes of key material for a total of 33 bytes)
|
||||
- signedEcPreKeyId: an 8-byte, big-endian representation of the ID of the client's signed EC pre-key
|
||||
- signedEcPreKeyBytes: the serialized form of the client's signed EC pre-key as produced by libsignal (i.e. one
|
||||
version byte followed by 32 bytes of key material for a total of 33 bytes)
|
||||
- lastResortKeyId: an 8-byte, big-endian representation of the ID of the client's last-resort Kyber key
|
||||
- lastResortKeyBytes: the serialized form of the client's last-resort Kyber key as produced by libsignal (i.e. one
|
||||
version byte followed by 1568 bytes of key material for a total of 1569 bytes)
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Indicates that client and server have consistent views of repeated-use keys")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
|
||||
@ApiResponse(responseCode = "409", description = """
|
||||
Indicates that client and server have inconsistent views of repeated-use keys or one or more repeated-use keys could
|
||||
not be found
|
||||
""")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
public CompletableFuture<Response> checkKeys(
|
||||
@ReadOnly @Auth final AuthenticatedAccount auth,
|
||||
@RequestBody @NotNull @Valid final CheckKeysRequest checkKeysRequest,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
|
||||
final UUID identifier = auth.getAccount().getIdentifier(checkKeysRequest.identityType());
|
||||
final byte deviceId = auth.getAuthenticatedDevice().getId();
|
||||
|
||||
final CompletableFuture<Optional<ECSignedPreKey>> ecSignedPreKeyFuture =
|
||||
keysManager.getEcSignedPreKey(identifier, deviceId);
|
||||
|
||||
final CompletableFuture<Optional<KEMSignedPreKey>> lastResortKeyFuture =
|
||||
keysManager.getLastResort(identifier, deviceId);
|
||||
|
||||
return CompletableFuture.allOf(ecSignedPreKeyFuture, lastResortKeyFuture)
|
||||
.thenApply(ignored -> {
|
||||
final Optional<ECSignedPreKey> maybeSignedPreKey = ecSignedPreKeyFuture.join();
|
||||
final Optional<KEMSignedPreKey> maybeLastResortKey = lastResortKeyFuture.join();
|
||||
|
||||
final boolean digestsMatch;
|
||||
|
||||
if (maybeSignedPreKey.isPresent() && maybeLastResortKey.isPresent()) {
|
||||
final IdentityKey identityKey = auth.getAccount().getIdentityKey(checkKeysRequest.identityType());
|
||||
final ECSignedPreKey ecSignedPreKey = maybeSignedPreKey.get();
|
||||
final KEMSignedPreKey lastResortKey = maybeLastResortKey.get();
|
||||
|
||||
final MessageDigest messageDigest;
|
||||
|
||||
try {
|
||||
messageDigest = MessageDigest.getInstance("SHA-256");
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support SHA-256", e);
|
||||
}
|
||||
|
||||
messageDigest.update(identityKey.serialize());
|
||||
|
||||
{
|
||||
final ByteBuffer ecSignedPreKeyIdBuffer = ByteBuffer.allocate(Long.BYTES);
|
||||
ecSignedPreKeyIdBuffer.putLong(ecSignedPreKey.keyId());
|
||||
ecSignedPreKeyIdBuffer.flip();
|
||||
|
||||
messageDigest.update(ecSignedPreKeyIdBuffer);
|
||||
messageDigest.update(ecSignedPreKey.serializedPublicKey());
|
||||
}
|
||||
|
||||
{
|
||||
final ByteBuffer lastResortKeyIdBuffer = ByteBuffer.allocate(Long.BYTES);
|
||||
lastResortKeyIdBuffer.putLong(lastResortKey.keyId());
|
||||
lastResortKeyIdBuffer.flip();
|
||||
|
||||
messageDigest.update(lastResortKeyIdBuffer);
|
||||
messageDigest.update(lastResortKey.serializedPublicKey());
|
||||
}
|
||||
|
||||
digestsMatch = MessageDigest.isEqual(messageDigest.digest(), checkKeysRequest.digest());
|
||||
} else {
|
||||
digestsMatch = false;
|
||||
}
|
||||
|
||||
return Response.status(digestsMatch ? Response.Status.OK : Response.Status.CONFLICT).build();
|
||||
});
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{identifier}/{device_id}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -180,7 +328,8 @@ public class KeysController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public PreKeyResponse getDeviceKeys(@Auth Optional<AuthenticatedAccount> auth,
|
||||
public PreKeyResponse getDeviceKeys(
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> auth,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
|
||||
@Parameter(description="the account or phone-number identifier to retrieve keys for")
|
||||
@@ -213,11 +362,6 @@ public class KeysController {
|
||||
+ "." + deviceId);
|
||||
}
|
||||
|
||||
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
io.micrometer.core.instrument.Tag.of("wildcardDeviceId", String.valueOf("*".equals(deviceId)))))
|
||||
.increment();
|
||||
|
||||
final List<Device> devices = parseDeviceId(deviceId, target);
|
||||
final List<PreKeyResponseItem> responseItems = new ArrayList<>(devices.size());
|
||||
|
||||
@@ -237,12 +381,14 @@ public class KeysController {
|
||||
final ECPreKey unsignedEcPreKey = unsignedEcPreKeyFuture.join().orElse(null);
|
||||
final ECSignedPreKey signedEcPreKey = signedEcPreKeyFuture.join().orElse(null);
|
||||
|
||||
if (unsignedEcPreKey == null) {
|
||||
Metrics.counter(ONE_TIME_EC_PRE_KEY_UNAVAILABLE_COUNTER_NAME,
|
||||
"isPrimary", String.valueOf(device.isPrimary()),
|
||||
"platform", getDevicePlatform(device).map(Enum::name).orElse("unknown"))
|
||||
.increment();
|
||||
}
|
||||
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
|
||||
Tag.of(PRIMARY_DEVICE_TAG_NAME, String.valueOf(device.isPrimary())),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("targetPlatform", getDevicePlatform(device).map(Enum::name).orElse("unknown")),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, targetIdentifier.identityType().name()),
|
||||
Tag.of("isStale", String.valueOf(isDeviceStale(device))),
|
||||
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null))))
|
||||
.increment();
|
||||
|
||||
if (signedEcPreKey != null || unsignedEcPreKey != null || pqPreKey != null) {
|
||||
final int registrationId = switch (targetIdentifier.identityType()) {
|
||||
@@ -279,6 +425,11 @@ public class KeysController {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static boolean isDeviceStale(final Device device) {
|
||||
return Duration.between(Instant.ofEpochMilli(device.getLastSeen()), Instant.now())
|
||||
.compareTo(Duration.ofDays(30)) >= 0;
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/signed")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -289,13 +440,20 @@ public class KeysController {
|
||||
@ApiResponse(responseCode = "200", description = "Indicates that new prekey was successfully stored.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
public CompletableFuture<Response> setSignedKey(@Auth final AuthenticatedAccount auth,
|
||||
// TODO Remove this endpoint on or after 2024-05-24
|
||||
@Deprecated(forRemoval = true)
|
||||
public CompletableFuture<Response> setSignedKey(
|
||||
@ReadOnly @Auth final AuthenticatedAccount auth,
|
||||
@Valid final ECSignedPreKey signedPreKey,
|
||||
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
|
||||
|
||||
final UUID identifier = auth.getAccount().getIdentifier(identityType);
|
||||
final byte deviceId = auth.getAuthenticatedDevice().getId();
|
||||
|
||||
if (!PreKeySignatureValidator.validatePreKeySignatures(auth.getAccount().getIdentityKey(identityType), List.of(signedPreKey))) {
|
||||
throw new WebApplicationException("Invalid signature", 422);
|
||||
}
|
||||
|
||||
return keysManager.storeEcSignedPreKeys(identifier, deviceId, signedPreKey)
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
+5
-5
@@ -113,7 +113,6 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -129,6 +128,7 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.websocket.Stories;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -235,7 +235,7 @@ public class MessageController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public Response sendMessage(@Auth Optional<AuthenticatedAccount> source,
|
||||
public Response sendMessage(@ReadOnly @Auth Optional<AuthenticatedAccount> source,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@PathParam("destination") ServiceIdentifier destinationIdentifier,
|
||||
@@ -667,7 +667,7 @@ public class MessageController {
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<OutgoingMessageEntityList> getPendingMessages(@Auth AuthenticatedAccount auth,
|
||||
public CompletableFuture<OutgoingMessageEntityList> getPendingMessages(@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@HeaderParam(Stories.X_SIGNAL_RECEIVE_STORIES) String receiveStoriesHeader,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
|
||||
|
||||
@@ -718,7 +718,7 @@ public class MessageController {
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/uuid/{uuid}")
|
||||
public CompletableFuture<Response> removePendingMessage(@Auth AuthenticatedAccount auth, @PathParam("uuid") UUID uuid) {
|
||||
public CompletableFuture<Response> removePendingMessage(@ReadOnly @Auth AuthenticatedAccount auth, @PathParam("uuid") UUID uuid) {
|
||||
return messagesManager.delete(
|
||||
auth.getAccount().getUuid(),
|
||||
auth.getAuthenticatedDevice().getId(),
|
||||
@@ -749,7 +749,7 @@ public class MessageController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Path("/report/{source}/{messageGuid}")
|
||||
public Response reportSpamMessage(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@PathParam("source") String source,
|
||||
@PathParam("messageGuid") UUID messageGuid,
|
||||
@Nullable @Valid SpamReport spamReport,
|
||||
|
||||
+3
-2
@@ -17,6 +17,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/payments")
|
||||
@Tag(name = "Payments")
|
||||
@@ -42,14 +43,14 @@ public class PaymentsController {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(final @Auth AuthenticatedAccount auth) {
|
||||
public ExternalServiceCredentials getAuth(final @ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
return paymentsServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/conversions")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CurrencyConversionEntityList getConversions(final @Auth AuthenticatedAccount auth) {
|
||||
public CurrencyConversionEntityList getConversions(final @ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
return currencyManager.getCurrencyConversions().orElseThrow();
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -99,6 +99,8 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
|
||||
@@ -162,7 +164,7 @@ public class ProfileController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public Response setProfile(@Auth AuthenticatedAccount auth, @NotNull @Valid CreateProfileRequest request) {
|
||||
public Response setProfile(@Mutable @Auth AuthenticatedAccount auth, @NotNull @Valid CreateProfileRequest request) {
|
||||
|
||||
final Optional<VersionedProfile> currentProfile = profilesManager.get(auth.getAccount().getUuid(),
|
||||
request.version());
|
||||
@@ -228,7 +230,7 @@ public class ProfileController {
|
||||
@Path("/{identifier}/{version}")
|
||||
@ManagedAsync
|
||||
public VersionedProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedAccount> auth,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> auth,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@PathParam("identifier") AciServiceIdentifier accountIdentifier,
|
||||
@@ -248,7 +250,7 @@ public class ProfileController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}/{credentialRequest}")
|
||||
public CredentialProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedAccount> auth,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> auth,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@PathParam("identifier") AciServiceIdentifier accountIdentifier,
|
||||
@@ -279,7 +281,7 @@ public class ProfileController {
|
||||
@Path("/{identifier}")
|
||||
@ManagedAsync
|
||||
public BaseProfileResponse getUnversionedProfile(
|
||||
@Auth Optional<AuthenticatedAccount> auth,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> auth,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
|
||||
+2
-1
@@ -23,6 +23,7 @@ import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningAddress;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/provisioning")
|
||||
@Tag(name = "Provisioning")
|
||||
@@ -40,7 +41,7 @@ public class ProvisioningController {
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public void sendProvisioningMessage(@Auth AuthenticatedAccount auth,
|
||||
public void sendProvisioningMessage(@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@PathParam("destination") String destinationName,
|
||||
@NotNull @Valid ProvisioningMessage message)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
+2
-1
@@ -28,6 +28,7 @@ import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/config")
|
||||
@Tag(name = "Remote Config")
|
||||
@@ -51,7 +52,7 @@ public class RemoteConfigController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public UserRemoteConfigList getAll(@Auth AuthenticatedAccount auth) {
|
||||
public UserRemoteConfigList getAll(@ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
|
||||
|
||||
+2
-1
@@ -15,6 +15,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/storage")
|
||||
@Tag(name = "Secure Storage")
|
||||
@@ -36,7 +37,7 @@ public class SecureStorageController {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(@Auth AuthenticatedAccount auth) {
|
||||
public ExternalServiceCredentials getAuth(@ReadOnly @Auth AuthenticatedAccount auth) {
|
||||
return storageServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v2/backup")
|
||||
@Tag(name = "Secure Value Recovery")
|
||||
@@ -77,7 +78,7 @@ public class SecureValueRecovery2Controller {
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public ExternalServiceCredentials getAuth(@Auth final AuthenticatedAccount auth) {
|
||||
public ExternalServiceCredentials getAuth(@ReadOnly @Auth final AuthenticatedAccount auth) {
|
||||
return backupServiceCredentialGenerator.generateFor(auth.getAccount().getUuid().toString());
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -21,6 +21,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
@@ -78,7 +79,7 @@ public class SecureValueRecovery3Controller {
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public ExternalServiceCredentials getAuth(@Auth final AuthenticatedAccount auth) {
|
||||
public ExternalServiceCredentials getAuth(@ReadOnly @Auth final AuthenticatedAccount auth) {
|
||||
return backupServiceCredentialGenerator.generateFor(auth.getAccount().getUuid().toString());
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -28,6 +28,7 @@ import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/sticker")
|
||||
@Tag(name = "Stickers")
|
||||
@@ -46,7 +47,7 @@ public class StickerController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/pack/form/{count}")
|
||||
public StickerPackFormUploadAttributes getStickersForm(@Auth AuthenticatedAccount auth,
|
||||
public StickerPackFormUploadAttributes getStickersForm(@ReadOnly @Auth AuthenticatedAccount auth,
|
||||
@PathParam("count") @Min(1) @Max(201) int stickerCount)
|
||||
throws RateLimitExceededException {
|
||||
rateLimiters.getStickerPackLimiter().validate(auth.getAccount().getUuid());
|
||||
|
||||
+11
-10
@@ -98,6 +98,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/subscription")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Subscriptions")
|
||||
@@ -224,7 +225,7 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> deleteSubscriber(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) {
|
||||
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
|
||||
@@ -246,7 +247,7 @@ public class SubscriptionController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> updateSubscriber(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) {
|
||||
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
|
||||
@@ -280,7 +281,7 @@ public class SubscriptionController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createPaymentMethod(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType) {
|
||||
|
||||
@@ -334,7 +335,7 @@ public class SubscriptionController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createPayPalPaymentMethod(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
|
||||
@Context ContainerRequestContext containerRequestContext) {
|
||||
@@ -399,7 +400,7 @@ public class SubscriptionController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Deprecated // use /{subscriberId}/default_payment_method/{processor}/{paymentMethodId}
|
||||
public CompletableFuture<Response> setDefaultPaymentMethod(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("paymentMethodId") @NotEmpty String paymentMethodId) {
|
||||
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
|
||||
@@ -415,7 +416,7 @@ public class SubscriptionController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> setDefaultPaymentMethodWithProcessor(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("processor") SubscriptionProcessor processor,
|
||||
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) {
|
||||
@@ -446,7 +447,7 @@ public class SubscriptionController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> setSubscriptionLevel(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("level") long level,
|
||||
@PathParam("currency") String currency,
|
||||
@@ -873,7 +874,7 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> getSubscriptionInformation(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) {
|
||||
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
|
||||
@@ -916,7 +917,7 @@ public class SubscriptionController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createSubscriptionReceiptCredentials(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid GetReceiptCredentialsRequest request) {
|
||||
@@ -965,7 +966,7 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}/default_payment_method_for_ideal/{setupIntentId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> setDefaultPaymentMethodForIdeal(
|
||||
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@ReadOnly @Auth Optional<AuthenticatedAccount> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) {
|
||||
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
+16
-36
@@ -80,10 +80,8 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceExceptio
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
|
||||
import org.whispersystems.textsecuregcm.registration.TransportNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.spam.Extract;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThreshold;
|
||||
import org.whispersystems.textsecuregcm.spam.SenderOverride;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker.VerificationCheck;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
@@ -121,7 +119,7 @@ public class VerificationController {
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Clock clock;
|
||||
|
||||
@@ -132,6 +130,7 @@ public class VerificationController {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final AccountsManager accountsManager,
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Clock clock) {
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
@@ -141,6 +140,7 @@ public class VerificationController {
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
@@ -195,17 +195,16 @@ public class VerificationController {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
@FilterSpam
|
||||
@PATCH
|
||||
@Path("/session/{sessionId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse updateSession(@PathParam("sessionId") final String encodedSessionId,
|
||||
public VerificationSessionResponse updateSession(
|
||||
@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Context ContainerRequestContext requestContext,
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest,
|
||||
@NotNull @Extract final ScoreThreshold scoreThreshold,
|
||||
@NotNull @Extract final SenderOverride senderOverride) {
|
||||
@Context ContainerRequestContext context) {
|
||||
|
||||
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
@@ -215,10 +214,16 @@ public class VerificationController {
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
final VerificationCheck verificationCheck = registrationFraudChecker.checkVerificationAttempt(
|
||||
context,
|
||||
verificationSession,
|
||||
registrationServiceSession.number(),
|
||||
updateVerificationSessionRequest);
|
||||
|
||||
try {
|
||||
// these handle* methods ordered from least likely to fail to most, so take care when considering a change
|
||||
|
||||
verificationSession = handleSenderOverrides(verificationSession, senderOverride);
|
||||
verificationSession = verificationCheck.updatedSession().orElse(verificationSession);
|
||||
|
||||
verificationSession = handlePushToken(pushTokenAndType, verificationSession);
|
||||
|
||||
@@ -226,7 +231,7 @@ public class VerificationController {
|
||||
verificationSession);
|
||||
|
||||
verificationSession = handleCaptcha(sourceHost, updateVerificationSessionRequest, registrationServiceSession,
|
||||
verificationSession, userAgent, scoreThreshold.getScoreThreshold());
|
||||
verificationSession, userAgent, verificationCheck.scoreThreshold());
|
||||
} catch (final RateLimitExceededException e) {
|
||||
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession, registrationServiceSession,
|
||||
@@ -424,31 +429,6 @@ public class VerificationController {
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the verification session with explicit sender overrides if present. When the session is used to send
|
||||
* verification codes, these overrides will be used.
|
||||
*
|
||||
* @param verificationSession the session to update
|
||||
* @param senderOverride configured sender overrides
|
||||
* @return An updated {@link VerificationSession}
|
||||
*/
|
||||
private VerificationSession handleSenderOverrides(
|
||||
VerificationSession verificationSession,
|
||||
SenderOverride senderOverride) {
|
||||
return new VerificationSession(
|
||||
verificationSession.pushChallenge(),
|
||||
verificationSession.requestedInformation(),
|
||||
verificationSession.submittedInformation(),
|
||||
Optional.ofNullable(verificationSession.smsSenderOverride())
|
||||
.or(senderOverride::getSmsSenderOverride).orElse(null),
|
||||
Optional.ofNullable(verificationSession.voiceSenderOverride())
|
||||
.or(senderOverride::getVoiceSenderOverride)
|
||||
.orElse(null), verificationSession.allowedToRequestCode(),
|
||||
verificationSession.createdTimestamp(),
|
||||
clock.millis(),
|
||||
verificationSession.remoteExpirationSeconds());
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/session/{sessionId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.AssertTrue;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
|
||||
public record ChangePhoneNumberRequest(
|
||||
@Schema(description="the new phone number for this account")
|
||||
@NotBlank String number,
|
||||
|
||||
@Schema(description="the registration verification code to authenticate this request")
|
||||
@NotBlank String code,
|
||||
|
||||
@Schema(description="the registration lock password for the new phone number, if necessary")
|
||||
@JsonProperty("reglock") @Nullable String registrationLock,
|
||||
|
||||
@Schema(description="the new public identity key to use for the phone-number identity associated with the new phone number")
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
@Nullable IdentityKey pniIdentityKey,
|
||||
|
||||
@Schema(description="""
|
||||
A list of synchronization messages to send to companion devices to supply the private keysManager
|
||||
associated with the new identity key and their new prekeys.
|
||||
Exactly one message must be supplied for each enabled device other than the sending (primary) device.""")
|
||||
@Nullable List<IncomingMessage> deviceMessages,
|
||||
|
||||
@Schema(description="""
|
||||
A new signed elliptic-curve prekey for each enabled device on the account, including this one.
|
||||
Each must be accompanied by a valid signature from the new identity key in this request.""")
|
||||
@Nullable Map<Long, ECSignedPreKey> devicePniSignedPrekeys,
|
||||
|
||||
@Schema(description="""
|
||||
A new signed post-quantum last-resort prekey for each enabled device on the account, including this one.
|
||||
May be absent, in which case the last resort PQ prekeys for each device will be deleted if any had been stored.
|
||||
If present, must contain one prekey per enabled device including this one.
|
||||
Prekeys for devices that did not previously have any post-quantum prekeys stored will be silently dropped.
|
||||
Each must be accompanied by a valid signature from the new identity key in this request.""")
|
||||
@Nullable @Valid Map<Long, @NotNull @Valid KEMSignedPreKey> devicePniPqLastResortPrekeys,
|
||||
|
||||
@Schema(description="the new phone-number-identity registration ID for each enabled device on the account, including this one")
|
||||
@Nullable Map<Long, Integer> pniRegistrationIds) {
|
||||
|
||||
@AssertTrue
|
||||
public boolean isSignatureValidOnEachSignedPreKey() {
|
||||
List<SignedPreKey<?>> spks = new ArrayList<>();
|
||||
if (devicePniSignedPrekeys != null) {
|
||||
spks.addAll(devicePniSignedPrekeys.values());
|
||||
}
|
||||
if (devicePniPqLastResortPrekeys != null) {
|
||||
spks.addAll(devicePniPqLastResortPrekeys.values());
|
||||
}
|
||||
return spks.isEmpty() || PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey, spks);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record CheckKeysRequest(
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
The identity type for which to check for a shared view of repeated-use keys
|
||||
""")
|
||||
IdentityType identityType,
|
||||
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@ExactlySize(32)
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
A 32-byte digest of the client's repeated-use keys for the given identity type. The digest is calculated as:
|
||||
|
||||
SHA256(identityKeyBytes || signedEcPreKeyId || signedEcPreKeyIdBytes || lastResortKeyId || lastResortKeyBytes)
|
||||
|
||||
…where the elements of the hash are:
|
||||
|
||||
- identityKeyBytes: the serialized form of the client's public identity key as produced by libsignal (i.e. one
|
||||
version byte followed by 32 bytes of key material for a total of 33 bytes)
|
||||
- signedEcPreKeyId: an 8-byte, big-endian representation of the ID of the client's signed EC pre-key
|
||||
- signedEcPreKeyBytes: the serialized form of the client's signed EC pre-key as produced by libsignal (i.e. one
|
||||
version byte followed by 32 bytes of key material for a total of 33 bytes)
|
||||
- lastResortKeyId: an 8-byte, big-endian representation of the ID of the client's last-resort Kyber key
|
||||
- lastResortKeyBytes: the serialized form of the client's last-resort Kyber key as produced by libsignal (i.e.
|
||||
one version byte followed by 1568 bytes of key material for a total of 1569 bytes)
|
||||
""")
|
||||
byte[] digest) {
|
||||
}
|
||||
+2
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
@@ -25,6 +26,7 @@ public record ConfirmUsernameHashRequest(
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
|
||||
@NotNull
|
||||
byte[] zkProof,
|
||||
|
||||
@Schema(type = "string", description = "The url-safe base64-encoded encrypted username to be stored for username links")
|
||||
|
||||
+6
-3
@@ -8,10 +8,13 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public record UserCapabilities(boolean paymentActivation,
|
||||
// TODO Remove the PNI capability entirely on or after 2024-05-14
|
||||
boolean pni) {
|
||||
// TODO Remove the PNI and PNP capabilities entirely on or after 2024-05-18
|
||||
boolean pni,
|
||||
boolean pnp,
|
||||
// TODO Remove the giftBadges capability on or after 2024-05-26
|
||||
boolean giftBadges) {
|
||||
|
||||
public static UserCapabilities createForAccount(final Account account) {
|
||||
return new UserCapabilities(account.isPaymentActivationSupported(), true);
|
||||
return new UserCapabilities(account.isPaymentActivationSupported(), true, true, true);
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.grpc.Server;
|
||||
|
||||
public class GrpcServerManagedWrapper implements Managed {
|
||||
|
||||
private final Server server;
|
||||
|
||||
public GrpcServerManagedWrapper(final Server server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws IOException {
|
||||
server.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
try {
|
||||
server.shutdown().awaitTermination(5, TimeUnit.MINUTES);
|
||||
} catch (InterruptedException e) {
|
||||
server.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.southernstorm.noise.protocol.HandshakeState;
|
||||
import io.netty.buffer.ByteBufUtil;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
|
||||
import io.netty.util.internal.EmptyArrays;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.ShortBufferException;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
|
||||
/**
|
||||
* An abstract base class for XX- and NX-patterned Noise responder handshake handlers.
|
||||
*
|
||||
* @see <a href="https://noiseprotocol.org/noise.html">The Noise Protocol Framework</a>
|
||||
*/
|
||||
abstract class AbstractNoiseHandshakeHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final ECKeyPair ecKeyPair;
|
||||
private final byte[] publicKeySignature;
|
||||
|
||||
private final HandshakeState handshakeState;
|
||||
|
||||
private static final int EXPECTED_EPHEMERAL_KEY_MESSAGE_LENGTH = 32;
|
||||
|
||||
/**
|
||||
* Constructs a new Noise handler with the given static server keys and static public key signature. The static public
|
||||
* key must be signed by a trusted root private key whose public key is known to and trusted by authenticating
|
||||
* clients.
|
||||
*
|
||||
* @param noiseProtocolName the name of the Noise protocol implemented by this handshake handler
|
||||
* @param ecKeyPair the static key pair for this server
|
||||
* @param publicKeySignature an Ed25519 signature of the raw bytes of the static public key
|
||||
*/
|
||||
AbstractNoiseHandshakeHandler(final String noiseProtocolName,
|
||||
final ECKeyPair ecKeyPair,
|
||||
final byte[] publicKeySignature) {
|
||||
|
||||
this.ecKeyPair = ecKeyPair;
|
||||
this.publicKeySignature = publicKeySignature;
|
||||
|
||||
try {
|
||||
this.handshakeState = new HandshakeState(noiseProtocolName, HandshakeState.RESPONDER);
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Unsupported Noise algorithm: " + noiseProtocolName, e);
|
||||
}
|
||||
}
|
||||
|
||||
protected HandshakeState getHandshakeState() {
|
||||
return handshakeState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an initial ephemeral key message from a client, advancing the handshake state and sending the server's
|
||||
* static keys to the client. Both XX and NX patterns begin with a client sending its ephemeral key to the server.
|
||||
* Clients must not include an additional payload with their ephemeral key message. The server's reply contains its
|
||||
* static keys along with an Ed25519 signature of its public static key by a trusted root key.
|
||||
*
|
||||
* @param context the channel handler context for this message
|
||||
* @param frame the websocket frame containing the ephemeral key message
|
||||
*
|
||||
* @throws NoiseHandshakeException if the ephemeral key message from the client was not of the expected size or if a
|
||||
* general Noise encryption error occurred
|
||||
*/
|
||||
protected void handleEphemeralKeyMessage(final ChannelHandlerContext context, final BinaryWebSocketFrame frame)
|
||||
throws NoiseHandshakeException {
|
||||
|
||||
if (frame.content().readableBytes() != EXPECTED_EPHEMERAL_KEY_MESSAGE_LENGTH) {
|
||||
throw new NoiseHandshakeException("Unexpected ephemeral key message length");
|
||||
}
|
||||
|
||||
// Cryptographically initializing a handshake is expensive, and so we defer it until we're confident the client is
|
||||
// making a good-faith effort to perform a handshake (i.e. now). Noise-java in particular will derive a public key
|
||||
// from the supplied private key (and will in fact overwrite any previously-set public key when setting a private
|
||||
// key), so we just set the private key here.
|
||||
handshakeState.getLocalKeyPair().setPrivateKey(ecKeyPair.getPrivateKey().serialize(), 0);
|
||||
handshakeState.start();
|
||||
|
||||
// The initial message from the client should just include a plaintext ephemeral key with no payload. The frame is
|
||||
// coming off the wire and so will be in a direct buffer that doesn't have a backing array.
|
||||
final byte[] ephemeralKeyMessage = ByteBufUtil.getBytes(frame.content());
|
||||
frame.content().readBytes(ephemeralKeyMessage);
|
||||
|
||||
try {
|
||||
handshakeState.readMessage(ephemeralKeyMessage, 0, ephemeralKeyMessage.length, EmptyArrays.EMPTY_BYTES, 0);
|
||||
} catch (final ShortBufferException e) {
|
||||
// This should never happen since we're checking the length of the frame up front
|
||||
throw new NoiseHandshakeException("Unexpected client payload");
|
||||
} catch (final BadPaddingException e) {
|
||||
// It turns out this should basically never happen because (a) we're not using padding and (b) the "bad AEAD tag"
|
||||
// subclass of a bad padding exception can only happen if we have some AD to check, which we don't for an
|
||||
// ephemeral-key-only message
|
||||
throw new NoiseHandshakeException("Invalid keys");
|
||||
}
|
||||
|
||||
// Send our key material and public key signature back to the client; this buffer will include:
|
||||
//
|
||||
// - A 32-byte plaintext ephemeral key
|
||||
// - A 32-byte encrypted static key
|
||||
// - A 16-byte AEAD tag for the static key
|
||||
// - The public key signature payload
|
||||
// - A 16-byte AEAD tag for the payload
|
||||
final byte[] keyMaterial = new byte[32 + 32 + 16 + publicKeySignature.length + 16];
|
||||
|
||||
try {
|
||||
handshakeState.writeMessage(keyMaterial, 0, publicKeySignature, 0, publicKeySignature.length);
|
||||
|
||||
context.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(keyMaterial)))
|
||||
.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
|
||||
} catch (final ShortBufferException e) {
|
||||
// This should never happen for messages of known length that we control
|
||||
throw new AssertionError("Key material buffer was too short for message", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlerRemoved(final ChannelHandlerContext context) {
|
||||
handshakeState.destroy();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
|
||||
|
||||
enum ApplicationWebSocketCloseReason {
|
||||
NOISE_HANDSHAKE_ERROR(4001),
|
||||
CLIENT_AUTHENTICATION_ERROR(4002),
|
||||
NOISE_ENCRYPTION_ERROR(4003),
|
||||
REAUTHENTICATION_REQUIRED(4004);
|
||||
|
||||
private final int statusCode;
|
||||
|
||||
ApplicationWebSocketCloseReason(final int statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
WebSocketCloseStatus toWebSocketCloseStatus(final String reason) {
|
||||
return new WebSocketCloseStatus(statusCode, reason);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
/**
|
||||
* Indicates that an attempt to authenticate a remote client failed for some reason.
|
||||
*/
|
||||
class ClientAuthenticationException extends Exception {
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* An error handler serves as a general backstop for exceptions elsewhere in the pipeline. If the client has completed a
|
||||
* WebSocket handshake, the error handler will send appropriate WebSocket closure codes to the client in an attempt to
|
||||
* identify the problem. If the client has not completed a WebSocket handshake, the handler simply closes the
|
||||
* connection.
|
||||
*/
|
||||
class ErrorHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private boolean websocketHandshakeComplete = false;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ErrorHandler.class);
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception {
|
||||
if (event instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
|
||||
setWebsocketHandshakeComplete();
|
||||
}
|
||||
|
||||
context.fireUserEventTriggered(event);
|
||||
}
|
||||
|
||||
protected void setWebsocketHandshakeComplete() {
|
||||
this.websocketHandshakeComplete = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
|
||||
if (websocketHandshakeComplete) {
|
||||
final WebSocketCloseStatus webSocketCloseStatus = switch (cause) {
|
||||
case NoiseHandshakeException e -> ApplicationWebSocketCloseReason.NOISE_HANDSHAKE_ERROR.toWebSocketCloseStatus(e.getMessage());
|
||||
case ClientAuthenticationException ignored -> ApplicationWebSocketCloseReason.CLIENT_AUTHENTICATION_ERROR.toWebSocketCloseStatus("Not authenticated");
|
||||
case BadPaddingException ignored -> ApplicationWebSocketCloseReason.NOISE_ENCRYPTION_ERROR.toWebSocketCloseStatus("Noise encryption error");
|
||||
default -> {
|
||||
log.warn("An unexpected exception reached the end of the pipeline", cause);
|
||||
yield WebSocketCloseStatus.INTERNAL_SERVER_ERROR;
|
||||
}
|
||||
};
|
||||
|
||||
context.writeAndFlush(new CloseWebSocketFrame(webSocketCloseStatus))
|
||||
.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
|
||||
} else {
|
||||
// We haven't completed a websocket handshake, so we can't really communicate errors in a semantically-meaningful
|
||||
// way; just close the connection instead.
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* An "establish local connection" handler waits for a Noise handshake to complete upstream in the pipeline, buffering
|
||||
* any inbound messages until the connection is fully-established, and then opens a proxy connection to a local gRPC
|
||||
* server.
|
||||
*/
|
||||
class EstablishLocalGrpcConnectionHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final LocalAddress authenticatedGrpcServerAddress;
|
||||
private final LocalAddress anonymousGrpcServerAddress;
|
||||
private final List<Object> pendingReads = new ArrayList<>();
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EstablishLocalGrpcConnectionHandler.class);
|
||||
|
||||
public EstablishLocalGrpcConnectionHandler(final LocalAddress authenticatedGrpcServerAddress,
|
||||
final LocalAddress anonymousGrpcServerAddress) {
|
||||
|
||||
this.authenticatedGrpcServerAddress = authenticatedGrpcServerAddress;
|
||||
this.anonymousGrpcServerAddress = anonymousGrpcServerAddress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) {
|
||||
pendingReads.add(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(final ChannelHandlerContext remoteChannelContext, final Object event) throws Exception {
|
||||
if (event instanceof NoiseHandshakeCompleteEvent noiseHandshakeCompleteEvent) {
|
||||
// We assume that we'll only get a completed handshake event if the handshake met all authentication requirements
|
||||
// for the requested service. If the handshake doesn't have an authenticated device, we assume we're trying to
|
||||
// connect to the anonymous service. If it does have an authenticated device, we assume we're aiming for the
|
||||
// authenticated service.
|
||||
final LocalAddress grpcServerAddress = noiseHandshakeCompleteEvent.authenticatedDevice().isPresent()
|
||||
? authenticatedGrpcServerAddress
|
||||
: anonymousGrpcServerAddress;
|
||||
|
||||
new Bootstrap()
|
||||
.remoteAddress(grpcServerAddress)
|
||||
// TODO Set local address
|
||||
.channel(LocalChannel.class)
|
||||
.group(remoteChannelContext.channel().eventLoop())
|
||||
.handler(new ChannelInitializer<LocalChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final LocalChannel localChannel) {
|
||||
localChannel.pipeline().addLast(new ProxyHandler(remoteChannelContext.channel()));
|
||||
}
|
||||
})
|
||||
.connect()
|
||||
.addListener((ChannelFutureListener) future -> {
|
||||
if (future.isSuccess()) {
|
||||
// Close the local connection if the remote channel closes and vice versa
|
||||
remoteChannelContext.channel().closeFuture().addListener(closeFuture -> future.channel().close());
|
||||
future.channel().closeFuture().addListener(closeFuture ->
|
||||
remoteChannelContext.write(new CloseWebSocketFrame(WebSocketCloseStatus.SERVICE_RESTART)));
|
||||
|
||||
remoteChannelContext.pipeline()
|
||||
.addAfter(remoteChannelContext.name(), null, new ProxyHandler(future.channel()));
|
||||
|
||||
// Flush any buffered reads we accumulated while waiting to open the connection
|
||||
pendingReads.forEach(remoteChannelContext::fireChannelRead);
|
||||
pendingReads.clear();
|
||||
|
||||
remoteChannelContext.pipeline().remove(EstablishLocalGrpcConnectionHandler.this);
|
||||
} else {
|
||||
log.warn("Failed to establish local connection to gRPC server", future.cause());
|
||||
remoteChannelContext.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
remoteChannelContext.fireUserEventTriggered(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlerRemoved(final ChannelHandlerContext context) {
|
||||
pendingReads.forEach(ReferenceCountUtil::release);
|
||||
pendingReads.clear();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
|
||||
/**
|
||||
* A wrapper for a Netty {@link DefaultEventLoopGroup} that implements Dropwizard's {@link Managed} interface, allowing
|
||||
* Dropwizard to manage the lifecycle of the event loop group.
|
||||
*/
|
||||
public class ManagedDefaultEventLoopGroup extends DefaultEventLoopGroup implements Managed {
|
||||
|
||||
@Override
|
||||
public void stop() throws InterruptedException {
|
||||
this.shutdownGracefully().await();
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.ServerBuilder;
|
||||
import io.grpc.netty.NettyServerBuilder;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* A managed, local gRPC server configures and wraps a gRPC {@link Server} that listens on a Netty {@link LocalAddress}
|
||||
* and whose lifecycle is managed by Dropwizard via the {@link Managed} interface.
|
||||
*/
|
||||
public abstract class ManagedLocalGrpcServer implements Managed {
|
||||
|
||||
private final Server server;
|
||||
|
||||
public ManagedLocalGrpcServer(final LocalAddress localAddress,
|
||||
final DefaultEventLoopGroup eventLoopGroup) {
|
||||
|
||||
final ServerBuilder<?> serverBuilder = NettyServerBuilder.forAddress(localAddress)
|
||||
.channelType(LocalServerChannel.class)
|
||||
.bossEventLoopGroup(eventLoopGroup)
|
||||
.workerEventLoopGroup(eventLoopGroup);
|
||||
|
||||
configureServer(serverBuilder);
|
||||
|
||||
server = serverBuilder.build();
|
||||
}
|
||||
|
||||
protected abstract void configureServer(final ServerBuilder<?> serverBuilder);
|
||||
|
||||
@Override
|
||||
public void start() throws IOException {
|
||||
server.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
try {
|
||||
server.shutdown().awaitTermination(5, TimeUnit.MINUTES);
|
||||
} catch (final InterruptedException e) {
|
||||
server.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* An event that indicates that a Noise handshake has completed, possibly authenticating a caller in the process.
|
||||
*
|
||||
* @param authenticatedDevice the device authenticated as part of the handshake, or empty if the handshake was not of a
|
||||
* type that performs authentication
|
||||
*/
|
||||
record NoiseHandshakeCompleteEvent(Optional<AuthenticatedDevice> authenticatedDevice) {
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
/**
|
||||
* Indicates that some problem occurred while completing a Noise handshake (e.g. an unexpected message size/format or
|
||||
* a general encryption error).
|
||||
*/
|
||||
class NoiseHandshakeException extends Exception {
|
||||
|
||||
public NoiseHandshakeException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
|
||||
import java.util.Optional;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
|
||||
/**
|
||||
* A Noise NX handler handles the responder side of a Noise NX handshake.
|
||||
*/
|
||||
class NoiseNXHandshakeHandler extends AbstractNoiseHandshakeHandler {
|
||||
|
||||
static final String NOISE_PROTOCOL_NAME = "Noise_NX_25519_ChaChaPoly_BLAKE2b";
|
||||
|
||||
NoiseNXHandshakeHandler(final ECKeyPair ecKeyPair, final byte[] publicKeySignature) {
|
||||
super(NOISE_PROTOCOL_NAME, ecKeyPair, publicKeySignature);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
|
||||
if (message instanceof BinaryWebSocketFrame frame) {
|
||||
try {
|
||||
handleEphemeralKeyMessage(context, frame);
|
||||
} finally {
|
||||
frame.release();
|
||||
}
|
||||
|
||||
// All we need to do is accept the client's ephemeral key and send our own static keys; after that, we can consider
|
||||
// the handshake complete
|
||||
context.fireUserEventTriggered(new NoiseHandshakeCompleteEvent(Optional.empty()));
|
||||
context.pipeline().replace(NoiseNXHandshakeHandler.this, null, new NoiseStreamHandler(getHandshakeState().split()));
|
||||
} else {
|
||||
// Anything except binary WebSocket frames should have been filtered out of the pipeline by now; treat this as an
|
||||
// error
|
||||
ReferenceCountUtil.release(message);
|
||||
throw new IllegalArgumentException("Unexpected message in pipeline: " + message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.southernstorm.noise.protocol.CipherState;
|
||||
import com.southernstorm.noise.protocol.CipherStatePair;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.ByteBufUtil;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelDuplexHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelPromise;
|
||||
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.ShortBufferException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* A Noise stream handler manages a bidirectional Noise session after a handshake has completed.
|
||||
*/
|
||||
class NoiseStreamHandler extends ChannelDuplexHandler {
|
||||
|
||||
private final CipherStatePair cipherStatePair;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(NoiseStreamHandler.class);
|
||||
|
||||
NoiseStreamHandler(CipherStatePair cipherStatePair) {
|
||||
this.cipherStatePair = cipherStatePair;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message)
|
||||
throws ShortBufferException, BadPaddingException {
|
||||
|
||||
if (message instanceof BinaryWebSocketFrame frame) {
|
||||
try {
|
||||
final CipherState cipherState = cipherStatePair.getReceiver();
|
||||
|
||||
// We've read this frame off the wire, and so it's most likely a direct buffer that's not backed by an array.
|
||||
// We'll need to copy it to a heap buffer.
|
||||
final byte[] noiseBuffer = ByteBufUtil.getBytes(frame.content());
|
||||
|
||||
// Overwrite the ciphertext with the plaintext to avoid an extra allocation for a dedicated plaintext buffer
|
||||
final int plaintextLength = cipherState.decryptWithAd(null, noiseBuffer, 0, noiseBuffer, 0, noiseBuffer.length);
|
||||
|
||||
context.fireChannelRead(Unpooled.wrappedBuffer(noiseBuffer, 0, plaintextLength));
|
||||
} finally {
|
||||
frame.release();
|
||||
}
|
||||
} else {
|
||||
// Anything except binary WebSocket frames should have been filtered out of the pipeline by now; treat this as an
|
||||
// error
|
||||
ReferenceCountUtil.release(message);
|
||||
throw new IllegalArgumentException("Unexpected message in pipeline: " + message);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) throws Exception {
|
||||
if (message instanceof ByteBuf plaintext) {
|
||||
try {
|
||||
// TODO Buffer/consolidate Noise writes to avoid sending a bazillion tiny (or empty) frames
|
||||
final CipherState cipherState = cipherStatePair.getSender();
|
||||
final int plaintextLength = plaintext.readableBytes();
|
||||
|
||||
// We've read these bytes from a local connection; although that likely means they're backed by a heap array, the
|
||||
// buffer is read-only and won't grant us access to the underlying array. Instead, we need to copy the bytes to a
|
||||
// mutable array. We also want to encrypt in place, so we allocate enough extra space for the trailing MAC.
|
||||
final byte[] noiseBuffer = new byte[plaintext.readableBytes() + cipherState.getMACLength()];
|
||||
plaintext.readBytes(noiseBuffer, 0, plaintext.readableBytes());
|
||||
|
||||
// Overwrite the plaintext with the ciphertext to avoid an extra allocation for a dedicated ciphertext buffer
|
||||
cipherState.encryptWithAd(null, noiseBuffer, 0, noiseBuffer, 0, plaintextLength);
|
||||
|
||||
context.write(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(noiseBuffer)), promise);
|
||||
} finally {
|
||||
plaintext.release();
|
||||
}
|
||||
} else {
|
||||
if (!(message instanceof WebSocketFrame)) {
|
||||
// Downstream handlers may write WebSocket frames that don't need to be encrypted (e.g. "close" frames that
|
||||
// get issued in response to exceptions)
|
||||
log.warn("Unexpected object in pipeline: {}", message);
|
||||
}
|
||||
|
||||
context.write(message, promise);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlerRemoved(final ChannelHandlerContext context) {
|
||||
cipherStatePair.destroy();
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.southernstorm.noise.protocol.HandshakeState;
|
||||
import io.netty.buffer.ByteBufUtil;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.ShortBufferException;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
/**
|
||||
* A Noise XX handler handles the responder side of a Noise XX handshake. This implementation expects clients to send
|
||||
* identifying information (an account identifier and device ID) as an additional payload when sending its static key
|
||||
* material. It compares the static public key against the stored public key for the identified device asynchronously,
|
||||
* buffering traffic from the client until the authentication check completes.
|
||||
*/
|
||||
class NoiseXXHandshakeHandler extends AbstractNoiseHandshakeHandler {
|
||||
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
|
||||
private AuthenticationState authenticationState = AuthenticationState.GET_EPHEMERAL_KEY;
|
||||
|
||||
private final List<BinaryWebSocketFrame> pendingInboundFrames = new ArrayList<>();
|
||||
|
||||
static final String NOISE_PROTOCOL_NAME = "Noise_XX_25519_ChaChaPoly_BLAKE2b";
|
||||
|
||||
// When the client sends its static key message, we expect:
|
||||
//
|
||||
// - A 32-byte encrypted static public key
|
||||
// - A 16-byte AEAD tag for the static key
|
||||
// - 17 bytes of identity data in the message payload (a UUID and a one-byte device ID)
|
||||
// - A 16-byte AEAD tag for the identity payload
|
||||
private static final int EXPECTED_CLIENT_STATIC_KEY_MESSAGE_LENGTH = 81;
|
||||
|
||||
private enum AuthenticationState {
|
||||
GET_EPHEMERAL_KEY,
|
||||
GET_STATIC_KEY,
|
||||
CHECK_PUBLIC_KEY,
|
||||
ERROR
|
||||
}
|
||||
|
||||
public NoiseXXHandshakeHandler(final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final ECKeyPair ecKeyPair,
|
||||
final byte[] publicKeySignature) {
|
||||
|
||||
super(NOISE_PROTOCOL_NAME, ecKeyPair, publicKeySignature);
|
||||
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
|
||||
if (message instanceof BinaryWebSocketFrame frame) {
|
||||
try {
|
||||
switch (authenticationState) {
|
||||
case GET_EPHEMERAL_KEY -> {
|
||||
try {
|
||||
handleEphemeralKeyMessage(context, frame);
|
||||
authenticationState = AuthenticationState.GET_STATIC_KEY;
|
||||
} finally {
|
||||
frame.release();
|
||||
}
|
||||
}
|
||||
case GET_STATIC_KEY -> {
|
||||
try {
|
||||
handleStaticKey(context, frame);
|
||||
authenticationState = AuthenticationState.CHECK_PUBLIC_KEY;
|
||||
} finally {
|
||||
frame.release();
|
||||
}
|
||||
}
|
||||
case CHECK_PUBLIC_KEY -> {
|
||||
// Buffer any inbound traffic until we've finished checking the client's public key
|
||||
pendingInboundFrames.add(frame);
|
||||
}
|
||||
case ERROR -> {
|
||||
// If authentication has failed for any reason, just discard inbound traffic until the channel closes
|
||||
frame.release();
|
||||
}
|
||||
}
|
||||
} catch (final ShortBufferException e) {
|
||||
authenticationState = AuthenticationState.ERROR;
|
||||
throw new NoiseHandshakeException("Unexpected payload length");
|
||||
} catch (final BadPaddingException e) {
|
||||
authenticationState = AuthenticationState.ERROR;
|
||||
throw new ClientAuthenticationException();
|
||||
}
|
||||
} else {
|
||||
// Anything except binary WebSocket frames should have been filtered out of the pipeline by now; treat this as an
|
||||
// error
|
||||
ReferenceCountUtil.release(message);
|
||||
throw new IllegalArgumentException("Unexpected message in pipeline: " + message);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleStaticKey(final ChannelHandlerContext context, final BinaryWebSocketFrame frame)
|
||||
throws NoiseHandshakeException, ShortBufferException, BadPaddingException {
|
||||
|
||||
if (frame.content().readableBytes() != EXPECTED_CLIENT_STATIC_KEY_MESSAGE_LENGTH) {
|
||||
throw new NoiseHandshakeException("Unexpected client static key message length");
|
||||
}
|
||||
|
||||
final HandshakeState handshakeState = getHandshakeState();
|
||||
|
||||
// The websocket frame will have come right off the wire, and so needs to be copied from a non-array-backed direct
|
||||
// buffer into a heap buffer.
|
||||
final byte[] staticKeyAndClientIdentityMessage = ByteBufUtil.getBytes(frame.content());
|
||||
|
||||
// The payload from the client should be a UUID (16 bytes) followed by a device ID (1 byte)
|
||||
final byte[] payload = new byte[17];
|
||||
|
||||
final UUID accountIdentifier;
|
||||
final byte deviceId;
|
||||
|
||||
final int payloadBytesRead = handshakeState.readMessage(staticKeyAndClientIdentityMessage,
|
||||
0, staticKeyAndClientIdentityMessage.length, payload, 0);
|
||||
|
||||
if (payloadBytesRead != 17) {
|
||||
throw new NoiseHandshakeException("Unexpected identity payload length");
|
||||
}
|
||||
|
||||
try {
|
||||
accountIdentifier = UUIDUtil.fromBytes(payload, 0);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new NoiseHandshakeException("Could not parse account identifier");
|
||||
}
|
||||
|
||||
deviceId = payload[16];
|
||||
|
||||
// Verify the identity of the caller by comparing the submitted static public key against the stored public key for
|
||||
// the identified device
|
||||
clientPublicKeysManager.findPublicKey(accountIdentifier, deviceId)
|
||||
.whenCompleteAsync((maybePublicKey, throwable) -> maybePublicKey.ifPresentOrElse(storedPublicKey -> {
|
||||
final byte[] publicKeyFromClient = new byte[handshakeState.getRemotePublicKey().getPublicKeyLength()];
|
||||
handshakeState.getRemotePublicKey().getPublicKey(publicKeyFromClient, 0);
|
||||
|
||||
if (MessageDigest.isEqual(publicKeyFromClient, storedPublicKey.getPublicKeyBytes())) {
|
||||
context.fireUserEventTriggered(new NoiseHandshakeCompleteEvent(
|
||||
Optional.of(new AuthenticatedDevice(accountIdentifier, deviceId))));
|
||||
|
||||
context.pipeline().addAfter(context.name(), null, new NoiseStreamHandler(handshakeState.split()));
|
||||
|
||||
// Flush any buffered reads
|
||||
pendingInboundFrames.forEach(context::fireChannelRead);
|
||||
pendingInboundFrames.clear();
|
||||
|
||||
context.pipeline().remove(NoiseXXHandshakeHandler.this);
|
||||
} else {
|
||||
// We found a key, but it doesn't match what the caller submitted
|
||||
context.fireExceptionCaught(new ClientAuthenticationException());
|
||||
authenticationState = AuthenticationState.ERROR;
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
// We couldn't find a key for the identified account/device
|
||||
context.fireExceptionCaught(new ClientAuthenticationException());
|
||||
authenticationState = AuthenticationState.ERROR;
|
||||
}),
|
||||
context.executor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlerRemoved(final ChannelHandlerContext context) {
|
||||
super.handlerRemoved(context);
|
||||
|
||||
pendingInboundFrames.forEach(BinaryWebSocketFrame::release);
|
||||
pendingInboundFrames.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
/**
|
||||
* A proxy handler writes all data read from one channel to another peer channel.
|
||||
*/
|
||||
class ProxyHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final Channel peerChannel;
|
||||
|
||||
public ProxyHandler(final Channel peerChannel) {
|
||||
this.peerChannel = peerChannel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) {
|
||||
peerChannel.writeAndFlush(message)
|
||||
.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
|
||||
/**
|
||||
* A "reject unsupported message" handler closes the channel if it receives messages it does not know how to process.
|
||||
*/
|
||||
public class RejectUnsupportedMessagesHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
|
||||
if (message instanceof final WebSocketFrame webSocketFrame) {
|
||||
if (webSocketFrame instanceof final TextWebSocketFrame textWebSocketFrame) {
|
||||
try {
|
||||
context.writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.INVALID_MESSAGE_TYPE));
|
||||
} finally {
|
||||
textWebSocketFrame.release();
|
||||
}
|
||||
} else {
|
||||
// Allow all other types of WebSocket frames
|
||||
context.fireChannelRead(webSocketFrame);
|
||||
}
|
||||
} else {
|
||||
// Discard anything that's not a WebSocket frame
|
||||
ReferenceCountUtil.release(message);
|
||||
context.writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.INVALID_MESSAGE_TYPE));
|
||||
}
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.http.DefaultFullHttpResponse;
|
||||
import io.netty.handler.codec.http.FullHttpRequest;
|
||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||
import io.netty.handler.codec.http.HttpHeaderValues;
|
||||
import io.netty.handler.codec.http.HttpMethod;
|
||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
|
||||
/**
|
||||
* A WebSocket opening handshake handler serves as the "front door" for the WebSocket/Noise tunnel and gracefully
|
||||
* rejects requests for anything other than a WebSocket connection to a known endpoint.
|
||||
*/
|
||||
class WebSocketOpeningHandshakeHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final String authenticatedPath;
|
||||
private final String anonymousPath;
|
||||
|
||||
WebSocketOpeningHandshakeHandler(final String authenticatedPath, final String anonymousPath) {
|
||||
this.authenticatedPath = authenticatedPath;
|
||||
this.anonymousPath = anonymousPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {
|
||||
if (message instanceof FullHttpRequest request) {
|
||||
boolean shouldReleaseRequest = true;
|
||||
|
||||
try {
|
||||
if (request.decoderResult().isSuccess()) {
|
||||
if (HttpMethod.GET.equals(request.method())) {
|
||||
if (authenticatedPath.equals(request.uri()) || anonymousPath.equals(request.uri())) {
|
||||
if (request.headers().contains(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true)) {
|
||||
// Pass the request along to the websocket handshake handler and remove ourselves from the pipeline
|
||||
shouldReleaseRequest = false;
|
||||
|
||||
context.fireChannelRead(request);
|
||||
context.pipeline().remove(this);
|
||||
} else {
|
||||
closeConnectionWithStatus(context, request, HttpResponseStatus.UPGRADE_REQUIRED);
|
||||
}
|
||||
} else {
|
||||
closeConnectionWithStatus(context, request, HttpResponseStatus.NOT_FOUND);
|
||||
}
|
||||
} else {
|
||||
closeConnectionWithStatus(context, request, HttpResponseStatus.METHOD_NOT_ALLOWED);
|
||||
}
|
||||
} else {
|
||||
closeConnectionWithStatus(context, request, HttpResponseStatus.BAD_REQUEST);
|
||||
}
|
||||
} finally {
|
||||
if (shouldReleaseRequest) {
|
||||
request.release();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Anything except HTTP requests should have been filtered out of the pipeline by now; treat this as an error
|
||||
ReferenceCountUtil.release(message);
|
||||
throw new IllegalArgumentException("Unexpected message in pipeline: " + message);
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeConnectionWithStatus(final ChannelHandlerContext context,
|
||||
final FullHttpRequest request,
|
||||
final HttpResponseStatus status) {
|
||||
|
||||
context.writeAndFlush(new DefaultFullHttpResponse(request.protocolVersion(), status))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
|
||||
|
||||
/**
|
||||
* A WebSocket handshake listener waits for a WebSocket handshake to complete, then replaces itself with the appropriate
|
||||
* Noise handshake handler for the requested path.
|
||||
*/
|
||||
class WebsocketHandshakeCompleteListener extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
|
||||
private final ECKeyPair ecKeyPair;
|
||||
private final byte[] publicKeySignature;
|
||||
|
||||
WebsocketHandshakeCompleteListener(final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final ECKeyPair ecKeyPair,
|
||||
final byte[] publicKeySignature) {
|
||||
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
this.ecKeyPair = ecKeyPair;
|
||||
this.publicKeySignature = publicKeySignature;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
|
||||
if (event instanceof WebSocketServerProtocolHandler.HandshakeComplete handshakeCompleteEvent) {
|
||||
final ChannelHandler noiseHandshakeHandler = switch (handshakeCompleteEvent.requestUri()) {
|
||||
case WebsocketNoiseTunnelServer.AUTHENTICATED_SERVICE_PATH ->
|
||||
new NoiseXXHandshakeHandler(clientPublicKeysManager, ecKeyPair, publicKeySignature);
|
||||
|
||||
case WebsocketNoiseTunnelServer.ANONYMOUS_SERVICE_PATH ->
|
||||
new NoiseNXHandshakeHandler(ecKeyPair, publicKeySignature);
|
||||
|
||||
default -> {
|
||||
// The HttpHandler should have caught all of these cases already; we'll consider it an internal error if
|
||||
// something slipped through.
|
||||
throw new IllegalArgumentException("Unexpected URI: " + handshakeCompleteEvent.requestUri());
|
||||
}
|
||||
};
|
||||
|
||||
context.pipeline().replace(WebsocketHandshakeCompleteListener.this, null, noiseHandshakeHandler);
|
||||
}
|
||||
|
||||
context.fireUserEventTriggered(event);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.southernstorm.noise.protocol.Noise;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.ServerSocketChannel;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.http.HttpObjectAggregator;
|
||||
import io.netty.handler.codec.http.HttpServerCodec;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
||||
import io.netty.handler.ssl.ClientAuth;
|
||||
import io.netty.handler.ssl.OpenSsl;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslContextBuilder;
|
||||
import io.netty.handler.ssl.SslProtocols;
|
||||
import io.netty.handler.ssl.SslProvider;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.concurrent.Executor;
|
||||
import javax.net.ssl.SSLException;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
|
||||
|
||||
/**
|
||||
* A WebSocket/Noise tunnel server accepts traffic from the public internet (in the form of Noise packets framed by
|
||||
* binary WebSocket frames) and passes it through to a local gRPC server.
|
||||
*/
|
||||
public class WebsocketNoiseTunnelServer implements Managed {
|
||||
|
||||
private final ServerBootstrap bootstrap;
|
||||
private ServerSocketChannel channel;
|
||||
|
||||
static final String AUTHENTICATED_SERVICE_PATH = "/authenticated";
|
||||
static final String ANONYMOUS_SERVICE_PATH = "/anonymous";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WebsocketNoiseTunnelServer.class);
|
||||
|
||||
public WebsocketNoiseTunnelServer(final int websocketPort,
|
||||
final X509Certificate[] tlsCertificateChain,
|
||||
final PrivateKey tlsPrivateKey,
|
||||
final NioEventLoopGroup eventLoopGroup,
|
||||
final Executor delegatedTaskExecutor,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final ECKeyPair ecKeyPair,
|
||||
final byte[] publicKeySignature,
|
||||
final LocalAddress authenticatedGrpcServerAddress,
|
||||
final LocalAddress anonymousGrpcServerAddress) throws SSLException {
|
||||
|
||||
final SslProvider sslProvider;
|
||||
|
||||
if (OpenSsl.isAvailable()) {
|
||||
log.info("Native OpenSSL provider is available; will use native provider");
|
||||
sslProvider = SslProvider.OPENSSL;
|
||||
} else {
|
||||
log.info("No native SSL provider available; will use JDK provider");
|
||||
sslProvider = SslProvider.JDK;
|
||||
}
|
||||
|
||||
final SslContext sslContext = SslContextBuilder.forServer(tlsPrivateKey, tlsCertificateChain)
|
||||
.clientAuth(ClientAuth.NONE)
|
||||
.protocols(SslProtocols.TLS_v1_3)
|
||||
.sslProvider(sslProvider)
|
||||
.build();
|
||||
|
||||
this.bootstrap = new ServerBootstrap()
|
||||
.group(eventLoopGroup)
|
||||
.channel(NioServerSocketChannel.class)
|
||||
.localAddress(websocketPort)
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel socketChannel) {
|
||||
socketChannel.pipeline()
|
||||
.addLast(sslContext.newHandler(socketChannel.alloc(), delegatedTaskExecutor))
|
||||
.addLast(new HttpServerCodec())
|
||||
.addLast(new HttpObjectAggregator(Noise.MAX_PACKET_LEN))
|
||||
// The WebSocket opening handshake handler will remove itself from the pipeline once it has received a valid WebSocket upgrade
|
||||
// request and passed it down the pipeline
|
||||
.addLast(new WebSocketOpeningHandshakeHandler(AUTHENTICATED_SERVICE_PATH, ANONYMOUS_SERVICE_PATH))
|
||||
.addLast(new WebSocketServerProtocolHandler("/", true))
|
||||
.addLast(new RejectUnsupportedMessagesHandler())
|
||||
// The WebSocket handshake complete listener will replace itself with an appropriate Noise handshake handler once
|
||||
// a WebSocket handshake has been completed
|
||||
.addLast(new WebsocketHandshakeCompleteListener(clientPublicKeysManager, ecKeyPair, publicKeySignature))
|
||||
// This handler will open a local connection to the appropriate gRPC server and install a ProxyHandler
|
||||
// once the Noise handshake has completed
|
||||
.addLast(new EstablishLocalGrpcConnectionHandler(authenticatedGrpcServerAddress, anonymousGrpcServerAddress))
|
||||
.addLast(new ErrorHandler());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
InetSocketAddress getLocalAddress() {
|
||||
return channel.localAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws InterruptedException {
|
||||
channel = (ServerSocketChannel) bootstrap.bind().await().channel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() throws InterruptedException {
|
||||
if (channel != null) {
|
||||
channel.close().await();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -31,7 +31,7 @@ public class CardinalityEstimator {
|
||||
this.period = period;
|
||||
Metrics.gauge(
|
||||
MetricsUtil.name(getClass(), "unique"),
|
||||
Tags.of("name", name),
|
||||
Tags.of("metricName", name),
|
||||
this,
|
||||
obj -> obj.uniqueElementCount);
|
||||
}
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ public class StaticRateLimiter implements RateLimiter {
|
||||
this.validateScript = requireNonNull(validateScript);
|
||||
this.cacheCluster = requireNonNull(cacheCluster);
|
||||
this.clock = requireNonNull(clock);
|
||||
this.counter = Metrics.counter(MetricsUtil.name(getClass(), "exceeded"), "name", name);
|
||||
this.counter = Metrics.counter(MetricsUtil.name(getClass(), "exceeded"), "rateLimiterName", name);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
|
||||
+3
-4
@@ -5,22 +5,21 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
|
||||
import java.lang.management.BufferPoolMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.List;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class BufferPoolGauges {
|
||||
|
||||
private BufferPoolGauges() {}
|
||||
|
||||
public static void registerMetrics() {
|
||||
for (final BufferPoolMXBean bufferPoolMXBean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
|
||||
final List<Tag> tags = List.of(Tag.of("name", bufferPoolMXBean.getName()));
|
||||
final List<Tag> tags = List.of(Tag.of("bufferPoolName", bufferPoolMXBean.getName()));
|
||||
|
||||
Metrics.gauge(name(BufferPoolGauges.class, "count"), tags, bufferPoolMXBean, BufferPoolMXBean::getCount);
|
||||
Metrics.gauge(name(BufferPoolGauges.class, "memory_used"), tags, bufferPoolMXBean, BufferPoolMXBean::getMemoryUsed);
|
||||
|
||||
+3
-4
@@ -5,22 +5,21 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
|
||||
import java.lang.management.GarbageCollectorMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.List;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class GarbageCollectionGauges {
|
||||
|
||||
private GarbageCollectionGauges() {}
|
||||
|
||||
public static void registerMetrics() {
|
||||
for (final GarbageCollectorMXBean garbageCollectorMXBean : ManagementFactory.getGarbageCollectorMXBeans()) {
|
||||
final List<Tag> tags = List.of(Tag.of("name", garbageCollectorMXBean.getName()));
|
||||
final List<Tag> tags = List.of(Tag.of("memoryManagerName", garbageCollectorMXBean.getName()));
|
||||
|
||||
Metrics.gauge(name(GarbageCollectionGauges.class, "collection_count"), tags, garbageCollectorMXBean, GarbageCollectorMXBean::getCollectionCount);
|
||||
Metrics.gauge(name(GarbageCollectionGauges.class, "collection_time"), tags, garbageCollectorMXBean, GarbageCollectorMXBean::getCollectionTime);
|
||||
|
||||
+6
@@ -13,12 +13,18 @@ import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
|
||||
/**
|
||||
* Delegates request events to a listener that captures and reports request-level metrics.
|
||||
*
|
||||
* @see MetricsHttpChannelListener
|
||||
* @see MetricsRequestEventListener
|
||||
*/
|
||||
public class MetricsApplicationEventListener implements ApplicationEventListener {
|
||||
|
||||
private final MetricsRequestEventListener metricsRequestEventListener;
|
||||
|
||||
public MetricsApplicationEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
if (trafficSource == TrafficSource.HTTP) {
|
||||
throw new IllegalArgumentException("Use " + MetricsHttpChannelListener.class.getName() + " for HTTP traffic");
|
||||
}
|
||||
this.metricsRequestEventListener = new MetricsRequestEventListener(trafficSource, clientReleaseManager);
|
||||
}
|
||||
|
||||
|
||||
+3
-5
@@ -5,8 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
@@ -57,9 +55,9 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final Set<String> servletPaths;
|
||||
|
||||
public static final String REQUEST_COUNTER_NAME = name(MetricsHttpChannelListener.class, "request");
|
||||
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = name(MetricsHttpChannelListener.class,
|
||||
"requestByVersion");
|
||||
// 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 URI_INFO_PROPERTY_NAME = MetricsHttpChannelListener.class.getName() + ".uriInfo";
|
||||
|
||||
|
||||
+15
-1
@@ -10,6 +10,7 @@ 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.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
@@ -167,7 +168,20 @@ public class PushNotificationManager {
|
||||
private void handleDeviceUnregistered(final Account account, final Device device) {
|
||||
if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
if (device.getUninstalledFeedbackTimestamp() == 0) {
|
||||
accountsManager.updateDevice(account, device.getId(), d ->
|
||||
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
|
||||
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
|
||||
// updating an uninstalled feedback timestamp though.
|
||||
final Optional<Account> rereadAccount = accountsManager.getByAccountIdentifier(account.getUuid());
|
||||
if (rereadAccount.isEmpty()) {
|
||||
// don't bother adding the uninstalled timestamp, the account is gone
|
||||
return;
|
||||
}
|
||||
final Optional<Device> rereadDevice = rereadAccount.get().getDevice(device.getId());
|
||||
if (rereadDevice.map(Device::getUninstalledFeedbackTimestamp).orElse(-1L) != 0) {
|
||||
// don't bother adding the uninstalled timestamp, the device is gone or already updated
|
||||
return;
|
||||
}
|
||||
accountsManager.updateDevice(rereadAccount.get(), device.getId(), d ->
|
||||
d.setUninstalledFeedbackTimestamp(Util.todayInMillis()));
|
||||
}
|
||||
} else {
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ public class FaultTolerantPubSubConnection<K, V> {
|
||||
|
||||
this.pubSubConnection.setNodeMessagePropagation(true);
|
||||
|
||||
this.executeTimer = Metrics.timer(name(getClass(), "execute"), "name", name + "-pubsub");
|
||||
this.executeTimer = Metrics.timer(name(getClass(), "execute"), "clusterName", name + "-pubsub");
|
||||
|
||||
CircuitBreakerUtil.registerMetrics(circuitBreaker, FaultTolerantPubSubConnection.class);
|
||||
}
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface ChallengeConstraintChecker {
|
||||
|
||||
record ChallengeConstraints(boolean pushPermitted, Optional<Float> captchaScoreThreshold) {}
|
||||
|
||||
/**
|
||||
* Retrieve constraints for captcha and push challenges
|
||||
*
|
||||
* @param authenticatedAccount The authenticated account attempting to request or solve a challenge
|
||||
* @return ChallengeConstraints indicating what constraints should be applied to challenges
|
||||
*/
|
||||
ChallengeConstraints challengeConstraints(ContainerRequestContext requestContext, Account authenticatedAccount);
|
||||
|
||||
static ChallengeConstraintChecker noop() {
|
||||
return (account, ctx) -> new ChallengeConstraints(true, Optional.empty());
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Indicates that a parameter should be parsed from a {@link org.glassfish.jersey.server.ContainerRequest}
|
||||
*/
|
||||
@Target({ElementType.PARAMETER, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Extract {
|
||||
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import javax.ws.rs.NameBinding;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* A name-binding annotation that associates {@link SpamFilter}s with resource methods.
|
||||
*/
|
||||
@NameBinding
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
public @interface FilterSpam {
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* A PushChallengeConfig may be provided by an upstream request filter. If request contains a
|
||||
* property for PROPERTY_NAME it can be forwarded to a downstream filter to indicate whether
|
||||
* push-token challenges can be used in place of captchas when evaluating whether a request should
|
||||
* be allowed to continue.
|
||||
*/
|
||||
public class PushChallengeConfig {
|
||||
private static final Logger logger = LoggerFactory.getLogger(PushChallengeConfig.class);
|
||||
|
||||
public static final String PROPERTY_NAME = "pushChallengePermitted";
|
||||
|
||||
/**
|
||||
* A score threshold in the range [0, 1.0]
|
||||
*/
|
||||
private final boolean pushPermitted;
|
||||
|
||||
/**
|
||||
* Extract an optional score threshold parameter provided by an upstream request filter
|
||||
*/
|
||||
public PushChallengeConfig(final ContainerRequest containerRequest) {
|
||||
this.pushPermitted = Optional
|
||||
.ofNullable(containerRequest.getProperty(PROPERTY_NAME))
|
||||
.filter(obj -> obj instanceof Boolean)
|
||||
.map(obj -> (Boolean) obj)
|
||||
.orElse(true); // not a typo! true is the default
|
||||
}
|
||||
|
||||
public boolean pushPermitted() {
|
||||
return pushPermitted;
|
||||
}
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.util.function.Function;
|
||||
import javax.inject.Singleton;
|
||||
import javax.ws.rs.core.Feature;
|
||||
import javax.ws.rs.core.FeatureContext;
|
||||
import org.glassfish.jersey.internal.inject.AbstractBinder;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.glassfish.jersey.server.model.Parameter;
|
||||
import org.glassfish.jersey.server.spi.internal.ValueParamProvider;
|
||||
|
||||
/**
|
||||
* Parses a {@link PushChallengeConfig} out of a {@link ContainerRequest} to provide to jersey resources.
|
||||
*
|
||||
* A request filter may enrich a ContainerRequest with a PushChallengeConfig by providing a float
|
||||
* property with the name {@link PushChallengeConfig#PROPERTY_NAME}. This indicates whether push
|
||||
* challenges may be considered when evaluating whether a request should proceed.
|
||||
*
|
||||
* A resource can consume a PushChallengeConfig with by annotating a PushChallengeConfig parameter with {@link Extract}
|
||||
*/
|
||||
public class PushChallengeConfigProvider implements ValueParamProvider {
|
||||
|
||||
/**
|
||||
* Configures the PushChallengeConfigProvider
|
||||
*/
|
||||
public static class PushChallengeConfigFeature implements Feature {
|
||||
@Override
|
||||
public boolean configure(FeatureContext context) {
|
||||
context.register(new AbstractBinder() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(PushChallengeConfigProvider.class)
|
||||
.to(ValueParamProvider.class)
|
||||
.in(Singleton.class);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<ContainerRequest, ?> getValueProvider(final Parameter parameter) {
|
||||
if (parameter.getRawType().equals(PushChallengeConfig.class)
|
||||
&& parameter.isAnnotationPresent(Extract.class)) {
|
||||
return PushChallengeConfig::new;
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public PriorityType getPriority() {
|
||||
return Priority.HIGH;
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public interface RegistrationFraudChecker {
|
||||
|
||||
record VerificationCheck(Optional<VerificationSession> updatedSession, Optional<Float> scoreThreshold) {}
|
||||
|
||||
/**
|
||||
* Determine if a registration attempt is suspicious
|
||||
*
|
||||
* @param requestContext The request context for an update verification session attempt
|
||||
* @param verificationSession The target verification session
|
||||
* @param e164 The target phone number
|
||||
* @param request The information to add to the verification session
|
||||
* @return A SessionUpdate including updates to the verification session that should be persisted to the caller along
|
||||
* with other constraints to enforce when evaluating the UpdateVerificationSessionRequest.
|
||||
*/
|
||||
VerificationCheck checkVerificationAttempt(
|
||||
final ContainerRequestContext requestContext,
|
||||
final VerificationSession verificationSession,
|
||||
final String e164,
|
||||
final UpdateVerificationSessionRequest request);
|
||||
|
||||
static RegistrationFraudChecker noop() {
|
||||
return (ignoredContext, ignoredSession, ignoredE164, ignoredRequest) -> new VerificationCheck(
|
||||
Optional.empty(),
|
||||
Optional.empty());
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A ScoreThreshold may be provided by an upstream request filter. If request contains a property for
|
||||
* {@link #PROPERTY_NAME} it can be forwarded to a downstream filter to indicate it can use a more or less strict
|
||||
* score threshold when evaluating whether a request should be allowed to continue.
|
||||
*/
|
||||
public class ScoreThreshold {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ScoreThreshold.class);
|
||||
|
||||
public static final String PROPERTY_NAME = "scoreThreshold";
|
||||
|
||||
/**
|
||||
* A score threshold in the range [0, 1.0]
|
||||
*/
|
||||
private final Optional<Float> scoreThreshold;
|
||||
|
||||
/**
|
||||
* Extract an optional score threshold parameter provided by an upstream request filter
|
||||
*/
|
||||
public ScoreThreshold(final ContainerRequest containerRequest) {
|
||||
this.scoreThreshold = Optional
|
||||
.ofNullable(containerRequest.getProperty(PROPERTY_NAME))
|
||||
.flatMap(obj -> {
|
||||
if (obj instanceof Float f) {
|
||||
return Optional.of(f);
|
||||
}
|
||||
logger.warn("invalid format for filter provided score threshold {}", obj);
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<Float> getScoreThreshold() {
|
||||
return this.scoreThreshold;
|
||||
}
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.util.function.Function;
|
||||
import javax.inject.Singleton;
|
||||
import javax.ws.rs.core.Feature;
|
||||
import javax.ws.rs.core.FeatureContext;
|
||||
import org.glassfish.jersey.internal.inject.AbstractBinder;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.glassfish.jersey.server.model.Parameter;
|
||||
import org.glassfish.jersey.server.spi.internal.ValueParamProvider;
|
||||
|
||||
/**
|
||||
* Parses a {@link ScoreThreshold} out of a {@link ContainerRequest} to provide to jersey resources.
|
||||
* <p>
|
||||
* A request filter may enrich a ContainerRequest with a scoreThreshold by providing a float property with the name
|
||||
* {@link ScoreThreshold#PROPERTY_NAME}. This indicates the desired scoreThreshold to use when evaluating whether a
|
||||
* request should proceed.
|
||||
* <p>
|
||||
* A resource can consume a ScoreThreshold with by annotating a ScoreThreshold parameter with {@link Extract}
|
||||
*/
|
||||
public class ScoreThresholdProvider implements ValueParamProvider {
|
||||
|
||||
/**
|
||||
* Configures the ScoreThresholdProvider
|
||||
*/
|
||||
public static class ScoreThresholdFeature implements Feature {
|
||||
|
||||
@Override
|
||||
public boolean configure(FeatureContext context) {
|
||||
context.register(new AbstractBinder() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(ScoreThresholdProvider.class)
|
||||
.to(ValueParamProvider.class)
|
||||
.in(Singleton.class);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<ContainerRequest, ?> getValueProvider(final Parameter parameter) {
|
||||
if (parameter.getRawType().equals(ScoreThreshold.class)
|
||||
&& parameter.isAnnotationPresent(Extract.class)) {
|
||||
return ScoreThreshold::new;
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public PriorityType getPriority() {
|
||||
return Priority.HIGH;
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A SenderOverride may be provided by an upstream request filter. If request contains a property for
|
||||
* {@link #SMS_SENDER_OVERRIDE_PROPERTY_NAME} or {@link #VOICE_SENDER_OVERRIDE_PROPERTY_NAME} it can be
|
||||
* forwarded to a downstream filter to indicate a specific sender should be used when sending verification codes.
|
||||
*/
|
||||
public class SenderOverride {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SenderOverride.class);
|
||||
public static final String SMS_SENDER_OVERRIDE_PROPERTY_NAME = "smsSenderOverride";
|
||||
public static final String VOICE_SENDER_OVERRIDE_PROPERTY_NAME = "voiceSenderOverride";
|
||||
|
||||
/**
|
||||
* The name of the sender to use to deliver a verification code via SMS
|
||||
*/
|
||||
private final Optional<String> smsSenderOverride;
|
||||
|
||||
/**
|
||||
* The name of the sender to use to deliver a verification code via voice
|
||||
*/
|
||||
private final Optional<String> voiceSenderOverride;
|
||||
|
||||
public SenderOverride(final ContainerRequest containerRequest) {
|
||||
this.smsSenderOverride = parse(String.class, SMS_SENDER_OVERRIDE_PROPERTY_NAME, containerRequest);
|
||||
this.voiceSenderOverride = parse(String.class, VOICE_SENDER_OVERRIDE_PROPERTY_NAME, containerRequest);
|
||||
}
|
||||
|
||||
private static <T> Optional<T> parse(Class<T> type, final String propertyName,
|
||||
final ContainerRequest containerRequest) {
|
||||
return Optional
|
||||
.ofNullable(containerRequest.getProperty(propertyName))
|
||||
.flatMap(obj -> {
|
||||
if (type.isInstance(obj)) {
|
||||
return Optional.of(type.cast(obj));
|
||||
}
|
||||
logger.warn("invalid format for filter provided property {}: {}", propertyName, obj);
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public Optional<String> getSmsSenderOverride() {
|
||||
return smsSenderOverride;
|
||||
}
|
||||
|
||||
public Optional<String> getVoiceSenderOverride() {
|
||||
return voiceSenderOverride;
|
||||
}
|
||||
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import java.util.function.Function;
|
||||
import javax.inject.Singleton;
|
||||
import javax.ws.rs.core.Feature;
|
||||
import javax.ws.rs.core.FeatureContext;
|
||||
import org.glassfish.jersey.internal.inject.AbstractBinder;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.glassfish.jersey.server.model.Parameter;
|
||||
import org.glassfish.jersey.server.spi.internal.ValueParamProvider;
|
||||
|
||||
/**
|
||||
* Parses a {@link SenderOverride} out of a {@link ContainerRequest} to provide to jersey resources.
|
||||
* <p>
|
||||
* A request filter may enrich a ContainerRequest with senderOverrides by providing a string property names defined in
|
||||
* {@link SenderOverride}. This indicates the desired senderOverride to use when sending verification codes.
|
||||
* <p>
|
||||
* A resource can consume a SenderOverride with by annotating a SenderOverride parameter with {@link Extract}
|
||||
*/
|
||||
public class SenderOverrideProvider implements ValueParamProvider {
|
||||
|
||||
/**
|
||||
* Configures the SenderOverrideProvider
|
||||
*/
|
||||
public static class SenderOverrideFeature implements Feature {
|
||||
|
||||
@Override
|
||||
public boolean configure(FeatureContext context) {
|
||||
context.register(new AbstractBinder() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(SenderOverrideProvider.class)
|
||||
.to(ValueParamProvider.class)
|
||||
.in(Singleton.class);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<ContainerRequest, ?> getValueProvider(final Parameter parameter) {
|
||||
if (parameter.getRawType().equals(SenderOverride.class)
|
||||
&& parameter.isAnnotationPresent(Extract.class)) {
|
||||
return SenderOverride::new;
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public PriorityType getPriority() {
|
||||
return Priority.HIGH;
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,14 @@ import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* A spam filter is a {@link ContainerRequestFilter} that filters requests to endpoints to detect and respond to
|
||||
* patterns of spam and fraud.
|
||||
* A spam filter provides various checkers and listeners to detect and respond to patterns of spam and fraud.
|
||||
* <p/>
|
||||
* Spam filters are managed components that are generally loaded dynamically via a {@link java.util.ServiceLoader}.
|
||||
* Their {@link #configure(String)} method will be called prior to be adding to the server's pool of {@link Managed}
|
||||
* objects.
|
||||
* <p/>
|
||||
* Spam filters must be annotated with {@link FilterSpam}, a name binding annotation that restricts the endpoints to
|
||||
* which the filter may apply.
|
||||
*/
|
||||
public interface SpamFilter extends ContainerRequestFilter, Managed {
|
||||
public interface SpamFilter extends Managed {
|
||||
|
||||
/**
|
||||
* Configures this spam filter. This method will be called before the filter is added to the server's pool of managed
|
||||
@@ -64,4 +61,19 @@ public interface SpamFilter extends ContainerRequestFilter, Managed {
|
||||
* @return a {@link SpamChecker} controlled by the spam filter
|
||||
*/
|
||||
SpamChecker getSpamChecker();
|
||||
|
||||
/**
|
||||
* Return a checker that will be called to check registration attempts
|
||||
*
|
||||
* @return a {@link RegistrationFraudChecker} controlled by the spam filter
|
||||
*/
|
||||
RegistrationFraudChecker getRegistrationFraudChecker();
|
||||
|
||||
/**
|
||||
* Return a checker that will be called to determine what constraints should be applied
|
||||
* when a user requests or solves a challenge (captchas, push challenges, etc).
|
||||
*
|
||||
* @return a {@link ChallengeConstraintChecker} controlled by the spam filter
|
||||
*/
|
||||
ChallengeConstraintChecker getChallengeConstraintChecker();
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
|
||||
public class AccountPrincipalSupplier implements PrincipalSupplier<AuthenticatedAccount> {
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
public AccountPrincipalSupplier(final AccountsManager accountsManager) {
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthenticatedAccount refresh(final AuthenticatedAccount oldAccount) {
|
||||
final Account account = accountsManager.getByAccountIdentifier(oldAccount.getAccount().getUuid())
|
||||
.orElseThrow(() -> new RefreshingAccountNotFoundException("Could not find account"));
|
||||
final Device device = account.getDevice(oldAccount.getAuthenticatedDevice().getId())
|
||||
.orElseThrow(() -> new RefreshingAccountNotFoundException("Could not find device"));
|
||||
return new AuthenticatedAccount(account, device);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthenticatedAccount deepCopy(final AuthenticatedAccount authenticatedAccount) {
|
||||
final Account cloned = AccountUtil.cloneAccountAsNotStale(authenticatedAccount.getAccount());
|
||||
return new AuthenticatedAccount(
|
||||
cloned,
|
||||
cloned.getDevice(authenticatedAccount.getAuthenticatedDevice().getId())
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"Could not find device from a clone of an account where the device was present")));
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,12 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
import java.io.IOException;
|
||||
|
||||
class AccountUtil {
|
||||
public class AccountUtil {
|
||||
|
||||
static Account cloneAccountAsNotStale(final Account account) {
|
||||
try {
|
||||
|
||||
@@ -455,7 +455,8 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
/**
|
||||
* Reserve a username hash under the account UUID
|
||||
* @return a future that completes once the username hash has been reserved; may fail with an
|
||||
* {@link ContestedOptimisticLockException} if the account has been updated or
|
||||
* {@link ContestedOptimisticLockException} if the account has been updated or there are concurrent updates to the
|
||||
* account or constraint records, and with an
|
||||
* {@link UsernameHashNotAvailableException} if the username was taken by someone else
|
||||
*/
|
||||
public CompletableFuture<Void> reserveUsernameHash(
|
||||
@@ -523,11 +524,12 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException e) {
|
||||
// If the constraint table update failed the condition check, the username's taken and we should stop
|
||||
// trying. However if it was only in the accounts table that the condition check update failed, it's an
|
||||
// optimistic locking failure (the account was concurrently updated) and we should try again.
|
||||
// trying. However, if the accounts table fails the conditional check or
|
||||
// either table was concurrently updated, it's an optimistic locking failure and we should try again.
|
||||
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
|
||||
throw ExceptionUtils.wrap(new UsernameHashNotAvailableException());
|
||||
} else if (conditionalCheckFailed(e.cancellationReasons().get(1))) {
|
||||
} else if (conditionalCheckFailed(e.cancellationReasons().get(1)) ||
|
||||
e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
}
|
||||
@@ -551,8 +553,10 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
*
|
||||
* @param account to update
|
||||
* @param usernameHash believed to be available
|
||||
* @param encryptedUsername the encrypted form of the previously reserved username; used for the username link
|
||||
* @return a future that completes once the username hash has been confirmed; may fail with an
|
||||
* {@link ContestedOptimisticLockException} if the account has been updated or
|
||||
* {@link ContestedOptimisticLockException} if the account has been updated or there are concurrent updates to the
|
||||
* account or constraint records, and with an
|
||||
* {@link UsernameHashNotAvailableException} if the username was taken by someone else
|
||||
*/
|
||||
public CompletableFuture<Void> confirmUsernameHash(final Account account, final byte[] usernameHash, @Nullable final byte[] encryptedUsername) {
|
||||
@@ -585,13 +589,14 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException e) {
|
||||
// If the constraint table update failed the condition check, the username's taken and we should stop
|
||||
// trying. However if it was only in the accounts table that the condition check update failed, it's an
|
||||
// optimistic locking failure (the account was concurrently updated) and we should try again.
|
||||
// trying. However, if the accounts table fails the conditional check or
|
||||
// either table was concurrently updated, it's an optimistic locking failure and we should try again.
|
||||
// NOTE: the fixed indices here must be kept in sync with the creation of the TransactWriteItems in
|
||||
// buildConfirmUsernameHashRequest!
|
||||
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
|
||||
throw ExceptionUtils.wrap(new UsernameHashNotAvailableException());
|
||||
} else if (conditionalCheckFailed(e.cancellationReasons().get(1))) {
|
||||
} else if (conditionalCheckFailed(e.cancellationReasons().get(1)) ||
|
||||
e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
}
|
||||
@@ -690,6 +695,14 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the username hash and link from the given account
|
||||
*
|
||||
* @param account to update
|
||||
* @return a future that completes once the username data has been cleared;
|
||||
* it can fail with a {@link ContestedOptimisticLockException} if there are concurrent updates
|
||||
* to the account or username constraint records.
|
||||
*/
|
||||
public CompletableFuture<Void> clearUsernameHash(final Account account) {
|
||||
return account.getUsernameHash().map(usernameHash -> {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
@@ -714,8 +727,9 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
account.setVersion(account.getVersion() + 1);
|
||||
})
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException transactionCanceledException) {
|
||||
if (conditionalCheckFailed(transactionCanceledException.cancellationReasons().get(0))) {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException e) {
|
||||
if (conditionalCheckFailed(e.cancellationReasons().get(0)) ||
|
||||
e.cancellationReasons().stream().anyMatch(Accounts::isTransactionConflict)) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
}
|
||||
@@ -1371,4 +1385,8 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
private static boolean conditionalCheckFailed(final CancellationReason reason) {
|
||||
return CONDITIONAL_CHECK_FAILED.equals(reason.code());
|
||||
}
|
||||
|
||||
private static boolean isTransactionConflict(final CancellationReason reason) {
|
||||
return TRANSACTION_CONFLICT.equals(reason.code());
|
||||
}
|
||||
}
|
||||
+20
-2
@@ -571,6 +571,12 @@ public class AccountsManager {
|
||||
() -> accounts.getByAccountIdentifierAsync(account.getUuid()).thenApply(Optional::orElseThrow),
|
||||
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR,
|
||||
MAX_UPDATE_ATTEMPTS))
|
||||
.whenComplete((updatedAccount, throwable) -> {
|
||||
if (throwable == null) {
|
||||
// Make a best effort to clear any stale data that may have been cached while this operation was in progress
|
||||
redisDeleteAsync(updatedAccount);
|
||||
}
|
||||
})
|
||||
.thenApply(updatedAccount -> new UsernameReservation(updatedAccount, reservedUsernameHash.get()));
|
||||
}
|
||||
|
||||
@@ -623,7 +629,13 @@ public class AccountsManager {
|
||||
() -> accounts.getByAccountIdentifierAsync(account.getUuid()).thenApply(Optional::orElseThrow),
|
||||
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR,
|
||||
MAX_UPDATE_ATTEMPTS
|
||||
));
|
||||
))
|
||||
.whenComplete((updatedAccount, throwable) -> {
|
||||
if (throwable == null) {
|
||||
// Make a best effort to clear any stale data that may have been cached while this operation was in progress
|
||||
redisDeleteAsync(updatedAccount);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Account> clearUsernameHash(final Account account) {
|
||||
@@ -634,7 +646,13 @@ public class AccountsManager {
|
||||
accounts::clearUsernameHash,
|
||||
() -> accounts.getByAccountIdentifierAsync(account.getUuid()).thenApply(Optional::orElseThrow),
|
||||
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR,
|
||||
MAX_UPDATE_ATTEMPTS));
|
||||
MAX_UPDATE_ATTEMPTS))
|
||||
.whenComplete((updatedAccount, throwable) -> {
|
||||
if (throwable == null) {
|
||||
// Make a best effort to clear any stale data that may have been cached while this operation was in progress
|
||||
redisDeleteAsync(updatedAccount);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Account update(Account account, Consumer<Account> updater) {
|
||||
|
||||
@@ -106,8 +106,7 @@ public class KeysManager {
|
||||
.orElseGet(() -> pqLastResortKeys.find(identifier, deviceId)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Optional<KEMSignedPreKey>> getLastResort(final UUID identifier, final byte deviceId) {
|
||||
public CompletableFuture<Optional<KEMSignedPreKey>> getLastResort(final UUID identifier, final byte deviceId) {
|
||||
return pqLastResortKeys.find(identifier, deviceId);
|
||||
}
|
||||
|
||||
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
public class RefreshingAccountAndDeviceSupplier implements Supplier<Pair<Account, Device>> {
|
||||
|
||||
private Account account;
|
||||
private Device device;
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
public RefreshingAccountAndDeviceSupplier(Account account, byte deviceId, AccountsManager accountsManager) {
|
||||
this.account = account;
|
||||
this.device = account.getDevice(deviceId)
|
||||
.orElseThrow(() -> new RefreshingAccountAndDeviceNotFoundException("Could not find device"));
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pair<Account, Device> get() {
|
||||
if (account.isStale()) {
|
||||
account = accountsManager.getByAccountIdentifier(account.getUuid())
|
||||
.orElseThrow(() -> new RuntimeException("Could not find account"));
|
||||
device = account.getDevice(device.getId())
|
||||
.orElseThrow(() -> new RefreshingAccountAndDeviceNotFoundException("Could not find device"));
|
||||
}
|
||||
|
||||
return new Pair<>(account, device);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -5,9 +5,9 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class RefreshingAccountAndDeviceNotFoundException extends RuntimeException {
|
||||
public class RefreshingAccountNotFoundException extends RuntimeException {
|
||||
|
||||
public RefreshingAccountAndDeviceNotFoundException(final String message) {
|
||||
public RefreshingAccountNotFoundException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
abstract class AbstractPublicKeyDeserializer<K> extends JsonDeserializer<K> {
|
||||
|
||||
private final String invalidKeyCounterName = MetricsUtil.name(getClass(), "invalidKey");
|
||||
|
||||
private static final String REASON_TAG_NAME = "reason";
|
||||
|
||||
@Override
|
||||
public K deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
|
||||
final byte[] publicKeyBytes;
|
||||
|
||||
try {
|
||||
publicKeyBytes = Base64.getDecoder().decode(parser.getValueAsString());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
Metrics.counter(invalidKeyCounterName, REASON_TAG_NAME, "illegal-base64").increment();
|
||||
throw new JsonParseException(parser, "Could not parse public key as a base64-encoded value", e);
|
||||
}
|
||||
|
||||
if (publicKeyBytes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return deserializePublicKey(publicKeyBytes);
|
||||
} catch (final InvalidKeyException e) {
|
||||
Metrics.counter(invalidKeyCounterName, REASON_TAG_NAME, "invalid-key").increment();
|
||||
throw new JsonParseException(parser, "Could not interpret key bytes as a public key", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract K deserializePublicKey(final byte[] publicKeyBytes) throws InvalidKeyException;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
abstract class AbstractPublicKeySerializer<K> extends JsonSerializer<K> {
|
||||
|
||||
@Override
|
||||
public void serialize(final K publicKey,
|
||||
final JsonGenerator jsonGenerator,
|
||||
final SerializerProvider serializerProvider) throws IOException {
|
||||
|
||||
jsonGenerator.writeString(Base64.getEncoder().encodeToString(serializePublicKey(publicKey)));
|
||||
}
|
||||
|
||||
protected abstract byte[] serializePublicKey(final K publicKey);
|
||||
}
|
||||
@@ -20,22 +20,22 @@ public class CircuitBreakerUtil {
|
||||
private static final String CIRCUIT_BREAKER_STATE_GAUGE_NAME = name(CircuitBreakerUtil.class, "breaker", "state");
|
||||
private static final String RETRY_CALL_COUNTER_NAME = name(CircuitBreakerUtil.class, "retry", "call");
|
||||
|
||||
private static final String NAME_TAG_NAME = "name";
|
||||
private static final String BREAKER_NAME_TAG_NAME = "breakerName";
|
||||
private static final String OUTCOME_TAG_NAME = "outcome";
|
||||
|
||||
public static void registerMetrics(CircuitBreaker circuitBreaker, Class<?> clazz) {
|
||||
final String breakerName = clazz.getSimpleName() + "/" + circuitBreaker.getName();
|
||||
|
||||
final Counter successCounter = Metrics.counter(CIRCUIT_BREAKER_CALL_COUNTER_NAME,
|
||||
NAME_TAG_NAME, breakerName,
|
||||
BREAKER_NAME_TAG_NAME, breakerName,
|
||||
OUTCOME_TAG_NAME, "success");
|
||||
|
||||
final Counter failureCounter = Metrics.counter(CIRCUIT_BREAKER_CALL_COUNTER_NAME,
|
||||
NAME_TAG_NAME, breakerName,
|
||||
BREAKER_NAME_TAG_NAME, breakerName,
|
||||
OUTCOME_TAG_NAME, "failure");
|
||||
|
||||
final Counter unpermittedCounter = Metrics.counter(CIRCUIT_BREAKER_CALL_COUNTER_NAME,
|
||||
NAME_TAG_NAME, breakerName,
|
||||
BREAKER_NAME_TAG_NAME, breakerName,
|
||||
OUTCOME_TAG_NAME, "unpermitted");
|
||||
|
||||
circuitBreaker.getEventPublisher().onSuccess(event -> {
|
||||
@@ -51,7 +51,7 @@ public class CircuitBreakerUtil {
|
||||
});
|
||||
|
||||
Metrics.gauge(CIRCUIT_BREAKER_STATE_GAUGE_NAME,
|
||||
Tags.of(Tag.of(NAME_TAG_NAME, circuitBreaker.getName())),
|
||||
Tags.of(Tag.of(BREAKER_NAME_TAG_NAME, circuitBreaker.getName())),
|
||||
circuitBreaker, breaker -> breaker.getState().getOrder());
|
||||
}
|
||||
|
||||
@@ -59,19 +59,19 @@ public class CircuitBreakerUtil {
|
||||
final String retryName = clazz.getSimpleName() + "/" + retry.getName();
|
||||
|
||||
final Counter successCounter = Metrics.counter(RETRY_CALL_COUNTER_NAME,
|
||||
NAME_TAG_NAME, retryName,
|
||||
BREAKER_NAME_TAG_NAME, retryName,
|
||||
OUTCOME_TAG_NAME, "success");
|
||||
|
||||
final Counter retryCounter = Metrics.counter(RETRY_CALL_COUNTER_NAME,
|
||||
NAME_TAG_NAME, retryName,
|
||||
BREAKER_NAME_TAG_NAME, retryName,
|
||||
OUTCOME_TAG_NAME, "retry");
|
||||
|
||||
final Counter errorCounter = Metrics.counter(RETRY_CALL_COUNTER_NAME,
|
||||
NAME_TAG_NAME, retryName,
|
||||
BREAKER_NAME_TAG_NAME, retryName,
|
||||
OUTCOME_TAG_NAME, "error");
|
||||
|
||||
final Counter ignoredErrorCounter = Metrics.counter(RETRY_CALL_COUNTER_NAME,
|
||||
NAME_TAG_NAME, retryName,
|
||||
BREAKER_NAME_TAG_NAME, retryName,
|
||||
OUTCOME_TAG_NAME, "ignored_error");
|
||||
|
||||
retry.getEventPublisher().onSuccess(event -> {
|
||||
|
||||
+6
-45
@@ -5,63 +5,24 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
public class ECPublicKeyAdapter {
|
||||
|
||||
private static final Counter EC_PUBLIC_KEY_WITHOUT_VERSION_BYTE_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(ECPublicKeyAdapter.class, "keyWithoutVersionByte"));
|
||||
|
||||
public static class Serializer extends JsonSerializer<ECPublicKey> {
|
||||
public static class Serializer extends AbstractPublicKeySerializer<ECPublicKey> {
|
||||
|
||||
@Override
|
||||
public void serialize(final ECPublicKey ecPublicKey,
|
||||
final JsonGenerator jsonGenerator,
|
||||
final SerializerProvider serializers) throws IOException {
|
||||
|
||||
jsonGenerator.writeString(Base64.getEncoder().encodeToString(ecPublicKey.serialize()));
|
||||
protected byte[] serializePublicKey(final ECPublicKey publicKey) {
|
||||
return publicKey.serialize();
|
||||
}
|
||||
}
|
||||
|
||||
public static class Deserializer extends JsonDeserializer<ECPublicKey> {
|
||||
public static class Deserializer extends AbstractPublicKeyDeserializer<ECPublicKey> {
|
||||
|
||||
@Override
|
||||
public ECPublicKey deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
|
||||
final byte[] ecPublicKeyBytes;
|
||||
|
||||
try {
|
||||
ecPublicKeyBytes = Base64.getDecoder().decode(parser.getValueAsString());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new JsonParseException(parser, "Could not parse EC public key as a base64-encoded value", e);
|
||||
}
|
||||
|
||||
if (ecPublicKeyBytes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new ECPublicKey(ecPublicKeyBytes);
|
||||
} catch (final InvalidKeyException e) {
|
||||
if (ecPublicKeyBytes.length == ECPublicKey.KEY_SIZE - 1) {
|
||||
EC_PUBLIC_KEY_WITHOUT_VERSION_BYTE_COUNTER.increment();
|
||||
return ECPublicKey.fromPublicKeyBytes(ecPublicKeyBytes);
|
||||
}
|
||||
|
||||
throw new JsonParseException(parser, "Could not interpret identity key bytes as an EC public key", e);
|
||||
}
|
||||
protected ECPublicKey deserializePublicKey(final byte[] publicKeyBytes) throws InvalidKeyException {
|
||||
return new ECPublicKey(publicKeyBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,16 +27,28 @@ public final class HmacUtils {
|
||||
}
|
||||
});
|
||||
|
||||
public static byte[] hmac256(final byte[] key, final byte[] input) {
|
||||
private static Mac initializedThreadLocalMac(final byte[] key) {
|
||||
try {
|
||||
final Mac mac = THREAD_LOCAL_HMAC_SHA_256.get();
|
||||
mac.init(new SecretKeySpec(key, HMAC_SHA_256));
|
||||
return mac.doFinal(input);
|
||||
return mac;
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] hmac256(final byte[] key, final byte[] input) {
|
||||
return initializedThreadLocalMac(key).doFinal(input);
|
||||
}
|
||||
|
||||
public static byte[] hmac256(final byte[] key, final byte[]... inputs) {
|
||||
final Mac mac = initializedThreadLocalMac(key);
|
||||
for (byte[] input : inputs) {
|
||||
mac.update(input);
|
||||
}
|
||||
return mac.doFinal();
|
||||
}
|
||||
|
||||
public static byte[] hmac256(final byte[] key, final String input) {
|
||||
return hmac256(key, input.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
+6
-34
@@ -5,52 +5,24 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
public class KEMPublicKeyAdapter {
|
||||
|
||||
public static class Serializer extends JsonSerializer<KEMPublicKey> {
|
||||
public static class Serializer extends AbstractPublicKeySerializer<KEMPublicKey> {
|
||||
|
||||
@Override
|
||||
public void serialize(final KEMPublicKey kemPublicKey,
|
||||
final JsonGenerator jsonGenerator,
|
||||
final SerializerProvider serializers) throws IOException {
|
||||
|
||||
jsonGenerator.writeString(Base64.getEncoder().encodeToString(kemPublicKey.serialize()));
|
||||
protected byte[] serializePublicKey(final KEMPublicKey publicKey) {
|
||||
return publicKey.serialize();
|
||||
}
|
||||
}
|
||||
|
||||
public static class Deserializer extends JsonDeserializer<KEMPublicKey> {
|
||||
public static class Deserializer extends AbstractPublicKeyDeserializer<KEMPublicKey> {
|
||||
|
||||
@Override
|
||||
public KEMPublicKey deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
|
||||
final byte[] kemPublicKeyBytes;
|
||||
|
||||
try {
|
||||
kemPublicKeyBytes = Base64.getDecoder().decode(parser.getValueAsString());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new JsonParseException(parser, "Could not parse KEM public key as a base64-encoded value", e);
|
||||
}
|
||||
|
||||
if (kemPublicKeyBytes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new KEMPublicKey(kemPublicKeyBytes);
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new JsonParseException(parser, "Could not interpret key bytes as a KEM public key", e);
|
||||
}
|
||||
protected KEMPublicKey deserializePublicKey(final byte[] publicKeyBytes) throws InvalidKeyException {
|
||||
return new KEMPublicKey(publicKeyBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.util;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.nio.BufferUnderflowException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class UUIDUtil {
|
||||
@@ -40,6 +39,10 @@ public final class UUIDUtil {
|
||||
return fromByteBuffer(ByteBuffer.wrap(bytes));
|
||||
}
|
||||
|
||||
public static UUID fromBytes(final byte[] bytes, final int offset) {
|
||||
return fromByteBuffer(ByteBuffer.wrap(bytes, offset, 16));
|
||||
}
|
||||
|
||||
public static UUID fromByteBuffer(final ByteBuffer byteBuffer) {
|
||||
try {
|
||||
final long mostSigBits = byteBuffer.getLong();
|
||||
@@ -52,12 +55,4 @@ public final class UUIDUtil {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was less than 16");
|
||||
}
|
||||
}
|
||||
|
||||
public static Optional<UUID> fromStringSafe(final String uuidString) {
|
||||
try {
|
||||
return Optional.of(UUID.fromString(uuidString));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-19
@@ -11,41 +11,40 @@ import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import org.eclipse.jetty.websocket.api.UpgradeRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
import org.whispersystems.websocket.auth.AuthenticationException;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
|
||||
|
||||
|
||||
public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<AuthenticatedAccount> {
|
||||
|
||||
private static final AuthenticationResult<AuthenticatedAccount> CREDENTIALS_NOT_PRESENTED =
|
||||
new AuthenticationResult<>(Optional.empty(), false);
|
||||
private static final ReusableAuth<AuthenticatedAccount> CREDENTIALS_NOT_PRESENTED = ReusableAuth.anonymous();
|
||||
|
||||
private static final AuthenticationResult<AuthenticatedAccount> INVALID_CREDENTIALS_PRESENTED =
|
||||
new AuthenticationResult<>(Optional.empty(), true);
|
||||
private static final ReusableAuth<AuthenticatedAccount> INVALID_CREDENTIALS_PRESENTED = ReusableAuth.invalid();
|
||||
|
||||
private final AccountAuthenticator accountAuthenticator;
|
||||
private final PrincipalSupplier<AuthenticatedAccount> principalSupplier;
|
||||
|
||||
|
||||
public WebSocketAccountAuthenticator(final AccountAuthenticator accountAuthenticator) {
|
||||
public WebSocketAccountAuthenticator(final AccountAuthenticator accountAuthenticator,
|
||||
final PrincipalSupplier<AuthenticatedAccount> principalSupplier) {
|
||||
this.accountAuthenticator = accountAuthenticator;
|
||||
this.principalSupplier = principalSupplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthenticationResult<AuthenticatedAccount> authenticate(final UpgradeRequest request)
|
||||
public ReusableAuth<AuthenticatedAccount> authenticate(final UpgradeRequest request)
|
||||
throws AuthenticationException {
|
||||
try {
|
||||
final AuthenticationResult<AuthenticatedAccount> authResultFromHeader =
|
||||
authenticatedAccountFromHeaderAuth(request.getHeader(HttpHeaders.AUTHORIZATION));
|
||||
// the logic here is that if the `Authorization` header was set for the request,
|
||||
// it takes the priority and we use the result of the header-based auth
|
||||
// ignoring the result of the query-based auth.
|
||||
if (authResultFromHeader.credentialsPresented()) {
|
||||
return authResultFromHeader;
|
||||
// If the `Authorization` header was set for the request it takes priority, and we use the result of the
|
||||
// header-based auth ignoring the result of the query-based auth.
|
||||
final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (authHeader != null) {
|
||||
return authenticatedAccountFromHeaderAuth(authHeader);
|
||||
}
|
||||
return authenticatedAccountFromQueryParams(request);
|
||||
} catch (final Exception e) {
|
||||
@@ -55,7 +54,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
}
|
||||
}
|
||||
|
||||
private AuthenticationResult<AuthenticatedAccount> authenticatedAccountFromQueryParams(final UpgradeRequest request) {
|
||||
private ReusableAuth<AuthenticatedAccount> authenticatedAccountFromQueryParams(final UpgradeRequest request) {
|
||||
final Map<String, List<String>> parameters = request.getParameterMap();
|
||||
final List<String> usernames = parameters.get("login");
|
||||
final List<String> passwords = parameters.get("password");
|
||||
@@ -65,16 +64,19 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
}
|
||||
final BasicCredentials credentials = new BasicCredentials(usernames.get(0).replace(" ", "+"),
|
||||
passwords.get(0).replace(" ", "+"));
|
||||
return new AuthenticationResult<>(accountAuthenticator.authenticate(credentials), true);
|
||||
return accountAuthenticator.authenticate(credentials)
|
||||
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
|
||||
.orElse(INVALID_CREDENTIALS_PRESENTED);
|
||||
}
|
||||
|
||||
private AuthenticationResult<AuthenticatedAccount> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader)
|
||||
private ReusableAuth<AuthenticatedAccount> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader)
|
||||
throws AuthenticationException {
|
||||
if (authHeader == null) {
|
||||
return CREDENTIALS_NOT_PRESENTED;
|
||||
}
|
||||
return basicCredentialsFromAuthHeader(authHeader)
|
||||
.map(credentials -> new AuthenticationResult<>(accountAuthenticator.authenticate(credentials), true))
|
||||
.flatMap(credentials -> accountAuthenticator.authenticate(credentials))
|
||||
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
|
||||
.orElse(INVALID_CREDENTIALS_PRESENTED);
|
||||
}
|
||||
}
|
||||
-4
@@ -15,7 +15,6 @@ import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -67,9 +66,6 @@ public abstract class AbstractSinglePassCrawlAccountsCommand extends Environment
|
||||
this.namespace = namespace;
|
||||
this.commandDependencies = CommandDependencies.build(getName(), environment, configuration);
|
||||
|
||||
MetricsUtil.configureRegistries(configuration, environment, commandDependencies.dynamicConfigurationManager());
|
||||
|
||||
|
||||
final int segments = Objects.requireNonNull(namespace.getInt(SEGMENT_COUNT));
|
||||
|
||||
logger.info("Crawling accounts with {} segments and {} processors",
|
||||
|
||||
+8
-5
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -71,6 +72,13 @@ record CommandDependencies(
|
||||
|
||||
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
MetricsUtil.configureRegistries(configuration, environment, dynamicConfigurationManager);
|
||||
|
||||
ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster",
|
||||
@@ -103,11 +111,6 @@ record CommandDependencies(
|
||||
ExternalServiceCredentialsGenerator secureValueRecoveryCredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
configuration.getSvr2Configuration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
|
||||
|
||||
+2
-15
@@ -9,14 +9,12 @@ import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.cli.ServerCommand;
|
||||
import io.dropwizard.core.server.DefaultServerFactory;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import java.time.Duration;
|
||||
import io.dropwizard.jetty.HttpsConnectorFactory;
|
||||
import java.time.Duration;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagePersister;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
|
||||
@@ -52,8 +50,6 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
|
||||
final CommandDependencies deps = CommandDependencies.build("message-persister-service", environment, configuration);
|
||||
|
||||
MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager());
|
||||
|
||||
if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) {
|
||||
defaultServerFactory.getApplicationConnectors()
|
||||
.forEach(connectorFactory -> {
|
||||
@@ -63,20 +59,11 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(),
|
||||
configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(),
|
||||
DynamicConfiguration.class);
|
||||
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(), deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.clientPresenceManager(),
|
||||
deps.keysManager(),
|
||||
dynamicConfigurationManager,
|
||||
deps.dynamicConfigurationManager(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(WORKER_COUNT),
|
||||
environment.lifecycle().executorService("messagePersisterUnlinkDeviceExecutor-%d")
|
||||
|
||||
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user