Compare commits

..
28 Commits
Author SHA1 Message Date
Jon Chambers ff7a5f471b Always use "conserve power" priority for challenge notifications 2023-11-21 17:58:32 -05:00
Ravi Khadiwala 42a47406cc Fix platform tag for push challenge metric 2023-11-21 17:57:32 -05:00
Katherine de10b6de7b Add metric to count invalid registration ID when setting account attributes 2023-11-20 14:25:27 -08:00
Chris Eager d6ade0e1ac Send HTTP 408 on idle timeout 2023-11-20 16:24:54 -06:00
Ravi Khadiwala e04b5e5c9f run integration-test job daily at 19:30 UTC 2023-11-20 15:31:45 -06:00
Ravi Khadiwala 15a6c46d47 use a configured number in integration test 2023-11-20 15:02:53 -06:00
Jonathan Klabunde Tomer cb1fc734c2 report exceptions in fanned-out sends of multi-recipient messages 2023-11-20 10:46:26 -08:00
Katherine Yen db7f18aae7 Add missing boolean parameter to getSubscriptionStatus method call 2023-11-16 19:28:10 -05:00
Katherine 7fbc327591 For Braintree, return active subscription status if latest transaction also succeeded 2023-11-16 19:15:46 -05:00
Chris Eager 84b56ae1b2 Upgrade to dropwizard 3.0 2023-11-16 17:57:48 -06:00
Katherine 041aa8639a Enforce story ratelimit 2023-11-16 12:36:43 -05:00
Katherine 216ac72ad0 Use Braintree subscription status alongside transaction status to determine 204 and 402 responses for /v1/subscription/{subscriberId}/receipt_credentials 2023-11-16 12:36:19 -05:00
Jon Chambers c85ddaeb9c Make DynamoDB client connection pool sizes configurable 2023-11-16 12:29:43 -05:00
Jonathan Klabunde Tomer e09dec330a Update to the latest version of the spam filter 2023-11-15 17:34:57 -08:00
Jonathan Klabunde TomerandChris Eager 8f7bae54fe When persisting messages fails due to a full queue in DynamoDB, automatically unlink one device to free up room.
Co-authored-by: Chris Eager <79161849+eager-signal@users.noreply.github.com>
2023-11-15 17:15:17 -08:00
Jon Chambers ce60f13320 Don't track IPv4/IPv6 metrics at the application level
We can measure this at the infrastructure level without observing IPs directly.
2023-11-15 17:18:54 -05:00
Jon Chambers 1ac0140666 Remove a couple of now-unused variables 2023-11-15 17:12:08 -05:00
Jon Chambers 6cc8b147a9 Remove unused X-Forwarded-For parameters 2023-11-15 17:09:47 -05:00
Jon Chambers e078161e2f Consistently use HttpHeaders.X_FORWARDED_FOR 2023-11-15 17:09:36 -05:00
Jonathan Klabunde Tomer 7764185c57 return explicit Response rather than Void from async controllers with no expected body content 2023-11-14 21:57:25 -08:00
Katherine d4ef2adf0a Remove low priority attempt login notification workaround for old iOS clients 2023-11-13 12:06:55 -05:00
Jonathan Klabunde Tomer a83378a44e add an option to replace username ciphertext without rotating the link handle 2023-11-13 09:01:54 -08:00
ravi-signal a4a4204762 Allow re-registered accounts to reclaim their usernames 2023-11-13 10:41:23 -06:00
Jon Chambers acd1140ef6 Make registration challenge APNs payloads "silent" 2023-11-13 08:39:58 -08:00
Jon Chambers fbf71c93ff Make rate limit challenge APNs payloads "silent" 2023-11-13 08:39:58 -08:00
Katherine 38bc0c466a Change sepaMaximumEuros field to number in JSON response 2023-11-10 10:16:03 -08:00
Katherine 71e4351743 Add sepaMaximumEuros field to subscription configuration 2023-11-10 09:13:51 -08:00
Katherine 387e4b94b4 Expand charge object on Stripe subscription to surface charge failure information 2023-11-10 09:12:59 -08:00
89 changed files with 1307 additions and 633 deletions

No files matched your search

+4 -1
View File
@@ -1,6 +1,9 @@
name: Integration Tests
on: [workflow_dispatch]
on:
schedule:
- cron: '30 19 * * MON-FRI'
workflow_dispatch:
jobs:
build:
@@ -133,6 +133,13 @@ public final class Operations {
return user;
}
public record PrescribedVerificationNumber(String number, String verificationCode) {}
public static PrescribedVerificationNumber prescribedVerificationNumber() {
return new PrescribedVerificationNumber(
CONFIG.prescribedRegistrationNumber(),
CONFIG.prescribedRegistrationCode());
}
public static void deleteUser(final TestUser user) {
apiDelete("/v1/accounts/me").authorized(user).executeExpectSuccess();
}
@@ -10,5 +10,7 @@ import org.whispersystems.textsecuregcm.configuration.DynamoDbClientConfiguratio
public record Config(String domain,
String rootCert,
DynamoDbClientConfiguration dynamoDbClientConfiguration,
DynamoDbTables dynamoDbTables) {
DynamoDbTables dynamoDbTables,
String prescribedRegistrationNumber,
String prescribedRegistrationCode) {
}
@@ -19,7 +19,10 @@ public class RegistrationTest {
public void testRegistration() throws Exception {
final UpdateVerificationSessionRequest originalRequest = new UpdateVerificationSessionRequest(
"test", UpdateVerificationSessionRequest.PushTokenType.FCM, null, null, null, null);
final CreateVerificationSessionRequest input = new CreateVerificationSessionRequest("+19995550102", originalRequest);
final Operations.PrescribedVerificationNumber params = Operations.prescribedVerificationNumber();
final CreateVerificationSessionRequest input = new CreateVerificationSessionRequest(params.number(),
originalRequest);
final VerificationSessionResponse verificationSessionResponse = Operations
.apiPost("/v1/verification/session", input)
@@ -46,7 +49,8 @@ public class RegistrationTest {
.executeExpectSuccess(VerificationSessionResponse.class);
// verify code
final SubmitVerificationCodeRequest submitVerificationCodeRequest = new SubmitVerificationCodeRequest("265402");
final SubmitVerificationCodeRequest submitVerificationCodeRequest = new SubmitVerificationCodeRequest(
params.verificationCode());
final VerificationSessionResponse codeVerified = Operations
.apiPut("/v1/verification/session/%s/code".formatted(sessionId), submitVerificationCodeRequest)
.executeExpectSuccess(VerificationSessionResponse.class);
+26 -6
View File
@@ -42,14 +42,18 @@
<braintree.version>3.27.0</braintree.version>
<commons-csv.version>1.10.0</commons-csv.version>
<commons-io.version>2.14.0</commons-io.version>
<dropwizard.version>2.1.9</dropwizard.version>
<dropwizard.version>3.0.4</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
<google-cloud-libraries.version>26.25.0</google-cloud-libraries.version>
<grpc.version>1.58.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.10.1</gson.version>
<jackson.version>2.13.5</jackson.version>
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.16.0</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<junit-pioneer.version>2.1.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>1.9.10</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<lettuce.version>6.2.6.RELEASE</lettuce.version>
@@ -66,7 +70,7 @@
<reactor-bom.version>2022.0.12</reactor-bom.version> <!-- 3.5.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>1.7.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<slf4j.version>1.7.36</slf4j.version>
<slf4j.version>2.0.9</slf4j.version>
<stripe.version>23.10.0</stripe.version>
<swagger.version>2.2.17</swagger.version>
<vavr.version>0.10.4</vavr.version>
@@ -262,6 +266,11 @@
<artifactId>braintree-java</artifactId>
<version>${braintree.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>${jsr305.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
@@ -285,6 +294,16 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
@@ -296,9 +315,10 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.35.1</version>
<groupId>org.wiremock</groupId>
<!-- use standalone until Dropwizard 4 + jakarta.* -->
<artifactId>wiremock-standalone</artifactId>
<version>3.3.1</version>
<scope>test</scope>
<exclusions>
<exclusion>
+1 -1
View File
@@ -342,7 +342,7 @@ subscription: # configuration for Stripe subscriptions
BRAINTREE: plan_example # braintree Plan ID
oneTimeDonations:
sepaMaxTransactionSizeEuros: '10000'
sepaMaximumEuros: '10000'
boost:
level: 1
expiration: P90D
+9 -17
View File
@@ -165,12 +165,6 @@
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-testing</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@@ -195,7 +189,7 @@
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-api</artifactId>
<artifactId>websocket-jetty-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
@@ -297,6 +291,14 @@
<artifactId>reactor-grpc-stub</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>apache-client</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>netty-nio-client</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sts</artifactId>
@@ -372,12 +374,6 @@
<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>
@@ -388,10 +384,6 @@
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -5,7 +5,7 @@
package org.whispersystems.textsecuregcm;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.core.Configuration;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
@@ -15,14 +15,14 @@ import com.google.cloud.logging.LoggingOptions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import io.dropwizard.Application;
import io.dropwizard.auth.AuthFilter;
import io.dropwizard.auth.PolymorphicAuthDynamicFeature;
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.setup.Bootstrap;
import io.dropwizard.core.setup.Environment;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptors;
import io.lettuce.core.metrics.MicrometerCommandLatencyRecorder;
@@ -50,6 +50,7 @@ import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletRegistration;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.glassfish.jersey.server.ServerProperties;
import org.signal.event.AdminEventLogger;
import org.signal.event.GoogleCloudAdminEventLogger;
@@ -91,11 +92,11 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.controllers.ArtController;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV2;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV3;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
import org.whispersystems.textsecuregcm.controllers.CertificateController;
import org.whispersystems.textsecuregcm.controllers.ChallengeController;
@@ -706,7 +707,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
///
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment = new WebSocketEnvironment<>(environment,
config.getWebSocketConfiguration(), 90000);
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(receiptSender, messagesManager, pushNotificationManager,
@@ -826,7 +827,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
}
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment = new WebSocketEnvironment<>(environment,
webSocketEnvironment.getRequestLog(), 60000);
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
@@ -840,6 +841,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
webSocketEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
provisioningEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
WebSocketResourceProviderFactory<AuthenticatedAccount> webSocketServlet = new WebSocketResourceProviderFactory<>(
webSocketEnvironment, AuthenticatedAccount.class, config.getWebSocketConfiguration());
WebSocketResourceProviderFactory<AuthenticatedAccount> provisioningServlet = new WebSocketResourceProviderFactory<>(
@@ -5,37 +5,27 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Duration;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
public class DynamoDbClientConfiguration {
public record DynamoDbClientConfiguration(@NotBlank String region,
@NotNull Duration clientExecutionTimeout,
@NotNull Duration clientRequestTimeout,
@Positive int maxConnections) {
private final String region;
private final Duration clientExecutionTimeout;
private final Duration clientRequestTimeout;
public DynamoDbClientConfiguration {
if (clientExecutionTimeout == null) {
clientExecutionTimeout = Duration.ofSeconds(30);
}
@JsonCreator
public DynamoDbClientConfiguration(
@JsonProperty("region") final String region,
@JsonProperty("clientExcecutionTimeout") final Duration clientExecutionTimeout,
@JsonProperty("clientRequestTimeout") final Duration clientRequestTimeout) {
this.region = region;
this.clientExecutionTimeout = clientExecutionTimeout != null ? clientExecutionTimeout : Duration.ofSeconds(30);
this.clientRequestTimeout = clientRequestTimeout != null ? clientRequestTimeout : Duration.ofSeconds(10);
}
if (clientRequestTimeout == null) {
clientRequestTimeout = Duration.ofSeconds(10);
}
@NotEmpty
public String getRegion() {
return region;
}
public Duration getClientExecutionTimeout() {
return clientExecutionTimeout;
}
public Duration getClientRequestTimeout() {
return clientRequestTimeout;
if (maxConnections == 0) {
maxConnections = 50;
}
}
}
@@ -5,11 +5,11 @@
package org.whispersystems.textsecuregcm.configuration;
import io.dropwizard.util.Strings;
import io.dropwizard.validation.ValidationMethod;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public record GcpAttachmentsConfiguration(@NotBlank String domain,
@@ -20,6 +20,6 @@ public record GcpAttachmentsConfiguration(@NotBlank String domain,
@SuppressWarnings("unused")
@ValidationMethod(message = "pathPrefix must be empty or start with /")
public boolean isPathPrefixValid() {
return Strings.isNullOrEmpty(pathPrefix) || pathPrefix.startsWith("/");
return StringUtils.isEmpty(pathPrefix) || pathPrefix.startsWith("/");
}
}
@@ -20,7 +20,7 @@ import javax.validation.constraints.Positive;
public record OneTimeDonationConfiguration(@Valid ExpiringLevelConfiguration boost,
@Valid ExpiringLevelConfiguration gift,
Map<String, @Valid OneTimeDonationCurrencyConfiguration> currencies,
BigDecimal sepaMaxTransactionSizeEuros) {
BigDecimal sepaMaximumEuros) {
/**
* @param badge the numeric donation level ID
@@ -4,7 +4,11 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@@ -56,6 +60,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -75,6 +80,7 @@ public class AccountController {
public static final int USERNAME_HASH_LENGTH = 32;
public static final int MAXIMUM_USERNAME_CIPHERTEXT_LENGTH = 128;
private static final String INVALID_REGISTRATION_ID = name(AccountController.class, "invalidRegistrationId");
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final TurnTokenGenerator turnTokenGenerator;
@@ -219,6 +225,10 @@ public class AccountController {
final Account account = disabledPermittedAuth.getAccount();
final byte deviceId = disabledPermittedAuth.getAuthenticatedDevice().getId();
if (!AccountsManager.validNewAccountAttributes(attributes)) {
Metrics.counter(INVALID_REGISTRATION_ID, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
}
final Account updatedAccount = accounts.update(account, a -> {
a.getDevice(deviceId).ifPresent(d -> {
d.setFetchesMessages(attributes.getFetchesMessages());
@@ -274,9 +284,9 @@ public class AccountController {
)
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public CompletableFuture<Void> deleteUsernameHash(@Auth final AuthenticatedAccount auth) {
public CompletableFuture<Response> deleteUsernameHash(@Auth final AuthenticatedAccount auth) {
return accounts.clearUsernameHash(auth.getAccount())
.thenRun(Util.NOOP);
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
@PUT
@@ -410,9 +420,8 @@ public class AccountController {
summary = "Set username link",
description = """
Authenticated endpoint. For the given encrypted username generates a username link handle.
Username link handle could be used to lookup the encrypted username.
An account can only have one username link at a time. Calling this endpoint will reset previously stored
encrypted username and deactivate previous link handle.
The username link handle can be used to lookup the encrypted username.
An account can only have one username link at a time; this endpoint overwrites the previous encrypted username if there was one.
"""
)
@ApiResponse(responseCode = "200", description = "Username Link updated successfully.", useReturnTypeSchema = true)
@@ -426,12 +435,19 @@ public class AccountController {
// check ratelimiter for username link operations
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.getAccount().getUuid());
final Account account = auth.getAccount();
// check if username hash is set for the account
if (auth.getAccount().getUsernameHash().isEmpty()) {
if (account.getUsernameHash().isEmpty()) {
throw new WebApplicationException(Status.CONFLICT);
}
final UUID usernameLinkHandle = UUID.randomUUID();
final UUID usernameLinkHandle;
if (encryptedUsername.keepLinkHandle() && account.getUsernameLinkHandle() != null) {
usernameLinkHandle = account.getUsernameLinkHandle();
} else {
usernameLinkHandle = UUID.randomUUID();
}
updateUsernameLink(auth.getAccount(), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
return new UsernameLinkHandle(usernameLinkHandle);
}
@@ -512,8 +528,8 @@ public class AccountController {
@DELETE
@Path("/me")
public CompletableFuture<Void> deleteAccount(@Auth DisabledPermittedAuthenticatedAccount auth) throws InterruptedException {
return accounts.delete(auth.getAccount(), AccountsManager.DeletionReason.USER_REQUEST);
public CompletableFuture<Response> deleteAccount(@Auth DisabledPermittedAuthenticatedAccount auth) throws InterruptedException {
return accounts.delete(auth.getAccount(), AccountsManager.DeletionReason.USER_REQUEST).thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
private void clearUsernameLink(final Account account) {
@@ -121,7 +121,7 @@ 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<Void> setKeys(@Auth final DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
public CompletableFuture<Response> setKeys(@Auth final DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
@RequestBody @NotNull @Valid final PreKeyState preKeys,
@Parameter(allowEmptyValue=true)
@@ -189,7 +189,8 @@ public class KeysController {
}
return keys.store(getIdentifier(account, identityType), device.getId(),
preKeys.getPreKeys(), preKeys.getPqPreKeys(), preKeys.getSignedPreKey(), preKeys.getPqLastResortPreKey());
preKeys.getPreKeys(), preKeys.getPqPreKeys(), preKeys.getSignedPreKey(), preKeys.getPqLastResortPreKey())
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
@GET
@@ -299,7 +300,7 @@ 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<Void> setSignedKey(@Auth final AuthenticatedAccount auth,
public CompletableFuture<Response> setSignedKey(@Auth final AuthenticatedAccount auth,
@Valid final ECSignedPreKey signedPreKey,
@QueryParam("identity") final Optional<String> identityType) {
@@ -314,7 +315,8 @@ public class KeysController {
});
return keys.storeEcSignedPreKeys(getIdentifier(auth.getAccount(), identityType),
Map.of(device.getId(), signedPreKey));
Map.of(device.getId(), signedPreKey))
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
private static boolean usePhoneNumberIdentity(final Optional<String> identityType) {
@@ -32,8 +32,9 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
@@ -132,7 +133,6 @@ public class MessageController {
private final ReportSpamTokenProvider reportSpamTokenProvider;
private final ClientReleaseManager clientReleaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = name(MessageController.class, "messageContentSize");
@@ -193,7 +193,6 @@ public class MessageController {
public Response sendMessage(@Auth Optional<AuthenticatedAccount> source,
@HeaderParam(OptionalAccess.UNIDENTIFIED) Optional<Anonymous> accessKey,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
@PathParam("destination") ServiceIdentifier destinationIdentifier,
@QueryParam("story") boolean isStory,
@NotNull @Valid IncomingMessageList messages,
@@ -280,7 +279,7 @@ public class MessageController {
}
if (isStory) {
checkStoryRateLimit(destination.get(), userAgent);
rateLimiters.getStoriesLimiter().validate(destination.get().getUuid());
}
final Set<Byte> excludedDeviceIds;
@@ -375,12 +374,11 @@ public class MessageController {
public Response sendMultiRecipientMessage(
@HeaderParam(OptionalAccess.UNIDENTIFIED) @Nullable CombinedUnidentifiedSenderAccessKeys accessKeys,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
@QueryParam("online") boolean online,
@QueryParam("ts") long timestamp,
@QueryParam("urgent") @DefaultValue("true") final boolean isUrgent,
@QueryParam("story") boolean isStory,
@NotNull @Valid MultiRecipientMessage multiRecipientMessage) {
@NotNull @Valid MultiRecipientMessage multiRecipientMessage) throws RateLimitExceededException {
final Map<ServiceIdentifier, Account> accountsByServiceIdentifier = new HashMap<>();
@@ -414,17 +412,20 @@ public class MessageController {
Collection<AccountMismatchedDevices> accountMismatchedDevices = new ArrayList<>();
Collection<AccountStaleDevices> accountStaleDevices = new ArrayList<>();
accountsByServiceIdentifier.forEach((serviceIdentifier, account) -> {
for (Map.Entry<ServiceIdentifier, Account> entry : accountsByServiceIdentifier.entrySet()) {
final ServiceIdentifier serviceIdentifier = entry.getKey();
final Account account = entry.getValue();
if (isStory) {
checkStoryRateLimit(account, userAgent);
rateLimiters.getStoriesLimiter().validate(account.getUuid());
}
Set<Byte> deviceIds = accountToDeviceIdAndRegistrationIdMap
.getOrDefault(account, Collections.emptySet())
.stream()
.map(Pair::first)
.collect(Collectors.toSet());
.getOrDefault(account, Collections.emptySet())
.stream()
.map(Pair::first)
.collect(Collectors.toSet());
try {
DestinationDeviceValidator.validateCompleteDeviceList(account, deviceIds, Collections.emptySet());
@@ -441,7 +442,8 @@ public class MessageController {
} catch (StaleDevicesException e) {
accountStaleDevices.add(new AccountStaleDevices(serviceIdentifier, new StaleDevices(e.getStaleDevices())));
}
});
}
if (!accountMismatchedDevices.isEmpty()) {
return Response
.status(409)
@@ -465,25 +467,37 @@ public class MessageController {
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED)));
multiRecipientMessageExecutor.invokeAll(Arrays.stream(multiRecipientMessage.recipients())
.map(recipient -> (Callable<Void>) () -> {
Account destinationAccount = accountsByServiceIdentifier.get(recipient.uuid());
CompletableFuture.allOf(
Arrays.stream(multiRecipientMessage.recipients())
// If we're sending a story, some recipients might not map to existing accounts
.filter(recipient -> accountsByServiceIdentifier.containsKey(recipient.uuid()))
.map(
recipient -> CompletableFuture.runAsync(
() -> {
Account destinationAccount = accountsByServiceIdentifier.get(recipient.uuid());
// we asserted this must exist in validateCompleteDeviceList
Device destinationDevice = destinationAccount.getDevice(recipient.deviceId()).orElseThrow();
sentMessageCounter.increment();
try {
sendCommonPayloadMessage(destinationAccount, destinationDevice, timestamp, online, isStory, isUrgent,
recipient, multiRecipientMessage.commonPayload());
} catch (NoSuchUserException e) {
uuids404.add(recipient.uuid());
}
return null;
})
.collect(Collectors.toList()));
// we asserted this must exist in validateCompleteDeviceList
Device destinationDevice = destinationAccount.getDevice(recipient.deviceId()).orElseThrow();
sentMessageCounter.increment();
try {
sendCommonPayloadMessage(destinationAccount, destinationDevice, timestamp, online, isStory, isUrgent,
recipient, multiRecipientMessage.commonPayload());
} catch (NoSuchUserException e) {
uuids404.add(recipient.uuid());
}
},
multiRecipientMessageExecutor))
.toArray(CompletableFuture[]::new))
.get();
} catch (InterruptedException e) {
logger.error("interrupted while delivering multi-recipient messages", e);
return Response.serverError().entity("interrupted during delivery").build();
} catch (CancellationException e) {
logger.error("cancelled while delivering multi-recipient messages", e);
return Response.serverError().entity("delivery cancelled").build();
} catch (ExecutionException e) {
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
return Response.serverError().entity("failure during delivery").build();
}
return Response.ok(new SendMultiRecipientMessageResponse(uuids404)).build();
}
@@ -581,7 +595,7 @@ public class MessageController {
@Timed
@DELETE
@Path("/uuid/{uuid}")
public CompletableFuture<Void> removePendingMessage(@Auth AuthenticatedAccount auth, @PathParam("uuid") UUID uuid) {
public CompletableFuture<Response> removePendingMessage(@Auth AuthenticatedAccount auth, @PathParam("uuid") UUID uuid) {
return messagesManager.delete(
auth.getAccount().getUuid(),
auth.getAuthenticatedDevice().getId(),
@@ -603,7 +617,8 @@ public class MessageController {
}
}
});
});
})
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
@Timed
@@ -736,14 +751,6 @@ public class MessageController {
}
}
private void checkStoryRateLimit(Account destination, String userAgent) {
try {
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
} catch (final RateLimitExceededException e) {
Metrics.counter(RATE_LIMITED_STORIES_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
}
}
private void checkMessageRateLimit(AuthenticatedAccount source, Account destination, String userAgent)
throws RateLimitExceededException {
final String senderCountryCode = Util.getCountryCode(source.getAccount().getNumber());
@@ -229,7 +229,7 @@ public class SubscriptionController {
giftBadge,
oneTimeDonationConfiguration.gift().expiration())));
return new GetSubscriptionConfigurationResponse(buildCurrencyConfiguration(userAgent), levels);
return new GetSubscriptionConfigurationResponse(buildCurrencyConfiguration(userAgent), levels, oneTimeDonationConfiguration.sepaMaximumEuros());
}
@DELETE
@@ -537,7 +537,8 @@ public class SubscriptionController {
* @param levels map of numeric level IDs to level-specific configuration
*/
public record GetSubscriptionConfigurationResponse(Map<String, CurrencyConfiguration> currencies,
Map<String, LevelConfiguration> levels) {
Map<String, LevelConfiguration> levels,
BigDecimal sepaMaximumEuros) {
}
@@ -712,11 +713,11 @@ public class SubscriptionController {
if (request.paymentMethod == PaymentMethod.SEPA_DEBIT &&
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
EURO_CURRENCY_CODE,
oneTimeDonationConfiguration.sepaMaxTransactionSizeEuros())) > 0) {
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(Map.of(
"error", "amount_above_sepa_limit",
"maximum", oneTimeDonationConfiguration.sepaMaxTransactionSizeEuros().toString())).build());
"maximum", oneTimeDonationConfiguration.sepaMaximumEuros().toString())).build());
}
}
@@ -5,6 +5,7 @@
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;
@@ -18,7 +19,17 @@ public record EncryptedUsername(
@NotNull
@Size(min = 1, max = EncryptedUsername.MAX_SIZE)
@Schema(type = "string", description = "the URL-safe base64 encoding of the encrypted username")
byte[] usernameLinkEncryptedValue) {
byte[] usernameLinkEncryptedValue,
@JsonProperty
@Schema(type = "boolean", description = "if set and the account already has an encrypted-username link handle, reuse the same link handle rather than generating a new one. The response will still have the link handle.")
boolean keepLinkHandle
) {
public static final int MAX_SIZE = 128;
public EncryptedUsername(final byte[] usernameLinkEncryptedValue) {
this(usernameLinkEncryptedValue, false);
}
}
@@ -8,20 +8,14 @@ package org.whispersystems.textsecuregcm.filters;
import static com.codahale.metrics.MetricRegistry.name;
import static java.util.Objects.requireNonNull;
import com.google.common.net.HttpHeaders;
import com.google.common.net.InetAddresses;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import javax.annotation.Nonnull;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
public class RequestStatisticsFilter implements ContainerRequestFilter {
@@ -29,12 +23,8 @@ public class RequestStatisticsFilter implements ContainerRequestFilter {
private static final String CONTENT_LENGTH_DISTRIBUTION_NAME = name(RequestStatisticsFilter.class, "contentLength");
private static final String IP_VERSION_METRIC = name(RequestStatisticsFilter.class, "ipVersion");
private static final String TRAFFIC_SOURCE_TAG = "trafficSource";
private static final String IP_VERSION_TAG = "ipVersion";
@Nonnull
private final String trafficSourceTag;
@@ -48,31 +38,8 @@ public class RequestStatisticsFilter implements ContainerRequestFilter {
try {
Metrics.summary(CONTENT_LENGTH_DISTRIBUTION_NAME, TRAFFIC_SOURCE_TAG, trafficSourceTag)
.record(requestContext.getLength());
Metrics.counter(IP_VERSION_METRIC, TRAFFIC_SOURCE_TAG, trafficSourceTag, IP_VERSION_TAG, resolveIpVersion(requestContext))
.increment();
} catch (final Exception e) {
logger.warn("Error recording request statistics", e);
}
}
@Nonnull
private static String resolveIpVersion(@Nonnull final ContainerRequestContext ctx) {
return HeaderUtils.getMostRecentProxy(ctx.getHeaderString(HttpHeaders.X_FORWARDED_FOR))
.map(ipString -> {
try {
//noinspection UnstableApiUsage
final InetAddress addr = InetAddresses.forString(ipString);
if (addr instanceof Inet4Address) {
return "IPv4";
}
if (addr instanceof Inet6Address) {
return "IPv6";
}
} catch (IllegalArgumentException e) {
// ignore illegal argument exception
}
return null;
})
.orElse("unresolved");
}
}
@@ -5,9 +5,6 @@
package org.whispersystems.textsecuregcm.gcp;
import io.dropwizard.util.Strings;
import javax.annotation.Nonnull;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -16,6 +13,8 @@ import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
public class CanonicalRequestGenerator {
private static final DateTimeFormatter SIMPLE_UTC_DATE = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US).withZone(ZoneOffset.UTC);
@@ -43,7 +42,7 @@ public class CanonicalRequestGenerator {
final StringBuilder result = new StringBuilder("POST\n");
final StringBuilder resourcePathBuilder = new StringBuilder();
if (!Strings.isNullOrEmpty(pathPrefix)) {
if (StringUtils.isNotEmpty(pathPrefix)) {
resourcePathBuilder.append(pathPrefix);
}
resourcePathBuilder.append('/').append(URLEncoder.encode(key, StandardCharsets.UTF_8));
@@ -267,7 +267,12 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
.asRuntimeException());
}
final UUID linkHandle = UUID.randomUUID();
final UUID linkHandle;
if (request.getKeepLinkHandle() && account.getUsernameLinkHandle() != null) {
linkHandle = account.getUsernameLinkHandle();
} else {
linkHandle = UUID.randomUUID();
}
return Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray())))
.thenReturn(linkHandle);
@@ -88,9 +88,9 @@ public class PushChallengeManager {
final String platform = account.getPrimaryDevice().map(primaryDevice -> {
if (StringUtils.isNotBlank(primaryDevice.getGcmId())) {
return ClientPlatform.IOS.name().toLowerCase();
} else if (StringUtils.isNotBlank(primaryDevice.getApnId())) {
return ClientPlatform.ANDROID.name().toLowerCase();
} else if (StringUtils.isNotBlank(primaryDevice.getApnId())) {
return ClientPlatform.IOS.name().toLowerCase();
} else {
return "unknown";
}
@@ -21,7 +21,10 @@ public class IOExceptionMapper implements ExceptionMapper<IOException> {
public Response toResponse(IOException e) {
if (!(e.getCause() instanceof java.util.concurrent.TimeoutException)) {
logger.warn("IOExceptionMapper", e);
} else if (e.getCause().getMessage().startsWith("Idle timeout expired")) {
return Response.status(Response.Status.REQUEST_TIMEOUT).build();
}
return Response.status(503).build();
}
}
@@ -17,10 +17,10 @@ import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.dropwizard.logging.AbstractAppenderFactory;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.filter.LevelFilterFactory;
import io.dropwizard.logging.layout.LayoutFactory;
import io.dropwizard.logging.common.AbstractAppenderFactory;
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
import io.dropwizard.logging.common.filter.LevelFilterFactory;
import io.dropwizard.logging.common.layout.LayoutFactory;
import java.time.Duration;
import java.util.Optional;
import javax.validation.constraints.NotEmpty;
@@ -7,7 +7,7 @@ package org.whispersystems.textsecuregcm.metrics;
import com.codahale.metrics.SharedMetricRegistries;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.setup.Environment;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
@@ -14,7 +14,7 @@ import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ScheduledReporter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.metrics.BaseReporterFactory;
import io.dropwizard.metrics.common.BaseReporterFactory;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
@@ -102,20 +102,13 @@ public class APNSender implements Managed, PushNotificationSender {
.addCustomProperty("attemptLoginContext", notification.data())
.build();
case ATTEMPT_LOGIN_NOTIFICATION_LOW_PRIORITY -> new SimpleApnsPayloadBuilder()
.setContentAvailable(true)
.addCustomProperty("attemptLoginContext", notification.data())
.build();
case CHALLENGE -> new SimpleApnsPayloadBuilder()
.setSound("default")
.setLocalizedAlertMessage("APN_Message")
.setContentAvailable(true)
.addCustomProperty("challenge", notification.data())
.build();
case RATE_LIMIT_CHALLENGE -> new SimpleApnsPayloadBuilder()
.setSound("default")
.setLocalizedAlertMessage("APN_Message")
.setContentAvailable(true)
.addCustomProperty("rateLimitChallenge", notification.data())
.build();
};
@@ -128,8 +121,12 @@ public class APNSender implements Managed, PushNotificationSender {
pushType = notification.urgent() ? PushType.ALERT : PushType.BACKGROUND;
}
final DeliveryPriority deliveryPriority =
(notification.urgent() || isVoip) ? DeliveryPriority.IMMEDIATE : DeliveryPriority.CONSERVE_POWER;
final DeliveryPriority deliveryPriority = switch (notification.notificationType()) {
case NOTIFICATION ->
(notification.urgent() || isVoip) ? DeliveryPriority.IMMEDIATE : DeliveryPriority.CONSERVE_POWER;
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> DeliveryPriority.IMMEDIATE;
case CHALLENGE, RATE_LIMIT_CHALLENGE -> DeliveryPriority.CONSERVE_POWER;
};
final String collapseId =
(notification.notificationType() == PushNotification.NotificationType.NOTIFICATION && notification.urgent() && !isVoip)
@@ -89,7 +89,7 @@ public class FcmSender implements PushNotificationSender {
final String key = switch (pushNotification.notificationType()) {
case NOTIFICATION -> "newMessageAlert";
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, ATTEMPT_LOGIN_NOTIFICATION_LOW_PRIORITY -> "attemptLoginContext";
case ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY -> "attemptLoginContext";
case CHALLENGE -> "challenge";
case RATE_LIMIT_CHALLENGE -> "rateLimitChallenge";
};
@@ -20,7 +20,6 @@ public record PushNotification(String deviceToken,
public enum NotificationType {
NOTIFICATION,
ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
@Deprecated ATTEMPT_LOGIN_NOTIFICATION_LOW_PRIORITY, // Temporary support for iOS clients; can be removed after 2023-06-12
CHALLENGE,
RATE_LIMIT_CHALLENGE
}
@@ -76,13 +76,6 @@ public class PushNotificationManager {
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
context, destination, device, true));
// This is a workaround for older iOS clients who need a low priority push to trigger the logout notification
if (tokenAndType.second() == PushNotification.TokenType.APN) {
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_LOW_PRIORITY,
context, destination, device, false));
}
}
public void handleMessagesRetrieved(final Account account, final Device device, final String userAgent) {
@@ -78,6 +78,8 @@ public class Accounts extends AbstractDynamoDbStore {
private static final Logger log = LoggerFactory.getLogger(Accounts.class);
private static final Duration USERNAME_RECLAIM_TTL = Duration.ofDays(3);
static final List<String> ACCOUNT_FIELDS_TO_EXCLUDE_FROM_SERIALIZATION = List.of("uuid", "usernameLinkHandle");
private static final ObjectWriter ACCOUNT_DDB_JSON_WRITER = SystemMapper.jsonMapper()
@@ -89,6 +91,7 @@ public class Accounts extends AbstractDynamoDbStore {
private static final Timer RESERVE_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "reserveUsername"));
private static final Timer CLEAR_USERNAME_HASH_TIMER = Metrics.timer(name(Accounts.class, "clearUsernameHash"));
private static final Timer UPDATE_TIMER = Metrics.timer(name(Accounts.class, "update"));
private static final Timer RECLAIM_TIMER = Metrics.timer(name(Accounts.class, "reclaim"));
private static final Timer GET_BY_NUMBER_TIMER = Metrics.timer(name(Accounts.class, "getByNumber"));
private static final Timer GET_BY_USERNAME_HASH_TIMER = Metrics.timer(name(Accounts.class, "getByUsernameHash"));
private static final Timer GET_BY_USERNAME_LINK_HANDLE_TIMER = Metrics.timer(name(Accounts.class, "getByUsernameLinkHandle"));
@@ -118,6 +121,8 @@ public class Accounts extends AbstractDynamoDbStore {
static final String ATTR_USERNAME_HASH = "N";
// confirmed; bool
static final String ATTR_CONFIRMED = "F";
// reclaimable; bool. Indicates that on confirmation the username link should be preserved
static final String ATTR_RECLAIMABLE = "R";
// unidentified access key; byte[] or null
static final String ATTR_UAK = "UAK";
// time to live; number
@@ -222,16 +227,9 @@ public class Accounts extends AbstractDynamoDbStore {
final ByteBuffer actualAccountUuid = reason.item().get(KEY_ACCOUNT_UUID).b().asByteBuffer();
account.setUuid(UUIDUtil.fromByteBuffer(actualAccountUuid));
final Account existingAccount = getByAccountIdentifier(account.getUuid()).orElseThrow();
// It's up to the client to delete this username hash if they can't retrieve and decrypt the plaintext username from storage service
existingAccount.getUsernameHash().ifPresent(account::setUsernameHash);
account.setNumber(existingAccount.getNumber(), existingAccount.getPhoneNumberIdentifier());
account.setVersion(existingAccount.getVersion());
update(account);
joinAndUnwrapUpdateFuture(reclaimAccount(existingAccount, account));
return false;
}
@@ -246,11 +244,91 @@ public class Accounts extends AbstractDynamoDbStore {
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
return true;
});
}
/**
* Copies over any account attributes that should be preserved when a new account reclaims an account identifier.
*
* @param existingAccount the existing account in the accounts table
* @param accountToCreate a new account, with the same number and identifier as existingAccount
*/
private CompletionStage<Void> reclaimAccount(final Account existingAccount, final Account accountToCreate) {
if (!existingAccount.getUuid().equals(accountToCreate.getUuid()) ||
!existingAccount.getNumber().equals(accountToCreate.getNumber())) {
throw new IllegalArgumentException("reclaimed accounts must match");
}
return AsyncTimerUtil.record(RECLAIM_TIMER, () -> {
accountToCreate.setVersion(existingAccount.getVersion());
final List<TransactWriteItem> writeItems = new ArrayList<>();
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
// an opportunity to reclaim their original username and link. We do this by:
// 1. marking the usernameHash as reserved for the aci
// 2. saving the username link id, but not the encrypted username. The link will be broken until the client
// reclaims their username
//
// If we partially reclaim the account but fail (for example, we update the account but the client goes away
// before creation is finished), we might be reclaiming the account we already reclaimed. In that case, we
// should copy over the reserved username and link verbatim
if (existingAccount.getReservedUsernameHash().isPresent() &&
existingAccount.getUsernameLinkHandle() != null &&
existingAccount.getUsernameHash().isEmpty() &&
existingAccount.getEncryptedUsername().isEmpty()) {
// reclaiming a partially reclaimed account
accountToCreate.setReservedUsernameHash(existingAccount.getReservedUsernameHash().get());
accountToCreate.setUsernameLinkHandle(existingAccount.getUsernameLinkHandle());
} else if (existingAccount.getUsernameHash().isPresent()) {
// reclaiming an account with a username
final byte[] usernameHash = existingAccount.getUsernameHash().get();
final long expirationTime = clock.instant().plus(USERNAME_RECLAIM_TTL).getEpochSecond();
accountToCreate.setReservedUsernameHash(usernameHash);
accountToCreate.setUsernameLinkHandle(existingAccount.getUsernameLinkHandle());
writeItems.add(TransactWriteItem.builder()
.put(Put.builder()
.tableName(usernamesConstraintTableName)
.item(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountToCreate.getUuid()),
ATTR_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash),
ATTR_TTL, AttributeValues.fromLong(expirationTime),
ATTR_CONFIRMED, AttributeValues.fromBool(false),
ATTR_RECLAIMABLE, AttributeValues.fromBool(true)))
.conditionExpression("attribute_not_exists(#username_hash) OR (#ttl < :now) OR #uuid = :uuid")
.expressionAttributeNames(Map.of(
"#username_hash", ATTR_USERNAME_HASH,
"#ttl", ATTR_TTL,
"#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
":uuid", AttributeValues.fromUUID(accountToCreate.getUuid())))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build());
}
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, accountToCreate).transactItem());
return asyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
.thenApply(response -> {
accountToCreate.setVersion(accountToCreate.getVersion() + 1);
return (Void) null;
})
.exceptionally(throwable -> {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
if (unwrapped instanceof TransactionCanceledException te) {
if (te.cancellationReasons().stream().anyMatch(Accounts::conditionalCheckFailed)) {
throw new ContestedOptimisticLockException();
}
}
// rethrow
throw CompletableFutureUtils.errorAsCompletionException(throwable);
});
});
}
/**
* Changes the phone number for the given account. The given account's number should be its current, pre-change
* number. If this method succeeds, the account's number will be changed to the new number and its phone number
@@ -369,7 +447,8 @@ public class Accounts extends AbstractDynamoDbStore {
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
ATTR_USERNAME_HASH, AttributeValues.fromByteArray(reservedUsernameHash),
ATTR_TTL, AttributeValues.fromLong(expirationTime),
ATTR_CONFIRMED, AttributeValues.fromBool(false)))
ATTR_CONFIRMED, AttributeValues.fromBool(false),
ATTR_RECLAIMABLE, AttributeValues.fromBool(false)))
.conditionExpression("attribute_not_exists(#username_hash) OR (#ttl < :now)")
.expressionAttributeNames(Map.of("#username_hash", ATTR_USERNAME_HASH, "#ttl", ATTR_TTL))
.expressionAttributeValues(Map.of(":now", AttributeValues.fromLong(clock.instant().getEpochSecond())))
@@ -426,32 +505,36 @@ public class Accounts extends AbstractDynamoDbStore {
*/
public CompletableFuture<Void> confirmUsernameHash(final Account account, final byte[] usernameHash, @Nullable final byte[] encryptedUsername) {
final Timer.Sample sample = Timer.start();
final UUID newLinkHandle = UUID.randomUUID();
final TransactWriteItemsRequest request;
return pickLinkHandle(account, usernameHash)
.thenCompose(linkHandle -> {
final TransactWriteItemsRequest request;
try {
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
updatedAccount.setUsernameHash(usernameHash);
updatedAccount.setReservedUsernameHash(null);
updatedAccount.setUsernameLinkDetails(encryptedUsername == null ? null : linkHandle, encryptedUsername);
try {
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
updatedAccount.setUsernameHash(usernameHash);
updatedAccount.setReservedUsernameHash(null);
updatedAccount.setUsernameLinkDetails(encryptedUsername == null ? null : newLinkHandle, encryptedUsername);
request = buildConfirmUsernameHashRequest(updatedAccount, account.getUsernameHash());
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
request = buildConfirmUsernameHashRequest(updatedAccount, account.getUsernameHash());
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
return asyncClient.transactWriteItems(request)
.thenRun(() -> {
return asyncClient.transactWriteItems(request).thenApply(ignored -> linkHandle);
})
.thenApply(linkHandle -> {
account.setUsernameHash(usernameHash);
account.setReservedUsernameHash(null);
account.setUsernameLinkDetails(encryptedUsername == null ? null : newLinkHandle, encryptedUsername);
account.setUsernameLinkDetails(encryptedUsername == null ? null : linkHandle, encryptedUsername);
account.setVersion(account.getVersion() + 1);
return (Void) null;
})
.exceptionally(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException transactionCanceledException) {
if (transactionCanceledException.cancellationReasons().stream().map(CancellationReason::code).anyMatch(CONDITIONAL_CHECK_FAILED::equals)) {
if (ExceptionUtils.unwrap(
throwable) instanceof TransactionCanceledException transactionCanceledException) {
if (transactionCanceledException.cancellationReasons().stream().map(CancellationReason::code)
.anyMatch(CONDITIONAL_CHECK_FAILED::equals)) {
throw new ContestedOptimisticLockException();
}
}
@@ -461,7 +544,31 @@ public class Accounts extends AbstractDynamoDbStore {
.whenComplete((ignored, throwable) -> sample.stop(SET_USERNAME_TIMER));
}
private TransactWriteItemsRequest buildConfirmUsernameHashRequest(final Account updatedAccount, final Optional<byte[]> maybeOriginalUsernameHash)
private CompletableFuture<UUID> pickLinkHandle(final Account account, final byte[] usernameHash) {
if (account.getUsernameLinkHandle() == null) {
// There's no old link handle, so we can just use a randomly generated link handle
return CompletableFuture.completedFuture(UUID.randomUUID());
}
// Otherwise, there's an existing link handle. If this is the result of an account being re-registered, we should
// preserve the link handle.
return asyncClient.getItem(GetItemRequest.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(ATTR_USERNAME_HASH, AttributeValues.b(usernameHash)))
.projectionExpression(ATTR_RECLAIMABLE).build())
.thenApply(response -> {
if (response.hasItem() && AttributeValues.getBool(response.item(), ATTR_RECLAIMABLE, false)) {
// this username reservation indicates it's a username waiting to be "reclaimed"
return account.getUsernameLinkHandle();
}
// There was no existing username reservation, or this was a standard "new" username. Either way, we should
// generate a new link handle.
return UUID.randomUUID();
});
}
private TransactWriteItemsRequest buildConfirmUsernameHashRequest(final Account updatedAccount,
final Optional<byte[]> maybeOriginalUsernameHash)
throws JsonProcessingException {
final List<TransactWriteItem> writeItems = new ArrayList<>();
@@ -528,9 +635,6 @@ public class Accounts extends AbstractDynamoDbStore {
return account.getUsernameHash().map(usernameHash -> {
final Timer.Sample sample = Timer.start();
@Nullable final UUID originalLinkHandle = account.getUsernameLinkHandle();
@Nullable final byte[] originalEncryptedUsername = account.getEncryptedUsername().orElse(null);
final TransactWriteItemsRequest request;
try {
@@ -593,10 +697,42 @@ public class Accounts extends AbstractDynamoDbStore {
.build();
}
@Nonnull
public CompletionStage<Void> updateAsync(final Account account) {
return AsyncTimerUtil.record(UPDATE_TIMER, () -> {
final UpdateItemRequest updateItemRequest;
/**
* A ddb update that can be used as part of a transaction or single-item update statement.
*/
record UpdateAccountSpec(
String tableName,
Map<String, AttributeValue> key,
Map<String, String> attrNames,
Map<String, AttributeValue> attrValues,
String updateExpression,
String conditionExpression) {
UpdateItemRequest updateItemRequest() {
return UpdateItemRequest.builder()
.tableName(tableName)
.key(key)
.updateExpression(updateExpression)
.conditionExpression(conditionExpression)
.expressionAttributeNames(attrNames)
.expressionAttributeValues(attrValues)
.build();
}
TransactWriteItem transactItem() {
return TransactWriteItem.builder().update(Update.builder()
.tableName(tableName)
.key(key)
.updateExpression(updateExpression)
.conditionExpression(conditionExpression)
.expressionAttributeNames(attrNames)
.expressionAttributeValues(attrValues)
.build()).build();
}
static UpdateAccountSpec forAccount(
final String accountTableName,
final Account account) {
try {
// username, e164, and pni cannot be modified through this method
final Map<String, String> attrNames = new HashMap<>(Map.of(
@@ -618,28 +754,53 @@ public class Accounts extends AbstractDynamoDbStore {
attrValues.put(":uak", AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
updateExpressionBuilder.append(", #uak = :uak");
}
// If the account has a username/handle pair, we should add it to the top level attributes.
// When we remove an encryptedUsername but preserve the link (re-registration), it's possible that the account
// has a usernameLinkHandle but not an encrypted username. In this case there should already be a top-level
// usernameLink attribute.
if (account.getEncryptedUsername().isPresent() && account.getUsernameLinkHandle() != null) {
attrNames.put("#ul", ATTR_USERNAME_LINK_UUID);
attrValues.put(":ul", AttributeValues.fromUUID(account.getUsernameLinkHandle()));
updateExpressionBuilder.append(", #ul = :ul");
}
updateExpressionBuilder.append(" ADD #version :version_increment");
if (account.getEncryptedUsername().isEmpty() || account.getUsernameLinkHandle() == null) {
attrNames.put("#ul", ATTR_USERNAME_LINK_UUID);
updateExpressionBuilder.append(" REMOVE #ul");
}
updateItemRequest = UpdateItemRequest.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.updateExpression(updateExpressionBuilder.toString())
.conditionExpression("attribute_exists(#number) AND #version = :version")
.expressionAttributeNames(attrNames)
.expressionAttributeValues(attrValues)
.build();
// Some operations may remove the usernameLink or the usernameHash (re-registration, clear username link, and
// clear username hash). Since these also have top-level ddb attributes, we need to make sure to remove those
// as well.
final List<String> removes = new ArrayList<>();
if (account.getUsernameLinkHandle() == null) {
attrNames.put("#ul", ATTR_USERNAME_LINK_UUID);
removes.add("#ul");
}
if (account.getUsernameHash().isEmpty()) {
attrNames.put("#username_hash", ATTR_USERNAME_HASH);
removes.add("#username_hash");
}
if (!removes.isEmpty()) {
updateExpressionBuilder.append(" REMOVE %s".formatted(String.join(",", removes)));
}
updateExpressionBuilder.append(" ADD #version :version_increment");
return new UpdateAccountSpec(
accountTableName,
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())),
attrNames,
attrValues,
updateExpressionBuilder.toString(),
"attribute_exists(#number) AND #version = :version");
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
}
@Nonnull
public CompletionStage<Void> updateAsync(final Account account) {
return AsyncTimerUtil.record(UPDATE_TIMER, () -> {
final UpdateItemRequest updateItemRequest = UpdateAccountSpec
.forAccount(accountsTableName, account)
.updateItemRequest();
return asyncClient.updateItem(updateItemRequest)
.thenApply(response -> {
@@ -662,9 +823,9 @@ public class Accounts extends AbstractDynamoDbStore {
});
}
public void update(final Account account) throws ContestedOptimisticLockException {
private static void joinAndUnwrapUpdateFuture(CompletionStage<Void> future) {
try {
updateAsync(account).toCompletableFuture().join();
future.toCompletableFuture().join();
} catch (final CompletionException e) {
// unwrap CompletionExceptions, throw as long is it's unchecked
Throwables.throwIfUnchecked(ExceptionUtils.unwrap(e));
@@ -676,6 +837,10 @@ public class Accounts extends AbstractDynamoDbStore {
}
}
public void update(final Account account) throws ContestedOptimisticLockException {
joinAndUnwrapUpdateFuture(updateAsync(account));
}
public CompletableFuture<Boolean> usernameHashAvailable(final byte[] username) {
return usernameHashAvailable(Optional.empty(), username);
}
@@ -16,17 +16,30 @@ import com.codahale.metrics.Timer;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.lifecycle.Managed;
import io.micrometer.core.instrument.Counter;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.util.Constants;
import org.whispersystems.textsecuregcm.util.Util;
@@ -35,6 +48,8 @@ public class MessagePersister implements Managed {
private final MessagesCache messagesCache;
private final MessagesManager messagesManager;
private final AccountsManager accountsManager;
private final ClientPresenceManager clientPresenceManager;
private final KeysManager keysManager;
private final Duration persistDelay;
@@ -50,27 +65,35 @@ public class MessagePersister implements Managed {
private final Counter oversizedQueueCounter = counter(name(MessagePersister.class, "persistQueueOversized"));
private final Histogram queueCountHistogram = metricRegistry.histogram(name(MessagePersister.class, "queueCount"));
private final Histogram queueSizeHistogram = metricRegistry.histogram(name(MessagePersister.class, "queueSize"));
private final ExecutorService executor;
static final int QUEUE_BATCH_LIMIT = 100;
static final int MESSAGE_BATCH_LIMIT = 100;
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
public static final Duration UNLINK_TIMEOUT = Duration.ofHours(1);
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
public MessagePersister(final MessagesCache messagesCache, final MessagesManager messagesManager,
final AccountsManager accountsManager,
final AccountsManager accountsManager, final ClientPresenceManager clientPresenceManager,
final KeysManager keysManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final Duration persistDelay,
final int dedicatedProcessWorkerThreadCount) {
final int dedicatedProcessWorkerThreadCount,
final ExecutorService executor
) {
this.messagesCache = messagesCache;
this.messagesManager = messagesManager;
this.accountsManager = accountsManager;
this.clientPresenceManager = clientPresenceManager;
this.keysManager = keysManager;
this.persistDelay = persistDelay;
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
this.dedicatedProcess = true;
this.executor = executor;
for (int i = 0; i < workerThreads.length; i++) {
workerThreads[i] = new Thread(() -> {
@@ -139,12 +162,14 @@ public class MessagePersister implements Managed {
final UUID accountUuid = MessagesCache.getAccountUuidFromQueueName(queue);
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queue);
final Optional<Account> maybeAccount = accountsManager.getByAccountIdentifier(accountUuid);
if (maybeAccount.isEmpty()) {
logger.error("No account record found for account {}", accountUuid);
continue;
}
try {
persistQueue(accountUuid, deviceId);
persistQueue(maybeAccount.get(), deviceId);
} catch (final Exception e) {
if (e instanceof ItemCollectionSizeLimitExceededException) {
oversizedQueueCounter.increment();
}
persistQueueExceptionMeter.mark();
logger.warn("Failed to persist queue {}::{}; will schedule for retry", accountUuid, deviceId, e);
@@ -161,14 +186,8 @@ public class MessagePersister implements Managed {
}
@VisibleForTesting
void persistQueue(final UUID accountUuid, final byte deviceId) throws MessagePersistenceException {
final Optional<Account> maybeAccount = accountsManager.getByAccountIdentifier(accountUuid);
if (maybeAccount.isEmpty()) {
logger.error("No account record found for account {}", accountUuid);
return;
}
void persistQueue(final Account account, final byte deviceId) throws MessagePersistenceException {
final UUID accountUuid = account.getUuid();
try (final Timer.Context ignored = persistQueueTimer.time()) {
messagesCache.lockQueueForPersistence(accountUuid, deviceId);
@@ -197,9 +216,73 @@ public class MessagePersister implements Managed {
} while (!messages.isEmpty());
queueSizeHistogram.update(messageCount);
} catch (ItemCollectionSizeLimitExceededException e) {
oversizedQueueCounter.increment();
unlinkLeastActiveDevice(account, deviceId); // this will either do a deferred reschedule for retry or throw
} finally {
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
}
}
}
@VisibleForTesting
void unlinkLeastActiveDevice(final Account account, byte destinationDeviceId) throws MessagePersistenceException {
if (!messagesCache.lockAccountForMessagePersisterCleanup(account.getUuid())) {
// don't try to unlink an account multiple times in parallel; just fail this persist attempt
// and we'll try again, hopefully deletions in progress will have made room
throw new MessagePersistenceException("account has a full queue and another device-unlinking attempt is in progress");
}
// Selection logic:
// The primary device is never unlinked
// The least-recently-seen inactive device gets unlinked
// If there are none, the device with the oldest queued message (not necessarily the
// least-recently-seen; a device could be connecting frequently but have some problem fetching
// its messages) is unlinked
final Device deviceToDelete = account.getDevices()
.stream()
.filter(d -> !d.isPrimary() && !d.isEnabled())
.min(Comparator.comparing(Device::getLastSeen))
.or(() ->
Flux.fromIterable(account.getDevices())
.filter(d -> !d.isPrimary())
.flatMap(d ->
messagesManager
.getEarliestUndeliveredTimestampForDevice(account.getUuid(), d.getId())
.map(t -> Tuples.of(d, t)))
.sort(Comparator.comparing(Tuple2::getT2))
.map(Tuple2::getT1)
.next()
.blockOptional())
.orElseThrow(() -> new MessagePersistenceException("account has a full queue and no unlinkable devices"));
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device {}{}",
account.getUuid(), destinationDeviceId, deviceToDelete.getId(), deviceToDelete.getId() == destinationDeviceId ? "" : " and schedule for retry");
executor.execute(
() -> {
try {
// Lock the device's auth token first to prevent it from connecting while we're
// destroying its queue, but we don't want to completely remove the device from the
// account until we're sure the messages have been cleared because otherwise we won't
// be able to find it later to try again, in the event of a failure or timeout
final Account updatedAccount = accountsManager.update(
account,
a -> a.getDevice(deviceToDelete.getId()).ifPresent(Device::lockAuthTokenHash));
clientPresenceManager.disconnectPresence(account.getUuid(), deviceToDelete.getId());
CompletableFuture
.allOf(
keysManager.delete(account.getUuid(), deviceToDelete.getId()),
messagesManager.clear(account.getUuid(), deviceToDelete.getId()))
.orTimeout((UNLINK_TIMEOUT.toSeconds() * 3) / 4, TimeUnit.SECONDS)
.join();
accountsManager.update(updatedAccount, a -> a.removeDevice(deviceToDelete.getId()));
} finally {
messagesCache.unlockAccountForMessagePersisterCleanup(account.getUuid());
if (deviceToDelete.getId() != destinationDeviceId) { // no point in persisting a device we just purged
messagesCache.addQueueToPersist(account.getUuid(), destinationDeviceId);
}
}
});
}
}
@@ -12,6 +12,7 @@ import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.ScoredValue;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.SetArgs;
import io.lettuce.core.ZAddArgs;
import io.lettuce.core.cluster.SlotHash;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
@@ -382,6 +383,20 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
connection -> connection.sync().del(getPersistInProgressKey(accountUuid, deviceId)));
}
boolean lockAccountForMessagePersisterCleanup(final UUID accountUuid) {
return readDeleteCluster.withBinaryCluster(
connection -> "OK".equals(
connection.sync().set(
getUnlinkInProgressKey(accountUuid),
LOCK_VALUE,
new SetArgs().ex(MessagePersister.UNLINK_TIMEOUT.toSeconds()).nx())));
}
void unlockAccountForMessagePersisterCleanup(final UUID accountUuid) {
readDeleteCluster.useBinaryCluster(
connection -> connection.sync().del(getUnlinkInProgressKey(accountUuid)));
}
public void addMessageAvailabilityListener(final UUID destinationUuid, final byte deviceId,
final MessageAvailabilityListener listener) {
final String queueName = getQueueName(destinationUuid, deviceId);
@@ -531,6 +546,10 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
return ("user_queue_persisting::{" + accountUuid + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
}
private static byte[] getUnlinkInProgressKey(final UUID accountUuid) {
return ("user_account_unlinking::{" + accountUuid + "}").getBytes(StandardCharsets.UTF_8);
}
static UUID getAccountUuidFromQueueName(final String queueName) {
final int startOfHashTag = queueName.indexOf('{');
@@ -102,6 +102,10 @@ public class MessagesManager {
.tap(Micrometer.metrics(Metrics.globalRegistry));
}
public Mono<Long> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, byte destinationDevice) {
return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp);
}
public CompletableFuture<Void> clear(UUID destinationUuid) {
return CompletableFuture.allOf(
messagesCache.clear(destinationUuid),
@@ -220,9 +220,11 @@ public class BraintreeManager implements SubscriptionProcessorManager {
}
}
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status) {
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status, final boolean latestTransactionFailed) {
return switch (status) {
case ACTIVE -> SubscriptionStatus.ACTIVE;
// Stripe returns a PAST_DUE status if the subscription's most recent payment failed.
// This check ensures that Braintree is consistent with Stripe.
case ACTIVE -> latestTransactionFailed ? SubscriptionStatus.PAST_DUE : SubscriptionStatus.ACTIVE;
case CANCELED, EXPIRED -> SubscriptionStatus.CANCELED;
case PAST_DUE -> SubscriptionStatus.PAST_DUE;
case PENDING -> SubscriptionStatus.INCOMPLETE;
@@ -435,9 +437,11 @@ public class BraintreeManager implements SubscriptionProcessorManager {
final Optional<Transaction> latestTransaction = getLatestTransactionForSubscription(subscription);
boolean latestTransactionFailed = false;
if (latestTransaction.isPresent()){
paymentProcessing = isPaymentProcessing(latestTransaction.get().getStatus());
if (getPaymentStatus(latestTransaction.get().getStatus()) != PaymentStatus.SUCCEEDED) {
latestTransactionFailed = true;
chargeFailure = createChargeFailure(latestTransaction.get());
}
}
@@ -450,7 +454,7 @@ public class BraintreeManager implements SubscriptionProcessorManager {
endOfCurrentPeriod,
Subscription.Status.ACTIVE == subscription.getStatus(),
!subscription.neverExpires(),
getSubscriptionStatus(subscription.getStatus()),
getSubscriptionStatus(subscription.getStatus(), latestTransactionFailed),
latestTransaction.map(this::getPaymentMethodFromTransaction).orElse(PaymentMethod.PAYPAL),
paymentProcessing,
chargeFailure
@@ -523,27 +527,35 @@ public class BraintreeManager implements SubscriptionProcessorManager {
@Override
public CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId) {
return getSubscription(subscriptionId)
.thenApply(BraintreeManager::getSubscription)
.thenApply(subscription -> getLatestTransactionForSubscription(subscription)
.map(transaction -> {
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true);
if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals(SubscriptionStatus.PAST_DUE)) {
throw new WebApplicationException(Response.Status.NO_CONTENT);
}
return getLatestTransactionForSubscription(subscriptionId).thenApply(maybeTransaction -> maybeTransaction.map(transaction -> {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(Map.of("chargeFailure", createChargeFailure(transaction)))
.build());
}
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
throw new WebApplicationException(Response.Status.PAYMENT_REQUIRED);
}
final Instant expiration = transaction.getSubscriptionDetails().getBillingPeriodEndDate().toInstant();
final Plan plan = braintreeGateway.plan().find(transaction.getPlanId());
final Instant expiration = transaction.getSubscriptionDetails().getBillingPeriodEndDate().toInstant();
final Plan plan = braintreeGateway.plan().find(transaction.getPlanId());
final BraintreePlanMetadata metadata;
try {
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
final BraintreePlanMetadata metadata;
try {
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return new ReceiptItem(transaction.getId(), expiration, metadata.level());
}).orElseThrow(() -> new WebApplicationException(Response.Status.NO_CONTENT)));
return new ReceiptItem(transaction.getId(), expiration, metadata.level());
})
.orElseThrow(() -> new WebApplicationException(Response.Status.NO_CONTENT)));
}
private static Subscription getSubscription(Object subscriptionObj) {
@@ -553,12 +565,6 @@ public class BraintreeManager implements SubscriptionProcessorManager {
return subscription;
}
public CompletableFuture<Optional<Transaction>> getLatestTransactionForSubscription(String subscriptionId) {
return getSubscription(subscriptionId)
.thenApply(BraintreeManager::getSubscription)
.thenApply(this::getLatestTransactionForSubscription);
}
private Optional<Transaction> getLatestTransactionForSubscription(Subscription subscription) {
return subscription.getTransactions().stream()
.max(Comparator.comparing(Transaction::getCreatedAt));
@@ -568,23 +568,11 @@ public class StripeManager implements SubscriptionProcessorManager {
@Override
public CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId) {
return getLatestInvoiceForSubscription(subscriptionId)
return getSubscription(subscriptionId)
.thenApply(stripeSubscription -> getSubscription(stripeSubscription).getLatestInvoiceObject())
.thenCompose(invoice -> convertInvoiceToReceipt(invoice, subscriptionId));
}
public CompletableFuture<Invoice> getLatestInvoiceForSubscription(String subscriptionId) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
.addExpand("latest_invoice")
.build();
try {
return stripeClient.subscriptions().retrieve(subscriptionId, params, commonOptions()).getLatestInvoiceObject();
} catch (StripeException e) {
throw new CompletionException(e);
}
}, executor);
}
private CompletableFuture<ReceiptItem> convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId) {
if (latestSubscriptionInvoice == null) {
throw new WebApplicationException(Status.NO_CONTENT);
@@ -84,7 +84,7 @@ public interface SubscriptionProcessorManager {
INCOMPLETE("incomplete"),
/**
* Payment on the latest renewal either failed or wasn't attempted.
* Payment on the latest renewal failed but there are processor retries left, or payment wasn't attempted.
*/
PAST_DUE("past_due"),
@@ -3,6 +3,8 @@ package org.whispersystems.textsecuregcm.util;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientConfiguration;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -11,12 +13,14 @@ public class DynamoDbFromConfig {
public static DynamoDbClient client(DynamoDbClientConfiguration config, AwsCredentialsProvider credentialsProvider) {
return DynamoDbClient.builder()
.region(Region.of(config.getRegion()))
.region(Region.of(config.region()))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(config.getClientExecutionTimeout())
.apiCallAttemptTimeout(config.getClientRequestTimeout())
.apiCallTimeout(config.clientExecutionTimeout())
.apiCallAttemptTimeout(config.clientRequestTimeout())
.build())
.httpClientBuilder(ApacheHttpClient.builder()
.maxConnections(config.maxConnections()))
.build();
}
@@ -24,12 +28,14 @@ public class DynamoDbFromConfig {
DynamoDbClientConfiguration config,
AwsCredentialsProvider credentialsProvider) {
return DynamoDbAsyncClient.builder()
.region(Region.of(config.getRegion()))
.region(Region.of(config.region()))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(config.getClientExecutionTimeout())
.apiCallAttemptTimeout(config.getClientRequestTimeout())
.apiCallTimeout(config.clientExecutionTimeout())
.apiCallAttemptTimeout(config.clientRequestTimeout())
.build())
.httpClientBuilder(NettyNioAsyncHttpClient.builder()
.maxConcurrency(config.maxConnections()))
.build();
}
}
@@ -16,8 +16,12 @@ import java.util.Locale;
import java.util.Locale.LanguageRange;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
public class Util {
@@ -28,6 +32,12 @@ public class Util {
public static final Runnable NOOP = () -> {};
// Use `CompletableFuture#thenApply(ASYNC_EMPTY_RESPONSE) to convert futures to
// CompletableFuture<Response> instead of using NOOP to convert them to CompletableFuture<Void>
// for jersey controllers; https://github.com/eclipse-ee4j/jersey/issues/3901 causes controllers
// returning Void futures to behave differently than synchronous controllers returning void
public static final Function<Object, Response> ASYNC_EMPTY_RESPONSE = ignored -> Response.noContent().build();
/**
* Checks that the given number is a valid, E164-normalized phone number.
*
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.util.logging;
import ch.qos.logback.access.spi.IAccessEvent;
import ch.qos.logback.core.filter.Filter;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.filter.FilterFactory;
import io.dropwizard.logging.common.filter.FilterFactory;
@JsonTypeName("requestLogEnabled")
class RequestLogEnabledFilterFactory implements FilterFactory<IAccessEvent> {
@@ -5,10 +5,10 @@
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.Application;
import io.dropwizard.cli.Cli;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.Cli;
import io.dropwizard.core.cli.EnvironmentCommand;
import io.dropwizard.core.setup.Environment;
import java.util.Objects;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@@ -8,9 +8,9 @@ package org.whispersystems.textsecuregcm.workers;
import static com.codahale.metrics.MetricRegistry.name;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.Application;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.EnvironmentCommand;
import io.dropwizard.core.setup.Environment;
import io.lettuce.core.resource.ClientResources;
import java.time.Clock;
import java.util.Base64;
@@ -7,6 +7,11 @@ package org.whispersystems.textsecuregcm.workers;
import com.google.common.base.MoreObjects;
import com.google.protobuf.ByteString;
import io.dropwizard.core.cli.Command;
import io.dropwizard.core.setup.Bootstrap;
import java.security.InvalidKeyException;
import java.util.Base64;
import java.util.Set;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@@ -15,13 +20,6 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import java.security.InvalidKeyException;
import java.util.Base64;
import java.util.Set;
import io.dropwizard.cli.Command;
import io.dropwizard.setup.Bootstrap;
public class CertificateCommand extends Command {
private static final Set<Integer> RESERVED_CERTIFICATE_IDS = Set.of(
@@ -5,8 +5,8 @@
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.cli.Command;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.core.cli.Command;
import io.dropwizard.core.setup.Bootstrap;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.workers;
import static com.codahale.metrics.MetricRegistry.name;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.setup.Environment;
import io.lettuce.core.resource.ClientResources;
import java.io.IOException;
import java.security.cert.CertificateException;
@@ -6,9 +6,9 @@
package org.whispersystems.textsecuregcm.workers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.Application;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.EnvironmentCommand;
import io.dropwizard.core.setup.Environment;
import java.util.Optional;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@@ -5,9 +5,9 @@
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.Application;
import io.dropwizard.cli.ServerCommand;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.ServerCommand;
import io.dropwizard.core.setup.Environment;
import java.time.Duration;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@@ -62,9 +62,14 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(), deps.messagesManager(),
deps.accountsManager(),
deps.clientPresenceManager(),
deps.keysManager(),
dynamicConfigurationManager,
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
namespace.getInt(WORKER_COUNT));
namespace.getInt(WORKER_COUNT),
environment.lifecycle().executorService("messagePersisterUnlinkDeviceExecutor-%d")
.maxThreads(2)
.build());
environment.lifecycle().manage(deps.messagesCache());
environment.lifecycle().manage(messagePersister);
@@ -7,9 +7,10 @@ package org.whispersystems.textsecuregcm.workers;
import static com.codahale.metrics.MetricRegistry.name;
import io.dropwizard.Application;
import io.dropwizard.cli.ServerCommand;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.ServerCommand;
import io.dropwizard.core.setup.Environment;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@@ -5,8 +5,8 @@
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.cli.Command;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.core.cli.Command;
import io.dropwizard.core.setup.Bootstrap;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
@@ -6,9 +6,9 @@
package org.whispersystems.textsecuregcm.workers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.Application;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.EnvironmentCommand;
import io.dropwizard.core.setup.Environment;
import java.util.Optional;
import java.util.UUID;
import net.sourceforge.argparse4j.inf.Namespace;
@@ -6,9 +6,9 @@
package org.whispersystems.textsecuregcm.workers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.Application;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.EnvironmentCommand;
import io.dropwizard.core.setup.Environment;
import java.util.List;
import java.util.UUID;
@@ -5,15 +5,14 @@
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.core.cli.Command;
import io.dropwizard.core.setup.Bootstrap;
import java.util.Base64;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.signal.libsignal.zkgroup.ServerPublicParams;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import io.dropwizard.cli.Command;
import io.dropwizard.setup.Bootstrap;
import java.util.Base64;
public class ZkParamsCommand extends Command {
public ZkParamsCommand() {
@@ -61,8 +61,9 @@ service Accounts {
rpc DeleteUsernameHash(DeleteUsernameHashRequest) returns (DeleteUsernameHashResponse) {}
/**
* Generates a new link handle for the given username ciphertext, displacing
* any previously-existing link handle.
* Associates the given username ciphertext with the account, replacing any
* previously stored ciphertext. A new link handle will optionally be created,
* and the link handle to use will be returned in any event.
*
* This RPC may fail with a status of `FAILED_PRECONDITION` if the
* authenticated account does not have a username. It may also fail with
@@ -235,6 +236,13 @@ message SetUsernameLinkRequest {
* The username ciphertext for which to generate a new link handle.
*/
bytes username_ciphertext = 1;
/**
* If true and the account already had an encrypted username stored, the
* existing link handle will be reused. Otherwise a new link handle will be
* created.
*/
bool keep_link_handle = 2;
}
message SetUsernameLinkResponse {
@@ -19,7 +19,6 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.auth.Auth;
import io.dropwizard.auth.PolymorphicAuthDynamicFeature;
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
@@ -28,9 +27,11 @@ import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
@@ -57,6 +58,7 @@ import javax.ws.rs.core.Response;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
@@ -337,7 +339,7 @@ class AuthEnablementRefreshRequirementProviderTest {
provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("test", account, authenticatedDevice), new ProtobufWebSocketMessageFactory(),
Optional.empty(), 30000);
Optional.empty(), Duration.ofMillis(30000));
remoteEndpoint = mock(RemoteEndpoint.class);
Session session = mock(Session.class);
@@ -363,9 +365,9 @@ class AuthEnablementRefreshRequirementProviderTest {
}
private SubProtocol.WebSocketResponseMessage verifyAndGetResponse(final RemoteEndpoint remoteEndpoint)
throws InvalidProtocolBufferException {
throws IOException {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
return SubProtocol.WebSocketMessage.parseFrom(responseBytesCaptor.getValue().array()).getResponse();
}
@@ -38,6 +38,7 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
@@ -52,6 +53,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.signal.libsignal.usernames.BaseUsernameException;
@@ -71,6 +73,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLock;
import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashRequest;
import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameLinkHandle;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
@@ -88,6 +91,7 @@ import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableExceptio
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
@@ -735,7 +739,7 @@ class AccountControllerTest {
@Test
void testDeleteUsername() {
when(accountsManager.clearUsernameHash(any()))
.thenAnswer(invocation -> CompletableFuture.completedFuture(invocation.getArgument(0)));
.thenAnswer(invocation -> CompletableFutureTestUtil.almostCompletedFuture(invocation.getArgument(0)));
Response response =
resources.getJerseyTest()
@@ -744,6 +748,7 @@ class AccountControllerTest {
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.delete();
assertThat(response.readEntity(String.class)).isEqualTo("");
assertThat(response.getStatus()).isEqualTo(204);
verify(accountsManager).clearUsernameHash(AuthHelper.VALID_ACCOUNT);
}
@@ -826,6 +831,8 @@ class AccountControllerTest {
@Test
void testDeleteAccount() {
when(accountsManager.delete(any(), any())).thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
Response response =
resources.getJerseyTest()
.target("/v1/accounts/me")
@@ -998,4 +1005,24 @@ class AccountControllerTest {
.get()
.getStatus()).isEqualTo(422);
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void testPutUsernameLink(boolean keepLink) {
when(rateLimiters.forDescriptor(eq(RateLimiters.For.USERNAME_LINK_OPERATION))).thenReturn(mock(RateLimiter.class));
final UUID oldLinkHandle = UUID.randomUUID();
when(AuthHelper.VALID_ACCOUNT.getUsernameLinkHandle()).thenReturn(oldLinkHandle);
final byte[] encryptedUsername = "some encrypted goop".getBytes();
final UsernameLinkHandle newHandle = resources.getJerseyTest()
.target("/v1/accounts/username_link")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.json(new EncryptedUsername(encryptedUsername, keepLink)), UsernameLinkHandle.class);
assertThat(newHandle.usernameLinkHandle().equals(oldLinkHandle)).isEqualTo(keepLink);
verify(AuthHelper.VALID_ACCOUNT).setUsernameLinkDetails(eq(newHandle.usernameLinkHandle()), eq(encryptedUsername));
}
}
@@ -74,6 +74,7 @@ import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
class KeysControllerTest {
@@ -235,9 +236,9 @@ class KeysControllerTest {
when(rateLimiters.getPreKeysLimiter()).thenReturn(rateLimiter);
when(KEYS.store(any(), anyByte(), any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(KEYS.store(any(), anyByte(), any(), any(), any(), any())).thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
when(KEYS.getEcSignedPreKey(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(KEYS.storeEcSignedPreKeys(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(KEYS.storeEcSignedPreKeys(any(), any())).thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
when(KEYS.takeEC(EXISTS_UUID, sampleDeviceId)).thenReturn(
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
@@ -32,6 +32,7 @@ import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.jsonFixtur
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.ByteString;
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
@@ -121,6 +122,7 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -165,7 +167,7 @@ class MessageControllerTest {
private static final RateLimiter rateLimiter = mock(RateLimiter.class);
private static final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
private static final ExecutorService multiRecipientMessageExecutor = mock(ExecutorService.class);
private static final ExecutorService multiRecipientMessageExecutor = MoreExecutors.newDirectExecutorService();
private static final Scheduler messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
private static final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
@@ -251,8 +253,7 @@ class MessageControllerTest {
rateLimiter,
cardinalityEstimator,
pushNotificationManager,
reportMessageManager,
multiRecipientMessageExecutor
reportMessageManager
);
}
@@ -610,19 +611,19 @@ class MessageControllerTest {
UUID uuid1 = UUID.randomUUID();
when(messagesManager.delete(AuthHelper.VALID_UUID, (byte) 1, uuid1, null))
.thenReturn(
CompletableFuture.completedFuture(Optional.of(generateEnvelope(uuid1, Envelope.Type.CIPHERTEXT_VALUE,
CompletableFutureTestUtil.almostCompletedFuture(Optional.of(generateEnvelope(uuid1, Envelope.Type.CIPHERTEXT_VALUE,
timestamp, sourceUuid, (byte) 1, AuthHelper.VALID_UUID, null, "hi".getBytes(), 0))));
UUID uuid2 = UUID.randomUUID();
when(messagesManager.delete(AuthHelper.VALID_UUID, (byte) 1, uuid2, null))
.thenReturn(
CompletableFuture.completedFuture(Optional.of(generateEnvelope(
CompletableFutureTestUtil.almostCompletedFuture(Optional.of(generateEnvelope(
uuid2, Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE,
System.currentTimeMillis(), sourceUuid, (byte) 1, AuthHelper.VALID_UUID, null, null, 0))));
UUID uuid3 = UUID.randomUUID();
when(messagesManager.delete(AuthHelper.VALID_UUID, (byte) 1, uuid3, null))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(Optional.empty()));
UUID uuid4 = UUID.randomUUID();
when(messagesManager.delete(AuthHelper.VALID_UUID, (byte) 1, uuid4, null))
@@ -989,19 +990,6 @@ class MessageControllerTest {
// set up the entity to use in our PUT request
Entity<InputStream> entity = Entity.entity(stream, MultiRecipientMessageProvider.MEDIA_TYPE);
when(multiRecipientMessageExecutor.invokeAll(any()))
.thenAnswer(answer -> {
final List<Callable> tasks = answer.getArgument(0, List.class);
tasks.forEach(c -> {
try {
c.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
return null;
});
// start building the request
Invocation.Builder bldr = resources
.getJerseyTest()
@@ -1109,6 +1097,32 @@ class MessageControllerTest {
);
}
@Test
void testMultiRecipientMessageToAccountsSomeOfWhichDoNotExist() throws Exception {
UUID badUUID = UUID.fromString("33333333-3333-3333-3333-333333333333");
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(badUUID))).thenReturn(Optional.empty());
final List<Recipient> recipients = List.of(
new Recipient(new AciServiceIdentifier(SINGLE_DEVICE_UUID), SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1,
new byte[48]),
new Recipient(new AciServiceIdentifier(badUUID), (byte) 1, 1, new byte[48]));
Response response = resources
.getJerseyTest()
.target("/v1/messages/multi_recipient")
.queryParam("online", true)
.queryParam("ts", 1700000000000L)
.queryParam("story", true)
.queryParam("urgent", false)
.request()
.header(HttpHeaders.USER_AGENT, "cluck cluck, i'm a parrot")
.header(OptionalAccess.UNIDENTIFIED, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
.put(Entity.entity(initializeMultiPayload(recipients, new byte[2048], true),
MultiRecipientMessageProvider.MEDIA_TYPE));
checkGoodMultiRecipientResponse(response, 1);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testMultiRecipientRedisBombProtection(final boolean useExplicitIdentifier) throws Exception {
@@ -1315,19 +1329,6 @@ class MessageControllerTest {
void sendMultiRecipientMessage404(final ServiceIdentifier serviceIdentifier)
throws NotPushRegisteredException, InterruptedException {
when(multiRecipientMessageExecutor.invokeAll(any()))
.thenAnswer(answer -> {
final List<Callable> tasks = answer.getArgument(0, List.class);
tasks.forEach(c -> {
try {
c.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
return null;
});
final List<Recipient> recipients = List.of(
new Recipient(serviceIdentifier, MULTI_DEVICE_ID1, MULTI_DEVICE_REG_ID1, new byte[48]),
new Recipient(serviceIdentifier, MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2, new byte[48]));
@@ -1370,14 +1371,12 @@ class MessageControllerTest {
private void checkBadMultiRecipientResponse(Response response, int expectedCode) throws Exception {
assertThat("Unexpected response", response.getStatus(), is(equalTo(expectedCode)));
verify(messageSender, never()).sendMessage(any(), any(), any(), anyBoolean());
verify(multiRecipientMessageExecutor, never()).invokeAll(any());
}
private void checkGoodMultiRecipientResponse(Response response, int expectedCount) throws Exception {
assertThat("Unexpected response", response.getStatus(), is(equalTo(200)));
ArgumentCaptor<List<Callable<Void>>> captor = ArgumentCaptor.forClass(List.class);
verify(multiRecipientMessageExecutor, times(1)).invokeAll(captor.capture());
assert (captor.getValue().size() == expectedCount);
verify(messageSender, times(expectedCount)).sendMessage(any(), any(), any(), anyBoolean());
SendMultiRecipientMessageResponse smrmr = response.readEntity(SendMultiRecipientMessageResponse.class);
assert (smrmr.uuids404().isEmpty());
}
@@ -802,6 +802,7 @@ class SubscriptionControllerTest {
.header(HttpHeaders.USER_AGENT, userAgent)
.get(GetSubscriptionConfigurationResponse.class);
assertThat(response.sepaMaximumEuros()).isEqualTo("10000");
assertThat(response.currencies()).containsKeys("usd", "jpy", "bif", "eur").satisfies(currencyMap -> {
assertThat(currencyMap).extractingByKey("usd").satisfies(currency -> {
assertThat(currency.minimum()).isEqualByComparingTo(
@@ -1087,7 +1088,7 @@ class SubscriptionControllerTest {
- '8000'
- '9000'
- '10000'
sepaMaxTransactionSizeEuros: '10000'
sepaMaximumEuros: '10000'
""";
}
@@ -521,10 +521,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
verify(accountsManager).clearUsernameHash(account);
}
@Test
void setUsernameLink() {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void setUsernameLink(final boolean keepLink) {
final Account account = mock(Account.class);
final UUID oldHandle = UUID.randomUUID();
when(account.getUsernameHash()).thenReturn(Optional.of(new byte[AccountController.USERNAME_HASH_LENGTH]));
when(account.getUsernameLinkHandle()).thenReturn(oldHandle);
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
@@ -535,12 +538,14 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final SetUsernameLinkResponse response =
authenticatedServiceStub().setUsernameLink(SetUsernameLinkRequest.newBuilder()
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
.setKeepLinkHandle(keepLink)
.build());
final ArgumentCaptor<UUID> linkHandleCaptor = ArgumentCaptor.forClass(UUID.class);
verify(account).setUsernameLinkDetails(linkHandleCaptor.capture(), eq(usernameCiphertext));
assertEquals(keepLink, oldHandle.equals(linkHandleCaptor.getValue()));
final SetUsernameLinkResponse expectedResponse = SetUsernameLinkResponse.newBuilder()
.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandleCaptor.getValue()))
.build();
@@ -22,8 +22,10 @@ import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.Principal;
import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
@@ -36,6 +38,7 @@ import javax.ws.rs.Path;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ContainerResponse;
@@ -121,7 +124,7 @@ class MetricsRequestEventListenerTest {
}
@Test
void testActualRouteMessageSuccess() throws InvalidProtocolBufferException {
void testActualRouteMessageSuccess() throws IOException {
final MetricsApplicationEventListener applicationEventListener = mock(MetricsApplicationEventListener.class);
when(applicationEventListener.onRequest(any())).thenReturn(listener);
@@ -140,7 +143,7 @@ class MetricsRequestEventListenerTest {
new TestPrincipal("foo"),
new ProtobufWebSocketMessageFactory(),
Optional.empty(),
30000);
Duration.ofMillis(30000));
final Session session = mock(Session.class);
final RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -163,7 +166,7 @@ class MetricsRequestEventListenerTest {
provider.onWebSocketBinary(message, 0, message.length);
final ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -187,7 +190,7 @@ class MetricsRequestEventListenerTest {
}
@Test
void testActualRouteMessageSuccessNoUserAgent() throws InvalidProtocolBufferException {
void testActualRouteMessageSuccessNoUserAgent() throws IOException {
final MetricsApplicationEventListener applicationEventListener = mock(MetricsApplicationEventListener.class);
when(applicationEventListener.onRequest(any())).thenReturn(listener);
@@ -200,8 +203,10 @@ class MetricsRequestEventListenerTest {
final ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
final WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
final WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
final WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1",
applicationHandler,
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
final Session session = mock(Session.class);
final RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -222,7 +227,7 @@ class MetricsRequestEventListenerTest {
provider.onWebSocketBinary(message, 0, message.length);
final ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -115,8 +115,6 @@ class PushNotificationManagerTest {
when(device.getApnId()).thenReturn(deviceToken);
when(apnSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
when(apnPushNotificationScheduler.scheduleBackgroundNotification(account, device))
.thenReturn(CompletableFuture.completedFuture(null));
} else {
when(device.getGcmId()).thenReturn(deviceToken);
when(fcmSender.sendNotification(any()))
@@ -129,7 +127,6 @@ class PushNotificationManagerTest {
if (isApn){
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN,
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, "someContext", account, device, true));
verify(apnPushNotificationScheduler).scheduleBackgroundNotification(account, device);
} else {
verify(fcmSender, times(1)).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM,
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, "someContext", account, device, true));
@@ -137,7 +137,7 @@ class AccountsManagerTest {
//noinspection unchecked
asyncCommands = mock(RedisAdvancedClusterAsyncCommands.class);
when(asyncCommands.del(any())).thenReturn(MockRedisFuture.completedFuture(0L));
when(asyncCommands.del(any(String[].class))).thenReturn(MockRedisFuture.completedFuture(0L));
when(asyncCommands.get(any())).thenReturn(MockRedisFuture.completedFuture(null));
when(asyncCommands.setex(any(), anyLong(), any())).thenReturn(MockRedisFuture.completedFuture("OK"));
@@ -34,6 +34,7 @@ import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@@ -45,6 +46,7 @@ import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
@@ -323,6 +325,75 @@ class AccountsTest {
verifyStoredState("+14151112222", uuid, null, null, retrieved.get(), account);
}
// State before the account is re-registered
enum UsernameStatus {
NONE,
RESERVED,
RESERVED_WITH_SAVED_LINK,
CONFIRMED
}
@ParameterizedTest
@EnumSource(UsernameStatus.class)
void reclaimAccountWithNoUsername(UsernameStatus usernameStatus) {
Device device = generateDevice(DEVICE_ID_1);
UUID firstUuid = UUID.randomUUID();
UUID firstPni = UUID.randomUUID();
Account account = generateAccount("+14151112222", firstUuid, firstPni, List.of(device));
accounts.create(account);
final byte[] usernameHash = randomBytes(32);
final byte[] encryptedUsername = randomBytes(32);
switch (usernameStatus) {
case NONE:
break;
case RESERVED:
accounts.reserveUsernameHash(account, randomBytes(32), Duration.ofMinutes(1)).join();
break;
case RESERVED_WITH_SAVED_LINK:
// give the account a username
accounts.reserveUsernameHash(account, usernameHash, Duration.ofMinutes(1)).join();
accounts.confirmUsernameHash(account, usernameHash, encryptedUsername).join();
// simulate a failed re-reg: we give the account a reclaimable username, but we'll try
// re-registering again later in the test case
account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
accounts.create(account);
break;
case CONFIRMED:
accounts.reserveUsernameHash(account, usernameHash, Duration.ofMinutes(1)).join();
accounts.confirmUsernameHash(account, usernameHash, encryptedUsername).join();
break;
}
Optional<UUID> preservedLink = Optional.ofNullable(account.getUsernameLinkHandle());
// re-register the account
account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
accounts.create(account);
// If we had a username link, or we had previously saved a username link from another re-registration, make sure
// we preserve it
accounts.confirmUsernameHash(account, usernameHash, encryptedUsername).join();
boolean shouldReuseLink = switch (usernameStatus) {
case RESERVED_WITH_SAVED_LINK, CONFIRMED -> true;
case NONE, RESERVED -> false;
};
// If we had a reclaimable username, make sure we preserved the link.
assertThat(account.getUsernameLinkHandle().equals(preservedLink.orElse(null)))
.isEqualTo(shouldReuseLink);
// in all cases, we should now have usernameHash, usernameLink, and encryptedUsername set
assertThat(account.getUsernameHash()).isNotEmpty();
assertThat(account.getEncryptedUsername()).isNotEmpty();
assertThat(account.getUsernameLinkHandle()).isNotNull();
assertThat(account.getReservedUsernameHash()).isEmpty();
}
@Test
void testOverwrite() {
Device device = generateDevice(DEVICE_ID_1);
@@ -332,14 +403,12 @@ class AccountsTest {
accounts.create(account);
final SecureRandom byteGenerator = new SecureRandom();
final byte[] usernameHash = new byte[32];
byteGenerator.nextBytes(usernameHash);
final byte[] encryptedUsername = new byte[16];
byteGenerator.nextBytes(encryptedUsername);
final byte[] usernameHash = randomBytes(32);
final byte[] encryptedUsername = randomBytes(16);
// Set up the existing account to have a username hash
accounts.confirmUsernameHash(account, usernameHash, encryptedUsername).join();
final UUID usernameLinkHandle = account.getUsernameLinkHandle();
verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), usernameHash, account, true);
@@ -355,14 +424,35 @@ class AccountsTest {
final boolean freshUser = accounts.create(account);
assertThat(freshUser).isFalse();
verifyStoredState("+14151112222", firstUuid, firstPni, usernameHash, account, true);
// usernameHash should be unset
verifyStoredState("+14151112222", firstUuid, firstPni, null, account, true);
// username should become 'reclaimable'
Map<String, AttributeValue> item = readAccount(firstUuid);
Account result = Accounts.fromItem(item);
assertThat(AttributeValues.getUUID(item, Accounts.ATTR_USERNAME_LINK_UUID, null))
.isEqualTo(usernameLinkHandle)
.isEqualTo(result.getUsernameLinkHandle());
assertThat(result.getUsernameHash()).isEmpty();
assertThat(result.getEncryptedUsername()).isEmpty();
assertArrayEquals(result.getReservedUsernameHash().get(), usernameHash);
// should keep the same usernameLink, now encryptedUsername should be set
accounts.confirmUsernameHash(result, usernameHash, encryptedUsername).join();
item = readAccount(firstUuid);
result = Accounts.fromItem(item);
assertThat(AttributeValues.getUUID(item, Accounts.ATTR_USERNAME_LINK_UUID, null))
.isEqualTo(usernameLinkHandle)
.isEqualTo(result.getUsernameLinkHandle());
assertArrayEquals(result.getEncryptedUsername().get(), encryptedUsername);
assertArrayEquals(result.getUsernameHash().get(), usernameHash);
assertThat(result.getReservedUsernameHash()).isEmpty();
assertPhoneNumberConstraintExists("+14151112222", firstUuid);
assertPhoneNumberIdentifierConstraintExists(firstPni, firstUuid);
device = generateDevice(DEVICE_ID_1);
Account invalidAccount = generateAccount("+14151113333", firstUuid, UUID.randomUUID(), List.of(device));
assertThatThrownBy(() -> accounts.create(invalidAccount));
}
@@ -1078,6 +1168,17 @@ class AccountsTest {
assertThat(pniConstraintResponse.hasItem()).isFalse();
}
private Map<String, AttributeValue> readAccount(final UUID uuid) {
final DynamoDbClient db = DYNAMO_DB_EXTENSION.getDynamoDbClient();
final GetItemResponse get = db.getItem(GetItemRequest.builder()
.tableName(Tables.ACCOUNTS.tableName())
.key(Map.of(Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
.consistentRead(true)
.build());
return get.item();
}
private void verifyStoredState(String number, UUID uuid, UUID pni, byte[] usernameHash, Account expecting, boolean canonicallyDiscoverable) {
final DynamoDbClient db = DYNAMO_DB_EXTENSION.getDynamoDbClient();
@@ -1131,4 +1232,10 @@ class AccountsTest {
assertThat(resultDevice.getCreated()).isEqualTo(expectingDevice.getCreated());
}
}
private static byte[] randomBytes(int count) {
byte[] bytes = new byte[count];
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
}
@@ -32,7 +32,9 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
@@ -83,7 +85,8 @@ class MessagePersisterIntegrationTest {
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
messageDeletionExecutorService);
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
dynamicConfigurationManager, PERSIST_DELAY, 1);
mock(ClientPresenceManager.class), mock(KeysManager.class), dynamicConfigurationManager, PERSIST_DELAY, 1,
Executors.newSingleThreadExecutor());
account = mock(Account.class);
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.mockito.ArgumentMatchers.any;
@@ -16,9 +17,13 @@ import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.util.MockUtils.exactly;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.ByteString;
import io.lettuce.core.cluster.SlotHash;
import java.nio.charset.StandardCharsets;
@@ -28,6 +33,7 @@ import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -41,9 +47,14 @@ import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
class MessagePersisterTest {
@@ -57,7 +68,10 @@ class MessagePersisterTest {
private MessagesDynamoDb messagesDynamoDb;
private MessagePersister messagePersister;
private AccountsManager accountsManager;
private ClientPresenceManager clientPresenceManager;
private KeysManager keysManager;
private MessagesManager messagesManager;
private Account destinationAccount;
private static final UUID DESTINATION_ACCOUNT_UUID = UUID.randomUUID();
private static final String DESTINATION_ACCOUNT_NUMBER = "+18005551234";
@@ -74,11 +88,13 @@ class MessagePersisterTest {
messagesDynamoDb = mock(MessagesDynamoDb.class);
accountsManager = mock(AccountsManager.class);
clientPresenceManager = mock(ClientPresenceManager.class);
keysManager = mock(KeysManager.class);
destinationAccount = mock(Account.class);;
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(DESTINATION_ACCOUNT_UUID)).thenReturn(Optional.of(account));
when(account.getNumber()).thenReturn(DESTINATION_ACCOUNT_NUMBER);
when(accountsManager.getByAccountIdentifier(DESTINATION_ACCOUNT_UUID)).thenReturn(Optional.of(destinationAccount));
when(destinationAccount.getUuid()).thenReturn(DESTINATION_ACCOUNT_UUID);
when(destinationAccount.getNumber()).thenReturn(DESTINATION_ACCOUNT_NUMBER);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
sharedExecutorService = Executors.newSingleThreadExecutor();
@@ -87,8 +103,8 @@ class MessagePersisterTest {
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, messageDeliveryScheduler,
sharedExecutorService, Clock.systemUTC());
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
dynamicConfigurationManager, PERSIST_DELAY, 1);
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, clientPresenceManager,
keysManager, dynamicConfigurationManager, PERSIST_DELAY, 1, MoreExecutors.newDirectExecutorService());
when(messagesManager.persistMessages(any(UUID.class), anyByte(), any())).thenAnswer(invocation -> {
final UUID destinationUuid = invocation.getArgument(0);
@@ -172,6 +188,7 @@ class MessagePersisterTest {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(accountUuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(accountUuid);
when(account.getNumber()).thenReturn(accountNumber);
insertMessages(accountUuid, deviceId, messagesPerQueue, now);
@@ -223,7 +240,150 @@ class MessagePersisterTest {
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
assertThrows(MessagePersistenceException.class,
() -> messagePersister.persistQueue(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)));
() -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE_ID)));
}
@Test
void testUnlinkFirstInactiveDeviceOnFullQueue() {
final String queueName = new String(
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
final int messageCount = 1;
final Instant now = Instant.now();
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
setNextSlotToPersist(SlotHash.getSlot(queueName));
final Device primary = mock(Device.class);
when(primary.getId()).thenReturn((byte) 1);
when(primary.isPrimary()).thenReturn(true);
when(primary.isEnabled()).thenReturn(true);
final Device activeA = mock(Device.class);
when(activeA.getId()).thenReturn((byte) 2);
when(activeA.isEnabled()).thenReturn(true);
final Device inactiveB = mock(Device.class);
final byte inactiveId = 3;
when(inactiveB.getId()).thenReturn(inactiveId);
when(inactiveB.isEnabled()).thenReturn(false);
final Device inactiveC = mock(Device.class);
when(inactiveC.getId()).thenReturn((byte) 4);
when(inactiveC.isEnabled()).thenReturn(false);
final Device activeD = mock(Device.class);
when(activeD.getId()).thenReturn((byte) 5);
when(activeD.isEnabled()).thenReturn(true);
final Device destination = mock(Device.class);
when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID);
when(destination.isEnabled()).thenReturn(true);
when(destinationAccount.getDevices()).thenReturn(List.of(primary, activeA, inactiveB, inactiveC, activeD, destination));
when(messagesManager.persistMessages(any(UUID.class), anyByte(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.delete(any(), eq(inactiveId))).thenReturn(CompletableFuture.completedFuture(null));
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE_ID));
verify(messagesManager, exactly()).clear(DESTINATION_ACCOUNT_UUID, inactiveId);
}
@Test
void testUnlinkActiveDeviceWithOldestMessageOnFullQueueWithNoInactiveDevices() {
final String queueName = new String(
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
final int messageCount = 1;
final Instant now = Instant.now();
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
setNextSlotToPersist(SlotHash.getSlot(queueName));
final Device primary = mock(Device.class);
final byte primaryId = 1;
when(primary.getId()).thenReturn(primaryId);
when(primary.isPrimary()).thenReturn(true);
when(primary.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(primaryId)))
.thenReturn(Mono.just(4L));
final Device deviceA = mock(Device.class);
final byte deviceIdA = 2;
when(deviceA.getId()).thenReturn(deviceIdA);
when(deviceA.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceIdA)))
.thenReturn(Mono.empty());
final Device deviceB = mock(Device.class);
final byte deviceIdB = 3;
when(deviceB.getId()).thenReturn(deviceIdB);
when(deviceB.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceIdB)))
.thenReturn(Mono.just(2L));
final Device destination = mock(Device.class);
when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID);
when(destination.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(DESTINATION_DEVICE_ID)))
.thenReturn(Mono.just(5L));
when(destinationAccount.getDevices()).thenReturn(List.of(primary, deviceA, deviceB, destination));
when(messagesManager.persistMessages(any(UUID.class), anyByte(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.delete(any(), eq(deviceIdB))).thenReturn(CompletableFuture.completedFuture(null));
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE_ID));
verify(messagesManager, exactly()).clear(DESTINATION_ACCOUNT_UUID, deviceIdB);
}
@Test
void testUnlinkDestinationDevice() {
final String queueName = new String(
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
final int messageCount = 1;
final Instant now = Instant.now();
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
setNextSlotToPersist(SlotHash.getSlot(queueName));
final Device primary = mock(Device.class);
final byte primaryId = 1;
when(primary.getId()).thenReturn(primaryId);
when(primary.isPrimary()).thenReturn(true);
when(primary.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(primaryId)))
.thenReturn(Mono.just(1L));
final Device deviceA = mock(Device.class);
final byte deviceIdA = 2;
when(deviceA.getId()).thenReturn(deviceIdA);
when(deviceA.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceIdA)))
.thenReturn(Mono.just(3L));
final Device deviceB = mock(Device.class);
final byte deviceIdB = 2;
when(deviceB.getId()).thenReturn(deviceIdB);
when(deviceB.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceIdB)))
.thenReturn(Mono.empty());
final Device destination = mock(Device.class);
when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID);
when(destination.isEnabled()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(DESTINATION_DEVICE_ID)))
.thenReturn(Mono.just(2L));
when(destinationAccount.getDevices()).thenReturn(List.of(primary, deviceA, deviceB, destination));
when(messagesManager.persistMessages(any(UUID.class), anyByte(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.delete(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE_ID));
verify(messagesManager, exactly()).clear(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID);
}
@SuppressWarnings("SameParameterValue")
@@ -265,5 +425,4 @@ class MessagePersisterTest {
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
connection -> connection.sync().set(MessagesCache.NEXT_SLOT_TO_PERSIST_KEY, String.valueOf(nextSlot - 1)));
}
}
@@ -679,7 +679,7 @@ class MessagesCacheTest {
pages.add(generatePage());
pages.add(generateStaleEphemeralPage());
when(reactiveCommands.evalsha(any(), any(), any(), any()))
when(reactiveCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class)))
.thenReturn(Flux.just(pages.pop()))
.thenReturn(Flux.just(pages.pop()))
.thenReturn(Flux.just(pages.pop()))
@@ -688,7 +688,7 @@ class MessagesCacheTest {
final AsyncCommand<?, ?, ?> removeSuccess = new AsyncCommand<>(mock(RedisCommand.class));
removeSuccess.complete();
when(asyncCommands.evalsha(any(), any(), any(), any()))
when(asyncCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class)))
.thenReturn((RedisFuture) removeSuccess);
final Publisher<?> allMessages = messagesCache.get(UUID.randomUUID(), Device.PRIMARY_ID);
@@ -696,9 +696,9 @@ class MessagesCacheTest {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(5));
// async commands are used for remove(), and nothing should happen until we are subscribed
verify(asyncCommands, never()).evalsha(any(), any(), any(byte[][].class), any(byte[].class));
verify(asyncCommands, never()).evalsha(any(), any(), any(byte[][].class), any(byte[][].class));
// the reactive commands will be called once, to prep the first page fetch (but no remote request would actually be sent)
verify(reactiveCommands, times(1)).evalsha(any(), any(), any(byte[][].class), any(byte[].class));
verify(reactiveCommands, times(1)).evalsha(any(), any(), any(byte[][].class), any(byte[][].class));
StepVerifier.create(allMessages)
.expectSubscription()
@@ -708,7 +708,7 @@ class MessagesCacheTest {
.verify();
assertTrue(pages.isEmpty());
verify(asyncCommands, atLeast(1)).evalsha(any(), any(), any(), any());
verify(asyncCommands, atLeast(1)).evalsha(any(), any(), any(byte[][].class), any(byte[][].class));
}
private List<byte[]> generatePage() {
@@ -116,6 +116,7 @@ public class AccountsHelper {
case "getNumber" -> when(updatedAccount.getNumber()).thenAnswer(stubbing);
case "getUsername" -> when(updatedAccount.getUsernameHash()).thenAnswer(stubbing);
case "getUsernameHash" -> when(updatedAccount.getUsernameHash()).thenAnswer(stubbing);
case "getUsernameLinkHandle" -> when(updatedAccount.getUsernameLinkHandle()).thenAnswer(stubbing);
case "getDevices" -> when(updatedAccount.getDevices()).thenAnswer(stubbing);
case "getDevice" -> when(updatedAccount.getDevice(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing);
case "getPrimaryDevice" -> when(updatedAccount.getPrimaryDevice()).thenAnswer(stubbing);
@@ -5,12 +5,11 @@
package org.whispersystems.textsecuregcm.tests.util;
import static io.dropwizard.testing.FixtureHelpers.fixture;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import io.dropwizard.util.Resources;
import org.whispersystems.textsecuregcm.util.SystemMapper;
public class JsonHelpers {
@@ -26,6 +25,7 @@ public class JsonHelpers {
}
public static String jsonFixture(String filename) throws IOException {
return objectMapper.writeValueAsString(objectMapper.readValue(fixture(filename), JsonNode.class));
return objectMapper.writeValueAsString(
objectMapper.readValue(Resources.getResource(filename), JsonNode.class));
}
}
@@ -50,24 +50,6 @@ public class RedisClusterHelper {
return null;
}).when(cluster).useCluster(any(Consumer.class));
when(cluster.withCluster(any(Function.class))).thenAnswer(invocation -> {
return invocation.getArgument(0, Function.class).apply(stringConnection);
});
doAnswer(invocation -> {
invocation.getArgument(0, Consumer.class).accept(stringConnection);
return null;
}).when(cluster).useCluster(any(Consumer.class));
when(cluster.withBinaryCluster(any(Function.class))).thenAnswer(invocation -> {
return invocation.getArgument(0, Function.class).apply(binaryConnection);
});
doAnswer(invocation -> {
invocation.getArgument(0, Consumer.class).accept(binaryConnection);
return null;
}).when(cluster).useBinaryCluster(any(Consumer.class));
when(cluster.withBinaryCluster(any(Function.class))).thenAnswer(invocation -> {
return invocation.getArgument(0, Function.class).apply(binaryConnection);
});
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
public class CompletableFutureTestUtil {
@@ -24,4 +25,9 @@ public class CompletableFutureTestUtil {
final CompletionException completionException = assertThrows(CompletionException.class, completableFuture::join, message);
assertTrue(ExceptionUtils.unwrap(completionException).getClass().isAssignableFrom(expectedCause), message);
}
public static <T> CompletableFuture<T> almostCompletedFuture(T result) {
return new CompletableFuture<T>().completeOnTimeout(result, 5, TimeUnit.MILLISECONDS);
}
}
@@ -9,12 +9,23 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.internal.exceptions.Reporter.noMoreInteractionsWanted;
import static org.mockito.internal.exceptions.Reporter.wantedButNotInvoked;
import static org.mockito.internal.invocation.InvocationMarker.markVerified;
import static org.mockito.internal.invocation.InvocationsFinder.findFirstUnverified;
import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import org.apache.commons.lang3.RandomUtils;
import org.mockito.Mockito;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MatchableInvocation;
import org.mockito.verification.VerificationMode;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
@@ -154,4 +165,30 @@ public final class MockUtils {
}
return new SecretBytes(bytes);
}
/**
* modeled after {@link org.mockito.Mockito#only()}, verifies that the matched invocation is the only invocation of
* this method
*/
public static VerificationMode exactly() {
return data -> {
MatchableInvocation target = data.getTarget();
final List<Invocation> allInvocations = data.getAllInvocations();
List<Invocation> chunk = findInvocations(allInvocations, target);
List<Invocation> otherInvocations = allInvocations.stream()
.filter(target::hasSameMethod)
.filter(Predicate.not(target::matches))
.toList();
if (!otherInvocations.isEmpty()) {
Invocation unverified = findFirstUnverified(otherInvocations);
throw noMoreInteractionsWanted(unverified, (List) allInvocations);
}
if (chunk.isEmpty()) {
throw wantedButNotInvoked(target);
}
markVerified(chunk.get(0), target);
};
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.util.logging;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.matches;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
@@ -20,8 +21,10 @@ import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.Principal;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -40,6 +43,7 @@ import javax.ws.rs.core.Response;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
@@ -159,7 +163,7 @@ class LoggingUnhandledExceptionMapperTest {
}
private WebSocketResourceProvider<TestPrincipal> createWebsocketProvider(final String userAgentHeader,
final Session session, final Consumer<ByteBuffer> responseHandler) {
final Session session, final Consumer<ByteBuffer> responseHandler) throws IOException {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(exceptionMapper);
resourceConfig.register(new TestController());
@@ -170,14 +174,14 @@ class LoggingUnhandledExceptionMapperTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
when(remoteEndpoint.sendBytesByFuture(any()))
.thenAnswer(answer -> {
responseHandler.accept(answer.getArgument(0, ByteBuffer.class));
return CompletableFuture.completedFuture(null);
});
doAnswer(answer -> {
responseHandler.accept(answer.getArgument(0, ByteBuffer.class));
return null;
}).when(remoteEndpoint).sendBytes(any(), any(WriteCallback.class));
UpgradeRequest request = mock(UpgradeRequest.class);
when(session.getUpgradeRequest()).thenReturn(request);
@@ -1 +0,0 @@
mock-maker-inline
+2 -8
View File
@@ -13,12 +13,11 @@
<dependencies>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-api</artifactId>
<artifactId>websocket-jetty-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-server</artifactId>
<scope>runtime</scope>
<artifactId>websocket-jetty-server</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
@@ -97,11 +96,6 @@
<artifactId>jsr305</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
@@ -14,7 +14,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketException;
import org.eclipse.jetty.websocket.api.exceptions.WebSocketException;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -99,7 +99,7 @@ public class WebSocketClient {
public void hardDisconnectQuietly() {
try {
session.disconnect();
} catch (IOException e) {
} catch (Exception e) {
// quietly we said
}
}
@@ -5,11 +5,30 @@
package org.whispersystems.websocket;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import com.google.protobuf.UninitializedMessageException;
import org.eclipse.jetty.websocket.api.MessageTooLargeException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.security.Principal;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.eclipse.jetty.websocket.api.exceptions.MessageTooLargeException;
import org.glassfish.jersey.internal.MapPropertiesDelegate;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ContainerRequest;
@@ -26,23 +45,6 @@ import org.whispersystems.websocket.session.ContextPrincipal;
import org.whispersystems.websocket.session.WebSocketSessionContext;
import org.whispersystems.websocket.setup.WebSocketConnectListener;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.security.Principal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class WebSocketResourceProvider<T extends Principal> implements WebSocketListener {
@@ -56,44 +58,44 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
private final Map<Long, CompletableFuture<WebSocketResponseMessage>> requestMap = new ConcurrentHashMap<>();
private final T authenticated;
private final WebSocketMessageFactory messageFactory;
private final T authenticated;
private final WebSocketMessageFactory messageFactory;
private final Optional<WebSocketConnectListener> connectListener;
private final ApplicationHandler jerseyHandler;
private final WebsocketRequestLog requestLog;
private final long idleTimeoutMillis;
private final String remoteAddress;
private final ApplicationHandler jerseyHandler;
private final WebsocketRequestLog requestLog;
private final Duration idleTimeout;
private final String remoteAddress;
private Session session;
private RemoteEndpoint remoteEndpoint;
private Session session;
private RemoteEndpoint remoteEndpoint;
private WebSocketSessionContext context;
private static final Set<String> EXCLUDED_UPGRADE_REQUEST_HEADERS = Set.of("connection", "upgrade");
public WebSocketResourceProvider(String remoteAddress,
ApplicationHandler jerseyHandler,
WebsocketRequestLog requestLog,
T authenticated,
WebSocketMessageFactory messageFactory,
Optional<WebSocketConnectListener> connectListener,
long idleTimeoutMillis)
{
this.remoteAddress = remoteAddress;
this.jerseyHandler = jerseyHandler;
this.requestLog = requestLog;
this.authenticated = authenticated;
this.messageFactory = messageFactory;
this.connectListener = connectListener;
this.idleTimeoutMillis = idleTimeoutMillis;
public WebSocketResourceProvider(String remoteAddress,
ApplicationHandler jerseyHandler,
WebsocketRequestLog requestLog,
T authenticated,
WebSocketMessageFactory messageFactory,
Optional<WebSocketConnectListener> connectListener,
Duration idleTimeout) {
this.remoteAddress = remoteAddress;
this.jerseyHandler = jerseyHandler;
this.requestLog = requestLog;
this.authenticated = authenticated;
this.messageFactory = messageFactory;
this.connectListener = connectListener;
this.idleTimeout = idleTimeout;
}
@Override
public void onWebSocketConnect(Session session) {
this.session = session;
this.session = session;
this.remoteEndpoint = session.getRemote();
this.context = new WebSocketSessionContext(new WebSocketClient(session, remoteEndpoint, messageFactory, requestMap));
this.context = new WebSocketSessionContext(
new WebSocketClient(session, remoteEndpoint, messageFactory, requestMap));
this.context.setAuthenticated(authenticated);
this.session.setIdleTimeout(idleTimeoutMillis);
this.session.setIdleTimeout(idleTimeout);
connectListener.ifPresent(listener -> listener.onWebSocketConnect(this.context));
}
@@ -128,12 +130,12 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
handleResponse(webSocketMessage.getResponseMessage());
break;
default:
close(session, 1018, "Badly formatted");
close(session, 1007, "Badly formatted");
break;
}
} catch (UninitializedMessageException | InvalidMessageException e) {
logger.debug("Parsing", e);
close(session, 1018, "Badly formatted");
close(session, 1007, "Badly formatted");
}
}
@@ -158,23 +160,36 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
}
private void handleRequest(WebSocketRequestMessage requestMessage) {
ContainerRequest containerRequest = new ContainerRequest(null, URI.create(requestMessage.getPath()), requestMessage.getVerb(), new WebSocketSecurityContext(new ContextPrincipal(context)), new MapPropertiesDelegate(new HashMap<>()), jerseyHandler.getConfiguration());
ContainerRequest containerRequest = new ContainerRequest(null, URI.create(requestMessage.getPath()),
requestMessage.getVerb(), new WebSocketSecurityContext(new ContextPrincipal(context)),
new MapPropertiesDelegate(new HashMap<>()), jerseyHandler.getConfiguration());
containerRequest.headers(getCombinedHeaders(session.getUpgradeRequest().getHeaders(), requestMessage.getHeaders()));
if (requestMessage.getBody().isPresent()) {
containerRequest.setEntityStream(new ByteArrayInputStream(requestMessage.getBody().get()));
}
ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
CompletableFuture<ContainerResponse> responseFuture = (CompletableFuture<ContainerResponse>) jerseyHandler.apply(containerRequest, responseBody);
ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
CompletableFuture<ContainerResponse> responseFuture = (CompletableFuture<ContainerResponse>) jerseyHandler.apply(
containerRequest, responseBody);
responseFuture.thenAccept(response -> {
sendResponse(requestMessage, response, responseBody);
try {
sendResponse(requestMessage, response, responseBody);
} catch (IOException e) {
throw new RuntimeException(e);
}
requestLog.log(remoteAddress, containerRequest, response);
}).exceptionally(exception -> {
logger.warn("Websocket Error: " + requestMessage.getVerb() + " " + requestMessage.getPath() + "\n" + requestMessage.getBody(), exception);
sendErrorResponse(requestMessage, Response.status(500).build());
requestLog.log(remoteAddress, containerRequest, new ContainerResponse(containerRequest, Response.status(500).build()));
logger.warn("Websocket Error: " + requestMessage.getVerb() + " " + requestMessage.getPath() + "\n"
+ requestMessage.getBody(), exception);
try {
sendErrorResponse(requestMessage, Response.status(500).build());
} catch (IOException e) {
logger.warn("Failed to send error response", e);
}
requestLog.log(remoteAddress, containerRequest,
new ContainerResponse(containerRequest, Response.status(500).build()));
return null;
});
}
@@ -201,7 +216,7 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
@VisibleForTesting
static boolean shouldIncludeRequestMessageHeader(final String header) {
return !"X-Forwarded-For".equalsIgnoreCase(header.trim());
return !HttpHeaders.X_FORWARDED_FOR.equalsIgnoreCase(header.trim());
}
private void handleResponse(WebSocketResponseMessage responseMessage) {
@@ -216,7 +231,8 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
session.close(status, message);
}
private void sendResponse(WebSocketRequestMessage requestMessage, ContainerResponse response, ByteArrayOutputStream responseBody) {
private void sendResponse(WebSocketRequestMessage requestMessage, ContainerResponse response,
ByteArrayOutputStream responseBody) throws IOException {
if (requestMessage.hasRequestId()) {
byte[] body = responseBody.toByteArray();
@@ -225,25 +241,25 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
}
byte[] responseBytes = messageFactory.createResponse(requestMessage.getRequestId(),
response.getStatus(),
response.getStatusInfo().getReasonPhrase(),
getHeaderList(response.getStringHeaders()),
Optional.ofNullable(body))
.toByteArray();
response.getStatus(),
response.getStatusInfo().getReasonPhrase(),
getHeaderList(response.getStringHeaders()),
Optional.ofNullable(body))
.toByteArray();
remoteEndpoint.sendBytesByFuture(ByteBuffer.wrap(responseBytes));
remoteEndpoint.sendBytes(ByteBuffer.wrap(responseBytes), WriteCallback.NOOP);
}
}
private void sendErrorResponse(WebSocketRequestMessage requestMessage, Response error) {
private void sendErrorResponse(WebSocketRequestMessage requestMessage, Response error) throws IOException {
if (requestMessage.hasRequestId()) {
WebSocketMessage response = messageFactory.createResponse(requestMessage.getRequestId(),
error.getStatus(),
"Error response",
getHeaderList(error.getStringHeaders()),
Optional.empty());
error.getStatus(),
"Error response",
getHeaderList(error.getStringHeaders()),
Optional.empty());
remoteEndpoint.sendBytesByFuture(ByteBuffer.wrap(response.toByteArray()));
remoteEndpoint.sendBytes(ByteBuffer.wrap(response.toByteArray()), WriteCallback.NOOP);
}
}
@@ -6,16 +6,18 @@ package org.whispersystems.websocket;
import static java.util.Optional.ofNullable;
import com.google.common.net.HttpHeaders;
import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.util.Arrays;
import java.util.Optional;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
import org.eclipse.jetty.websocket.server.JettyWebSocketCreator;
import org.eclipse.jetty.websocket.server.JettyWebSocketServlet;
import org.eclipse.jetty.websocket.server.JettyWebSocketServletFactory;
import org.glassfish.jersey.server.ApplicationHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -27,7 +29,8 @@ import org.whispersystems.websocket.configuration.WebSocketConfiguration;
import org.whispersystems.websocket.session.WebSocketSessionContextValueFactoryProvider;
import org.whispersystems.websocket.setup.WebSocketEnvironment;
public class WebSocketResourceProviderFactory<T extends Principal> extends WebSocketServlet implements WebSocketCreator {
public class WebSocketResourceProviderFactory<T extends Principal> extends JettyWebSocketServlet implements
JettyWebSocketCreator {
private static final Logger logger = LoggerFactory.getLogger(WebSocketResourceProviderFactory.class);
@@ -49,10 +52,10 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends WebSo
}
@Override
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
public Object createWebSocket(final JettyServerUpgradeRequest request, final JettyServerUpgradeResponse response) {
try {
Optional<WebSocketAuthenticator<T>> authenticator = Optional.ofNullable(environment.getAuthenticator());
T authenticated = null;
T authenticated = null;
if (authenticator.isPresent()) {
AuthenticationResult<T> authenticationResult = authenticator.get().authenticate(request);
@@ -71,7 +74,7 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends WebSo
authenticated,
this.environment.getMessageFactory(),
ofNullable(this.environment.getConnectListener()),
this.environment.getIdleTimeoutMillis());
this.environment.getIdleTimeout());
} catch (AuthenticationException | IOException e) {
logger.warn("Authentication failure", e);
try {
@@ -83,20 +86,23 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends WebSo
}
@Override
public void configure(WebSocketServletFactory factory) {
public void configure(JettyWebSocketServletFactory factory) {
factory.setCreator(this);
factory.getPolicy().setMaxBinaryMessageSize(configuration.getMaxBinaryMessageSize());
factory.getPolicy().setMaxTextMessageSize(configuration.getMaxTextMessageSize());
factory.setMaxBinaryMessageSize(configuration.getMaxBinaryMessageSize());
factory.setMaxTextMessageSize(configuration.getMaxTextMessageSize());
}
private String getRemoteAddress(ServletUpgradeRequest request) {
String forwardedFor = request.getHeader("X-Forwarded-For");
private String getRemoteAddress(JettyServerUpgradeRequest request) {
String forwardedFor = request.getHeader(HttpHeaders.X_FORWARDED_FOR);
if (forwardedFor == null || forwardedFor.isBlank()) {
return request.getRemoteAddress();
if (request.getRemoteSocketAddress() instanceof InetSocketAddress inetSocketAddress) {
return inetSocketAddress.getAddress().getHostAddress();
}
return null;
} else {
return Arrays.stream(forwardedFor.split(","))
.map(String::trim)
.map(String::trim)
.reduce((a, b) -> b)
.orElseThrow();
}
@@ -9,6 +9,7 @@ import java.util.Optional;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
public interface WebSocketAuthenticator<T extends Principal> {
AuthenticationResult<T> authenticate(UpgradeRequest request) throws AuthenticationException;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@@ -5,7 +5,7 @@
package org.whispersystems.websocket.logging;
import ch.qos.logback.core.AsyncAppenderBase;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
public class AsyncWebsocketEventAppenderFactory implements AsyncAppenderFactory<WebsocketEvent> {
@Override
@@ -15,12 +15,12 @@ import java.util.List;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import io.dropwizard.logging.AppenderFactory;
import io.dropwizard.logging.ConsoleAppenderFactory;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.filter.LevelFilterFactory;
import io.dropwizard.logging.filter.NullLevelFilterFactory;
import io.dropwizard.logging.layout.LayoutFactory;
import io.dropwizard.logging.common.AppenderFactory;
import io.dropwizard.logging.common.ConsoleAppenderFactory;
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
import io.dropwizard.logging.common.filter.LevelFilterFactory;
import io.dropwizard.logging.common.filter.NullLevelFilterFactory;
import io.dropwizard.logging.common.layout.LayoutFactory;
public class WebsocketRequestLoggerFactory {
@@ -6,7 +6,7 @@ package org.whispersystems.websocket.logging.layout;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import io.dropwizard.logging.layout.LayoutFactory;
import io.dropwizard.logging.common.layout.LayoutFactory;
import org.whispersystems.websocket.logging.WebsocketEvent;
import java.util.TimeZone;
@@ -6,10 +6,10 @@ package org.whispersystems.websocket.logging.layout.converters;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.util.CachingDateFormatter;
import org.whispersystems.websocket.logging.WebsocketEvent;
import java.time.ZoneId;
import java.util.List;
import java.util.TimeZone;
import java.util.Optional;
import org.whispersystems.websocket.logging.WebsocketEvent;
public class DateConverter extends WebSocketEventConverter {
@@ -28,7 +28,15 @@ public class DateConverter extends WebSocketEventConverter {
}
try {
cachingDateFormatter = new CachingDateFormatter(datePattern);
List<String> optionList = getOptionList();
Optional<ZoneId> timeZone = Optional.empty();
// if the option list contains a TZ option, then set it.
if (optionList != null && optionList.size() > 1) {
timeZone = Optional.of(ZoneId.of((String) optionList.get(1)));
}
cachingDateFormatter = new CachingDateFormatter(datePattern, timeZone.orElse(null));
// maximumCacheValidity = CachedDateFormat.getMaximumCacheValidity(pattern);
} catch (IllegalArgumentException e) {
addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e);
@@ -36,13 +44,7 @@ public class DateConverter extends WebSocketEventConverter {
cachingDateFormatter = new CachingDateFormatter(CoreConstants.CLF_DATE_PATTERN);
}
List optionList = getOptionList();
// if the option list contains a TZ option, then set it.
if (optionList != null && optionList.size() > 1) {
TimeZone tz = TimeZone.getTimeZone((String) optionList.get(1));
cachingDateFormatter.setTimeZone(tz);
}
}
@Override
@@ -6,7 +6,8 @@ package org.whispersystems.websocket.setup;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.setup.Environment;
import io.dropwizard.core.setup.Environment;
import java.time.Duration;
import org.glassfish.jersey.server.ResourceConfig;
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
@@ -19,31 +20,31 @@ import java.security.Principal;
public class WebSocketEnvironment<T extends Principal> {
private final ResourceConfig jerseyConfig;
private final ObjectMapper objectMapper;
private final Validator validator;
private final WebsocketRequestLog requestLog;
private final long idleTimeoutMillis;
private final ResourceConfig jerseyConfig;
private final ObjectMapper objectMapper;
private final Validator validator;
private final WebsocketRequestLog requestLog;
private final Duration idleTimeout;
private WebSocketAuthenticator<T> authenticator;
private WebSocketMessageFactory messageFactory;
private WebSocketConnectListener connectListener;
private WebSocketMessageFactory messageFactory;
private WebSocketConnectListener connectListener;
public WebSocketEnvironment(Environment environment, WebSocketConfiguration configuration) {
this(environment, configuration, 60000);
this(environment, configuration, Duration.ofMillis(60000));
}
public WebSocketEnvironment(Environment environment, WebSocketConfiguration configuration, long idleTimeoutMillis) {
this(environment, configuration.getRequestLog().build("websocket"), idleTimeoutMillis);
public WebSocketEnvironment(Environment environment, WebSocketConfiguration configuration, Duration idleTimeout) {
this(environment, configuration.getRequestLog().build("websocket"), idleTimeout);
}
public WebSocketEnvironment(Environment environment, WebsocketRequestLog requestLog, long idleTimeoutMillis) {
this.jerseyConfig = new DropwizardResourceConfig(environment.metrics());
this.objectMapper = environment.getObjectMapper();
this.validator = environment.getValidator();
this.requestLog = requestLog;
this.messageFactory = new ProtobufWebSocketMessageFactory();
this.idleTimeoutMillis = idleTimeoutMillis;
public WebSocketEnvironment(Environment environment, WebsocketRequestLog requestLog, Duration idleTimeout) {
this.jerseyConfig = new DropwizardResourceConfig(environment.metrics());
this.objectMapper = environment.getObjectMapper();
this.validator = environment.getValidator();
this.requestLog = requestLog;
this.messageFactory = new ProtobufWebSocketMessageFactory();
this.idleTimeout = idleTimeout;
}
public ResourceConfig jersey() {
@@ -58,8 +59,8 @@ public class WebSocketEnvironment<T extends Principal> {
this.authenticator = authenticator;
}
public long getIdleTimeoutMillis() {
return idleTimeoutMillis;
public Duration getIdleTimeout() {
return idleTimeout;
}
public ObjectMapper getObjectMapper() {
@@ -20,10 +20,9 @@ import java.util.Optional;
import javax.security.auth.Subject;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
import org.eclipse.jetty.websocket.server.JettyWebSocketServletFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -37,8 +36,8 @@ public class WebSocketResourceProviderFactoryTest {
private ResourceConfig jerseyEnvironment;
private WebSocketEnvironment<Account> environment;
private WebSocketAuthenticator<Account> authenticator;
private ServletUpgradeRequest request;
private ServletUpgradeResponse response;
private JettyServerUpgradeRequest request;
private JettyServerUpgradeResponse response;
@BeforeEach
void setup() {
@@ -47,8 +46,8 @@ public class WebSocketResourceProviderFactoryTest {
environment = mock(WebSocketEnvironment.class);
//noinspection unchecked
authenticator = mock(WebSocketAuthenticator.class);
request = mock(ServletUpgradeRequest.class);
response = mock(ServletUpgradeResponse.class);
request = mock(JettyServerUpgradeRequest.class);
response = mock(JettyServerUpgradeResponse.class);
}
@@ -111,9 +110,8 @@ public class WebSocketResourceProviderFactoryTest {
@Test
void testConfigure() {
WebSocketServletFactory servletFactory = mock(WebSocketServletFactory.class);
JettyWebSocketServletFactory servletFactory = mock(JettyWebSocketServletFactory.class);
when(environment.jersey()).thenReturn(jerseyEnvironment);
when(servletFactory.getPolicy()).thenReturn(mock(WebSocketPolicy.class));
WebSocketResourceProviderFactory<Account> factory = new WebSocketResourceProviderFactory<>(environment,
Account.class,
@@ -11,21 +11,21 @@ import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.net.HttpHeaders;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.auth.Auth;
import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.security.Principal;
import java.time.Duration;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@@ -80,7 +80,7 @@ class WebSocketResourceProviderTest {
new TestPrincipal("fooz"),
new ProtobufWebSocketMessageFactory(),
Optional.of(connectListener),
30000);
Duration.ofMillis(30000));
Session session = mock(Session.class);
UpgradeRequest request = mock(UpgradeRequest.class);
@@ -105,7 +105,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = mock(ApplicationHandler.class);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -164,7 +165,7 @@ class WebSocketResourceProviderTest {
assertThat(bundledRequest.getPath(false)).isEqualTo("bar");
verify(requestLog).log(eq("127.0.0.1"), eq(bundledRequest), eq(response));
verify(remoteEndpoint).sendBytesByFuture(responseCaptor.capture());
verify(remoteEndpoint).sendBytes(responseCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketMessage responseMessageContainer = SubProtocol.WebSocketMessage.parseFrom(
responseCaptor.getValue().array());
@@ -180,7 +181,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = mock(ApplicationHandler.class);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -215,7 +217,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseCaptor.capture());
verify(remoteEndpoint).sendBytes(responseCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketMessage responseMessageContainer = SubProtocol.WebSocketMessage.parseFrom(
responseCaptor.getValue().array());
@@ -225,7 +227,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessageSuccess() throws InvalidProtocolBufferException {
void testActualRouteMessageSuccess() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -235,7 +237,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -253,7 +256,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -264,7 +267,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessageNotFound() throws InvalidProtocolBufferException {
void testActualRouteMessageNotFound() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -274,7 +277,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("foo"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -292,7 +296,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -303,7 +307,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessageAuthorized() throws InvalidProtocolBufferException {
void testActualRouteMessageAuthorized() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -314,7 +318,7 @@ class WebSocketResourceProviderTest {
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("authorizedUserName"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
30000);
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -332,7 +336,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -343,7 +347,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessageUnauthorized() throws InvalidProtocolBufferException {
void testActualRouteMessageUnauthorized() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -353,7 +357,7 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, null, new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, null, new ProtobufWebSocketMessageFactory(), Optional.empty(), Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -371,7 +375,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -381,7 +385,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessageOptionalAuthorizedPresent() throws InvalidProtocolBufferException {
void testActualRouteMessageOptionalAuthorizedPresent() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -391,7 +395,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("something"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("something"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -409,7 +414,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -420,7 +425,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessageOptionalAuthorizedEmpty() throws InvalidProtocolBufferException {
void testActualRouteMessageOptionalAuthorizedEmpty() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -430,7 +435,7 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, null, new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, null, new ProtobufWebSocketMessageFactory(), Optional.empty(), Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -448,7 +453,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -459,7 +464,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessagePutAuthenticatedEntity() throws InvalidProtocolBufferException, JsonProcessingException {
void testActualRouteMessagePutAuthenticatedEntity() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -469,7 +474,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -488,7 +494,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -499,8 +505,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessagePutAuthenticatedBadEntity()
throws InvalidProtocolBufferException, JsonProcessingException {
void testActualRouteMessagePutAuthenticatedBadEntity() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new WebSocketSessionContextValueFactoryProvider.Binder());
@@ -510,7 +515,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -529,7 +535,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -540,7 +546,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteMessageExceptionMapping() throws InvalidProtocolBufferException {
void testActualRouteMessageExceptionMapping() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new TestExceptionMapper());
@@ -551,7 +557,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -569,7 +576,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -579,7 +586,7 @@ class WebSocketResourceProviderTest {
}
@Test
void testActualRouteSessionContextInjection() throws InvalidProtocolBufferException {
void testActualRouteSessionContextInjection() throws Exception {
ResourceConfig resourceConfig = new DropwizardResourceConfig();
resourceConfig.register(new TestResource());
resourceConfig.register(new TestExceptionMapper());
@@ -590,7 +597,8 @@ class WebSocketResourceProviderTest {
ApplicationHandler applicationHandler = new ApplicationHandler(resourceConfig);
WebsocketRequestLog requestLog = mock(WebsocketRequestLog.class);
WebSocketResourceProvider<TestPrincipal> provider = new WebSocketResourceProvider<>("127.0.0.1", applicationHandler,
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(), 30000);
requestLog, new TestPrincipal("gooduser"), new ProtobufWebSocketMessageFactory(), Optional.empty(),
Duration.ofMillis(30000));
Session session = mock(Session.class);
RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.class);
@@ -622,7 +630,7 @@ class WebSocketResourceProviderTest {
ArgumentCaptor<ByteBuffer> responseBytesCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
verify(remoteEndpoint).sendBytesByFuture(responseBytesCaptor.capture());
verify(remoteEndpoint, times(2)).sendBytes(responseBytesCaptor.capture(), any(WriteCallback.class));
SubProtocol.WebSocketResponseMessage response = getResponse(responseBytesCaptor);
@@ -653,13 +661,13 @@ class WebSocketResourceProviderTest {
assertThat(WebSocketResourceProvider.shouldIncludeUpgradeRequestHeader("Connection")).isFalse();
assertThat(WebSocketResourceProvider.shouldIncludeUpgradeRequestHeader("Sec-WebSocket-Key")).isFalse();
assertThat(WebSocketResourceProvider.shouldIncludeUpgradeRequestHeader(HttpHeaders.USER_AGENT)).isTrue();
assertThat(WebSocketResourceProvider.shouldIncludeUpgradeRequestHeader("X-Forwarded-For")).isTrue();
assertThat(WebSocketResourceProvider.shouldIncludeUpgradeRequestHeader(HttpHeaders.X_FORWARDED_FOR)).isTrue();
assertThat(WebSocketResourceProvider.shouldIncludeUpgradeRequestHeader("X-Signal-Receive-Stories")).isTrue();
}
@Test
void testShouldIncludeRequestMessageHeader() {
assertThat(WebSocketResourceProvider.shouldIncludeRequestMessageHeader("X-Forwarded-For")).isFalse();
assertThat(WebSocketResourceProvider.shouldIncludeRequestMessageHeader(HttpHeaders.X_FORWARDED_FOR)).isFalse();
assertThat(WebSocketResourceProvider.shouldIncludeRequestMessageHeader(HttpHeaders.USER_AGENT)).isTrue();
assertThat(WebSocketResourceProvider.shouldIncludeRequestMessageHeader("X-Signal-Receive-Stories")).isTrue();
}
@@ -673,16 +681,16 @@ class WebSocketResourceProviderTest {
"Sec-WebSocket-Key", List.of("dGhlIHNhbXBsZSBub25jZQ=="),
"Sec-WebSocket-Protocol", List.of("chat, superchat"),
"Sec-WebSocket-Version", List.of("13"),
"X-Forwarded-For", List.of("127.0.0.1"),
HttpHeaders.X_FORWARDED_FOR, List.of("127.0.0.1"),
HttpHeaders.USER_AGENT, List.of("Upgrade request user agent"));
final Map<String, String> requestMessageHeaders = Map.of(
"X-Forwarded-For", "192.168.0.1",
HttpHeaders.X_FORWARDED_FOR, "192.168.0.1",
HttpHeaders.USER_AGENT, "Request message user agent");
final Map<String, List<String>> expectedHeaders = Map.of(
"Host", List.of("server.example.com"),
"X-Forwarded-For", List.of("127.0.0.1"),
HttpHeaders.X_FORWARDED_FOR, List.of("127.0.0.1"),
HttpHeaders.USER_AGENT, List.of("Request message user agent"));
assertThat(WebSocketResourceProvider.getCombinedHeaders(upgradeRequestHeaders, requestMessageHeaders)).isEqualTo(
@@ -690,12 +698,12 @@ class WebSocketResourceProviderTest {
}
private SubProtocol.WebSocketResponseMessage getResponse(ArgumentCaptor<ByteBuffer> responseCaptor)
throws InvalidProtocolBufferException {
throws Exception {
return SubProtocol.WebSocketMessage.parseFrom(responseCaptor.getValue().array()).getResponse();
}
private SubProtocol.WebSocketRequestMessage getRequest(ArgumentCaptor<ByteBuffer> requestCaptor)
throws InvalidProtocolBufferException {
throws Exception {
return SubProtocol.WebSocketMessage.parseFrom(requestCaptor.getValue().array()).getRequest();
}
@@ -11,7 +11,7 @@ import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.OutputStreamAppender;
import ch.qos.logback.core.spi.DeferredProcessingAware;
import com.google.common.net.HttpHeaders;
import io.dropwizard.logging.AbstractOutputStreamAppenderFactory;
import io.dropwizard.logging.common.AbstractOutputStreamAppenderFactory;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.util.ArrayList;