mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 08:16:47 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9dfe51eac4 | ||
|
|
5de848bf38 | ||
|
|
295cedc075 | ||
|
|
4f1cab407f | ||
|
|
626a7fdad7 |
No files matched your search
@@ -641,7 +641,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
|
||||
apnSender, fcmSender, accountsManager, 0, 0);
|
||||
PushNotificationManager pushNotificationManager =
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler, experimentEnrollmentManager);
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager =
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
|
||||
|
||||
+8
-1
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -85,6 +86,7 @@ public class BackupAuthManager {
|
||||
* Store credential requests containing blinded backup-ids for future use.
|
||||
*
|
||||
* @param account The account using the backup-id
|
||||
* @param device The device setting the account backup-id
|
||||
* @param messagesBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
|
||||
* message backups
|
||||
* @param mediaBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
|
||||
@@ -92,12 +94,17 @@ public class BackupAuthManager {
|
||||
* @return A future that completes when the credentialRequest has been stored
|
||||
* @throws RateLimitExceededException If too many backup-ids have been committed
|
||||
*/
|
||||
public CompletableFuture<Void> commitBackupId(final Account account,
|
||||
public CompletableFuture<Void> commitBackupId(
|
||||
final Account account,
|
||||
final Device device,
|
||||
final BackupAuthCredentialRequest messagesBackupCredentialRequest,
|
||||
final BackupAuthCredentialRequest mediaBackupCredentialRequest) {
|
||||
if (configuredBackupLevel(account).isEmpty()) {
|
||||
throw Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException();
|
||||
}
|
||||
if (!device.isPrimary()) {
|
||||
throw Status.PERMISSION_DENIED.withDescription("Only primary device can set backup-id").asRuntimeException();
|
||||
}
|
||||
final byte[] serializedMessageCredentialRequest = messagesBackupCredentialRequest.serialize();
|
||||
final byte[] serializedMediaCredentialRequest = mediaBackupCredentialRequest.serialize();
|
||||
|
||||
|
||||
+3
-2
@@ -135,13 +135,14 @@ public class ArchiveController {
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "The backup-id was set")
|
||||
@ApiResponse(responseCode = "400", description = "The provided backup auth credential request was invalid")
|
||||
@ApiResponse(responseCode = "403", description = "The device did not have permission to set the backup-id. Only the primary device can set the backup-id for an account")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited. Too many attempts to change the backup-id have been made")
|
||||
public CompletionStage<Response> setBackupId(
|
||||
@Mutable @Auth final AuthenticatedDevice account,
|
||||
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest) throws RateLimitExceededException {
|
||||
|
||||
return this.backupAuthManager
|
||||
.commitBackupId(account.getAccount(), setBackupIdRequest.messagesBackupAuthCredentialRequest,
|
||||
.commitBackupId(account.getAccount(), account.getAuthenticatedDevice(),
|
||||
setBackupIdRequest.messagesBackupAuthCredentialRequest,
|
||||
setBackupIdRequest.mediaBackupAuthCredentialRequest)
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
+34
-10
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -70,21 +72,40 @@ public class DonationController {
|
||||
@Path("/redeem-receipt")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
|
||||
@Operation(
|
||||
summary = "Redeem receipt",
|
||||
description = """
|
||||
Redeem a receipt acquired from /v1/subscription/{subscriberId}/receipt_credentials to add a badge to the
|
||||
account. After successful redemption, profile responses will include the corresponding badge (if configured as
|
||||
visible) until the expiration time on the receipt.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The receipt was redeemed")
|
||||
@ApiResponse(responseCode = "400", description = """
|
||||
The provided presentation or receipt was invalid, or the receipt was already redeemed for a different account. A
|
||||
specific error message suitable for logging will be included as text/plain body
|
||||
""")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<Response> redeemReceipt(
|
||||
@Mutable @Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final RedeemReceiptRequest request) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
ReceiptCredentialPresentation receiptCredentialPresentation;
|
||||
try {
|
||||
receiptCredentialPresentation = receiptCredentialPresentationFactory.build(
|
||||
request.getReceiptCredentialPresentation());
|
||||
receiptCredentialPresentation = receiptCredentialPresentationFactory
|
||||
.build(request.getReceiptCredentialPresentation());
|
||||
} catch (InvalidInputException e) {
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST).entity("invalid receipt credential presentation").type(MediaType.TEXT_PLAIN_TYPE).build());
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
|
||||
.entity("invalid receipt credential presentation")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
}
|
||||
try {
|
||||
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
|
||||
} catch (VerificationFailedException e) {
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST).entity("receipt credential presentation verification failed").type(MediaType.TEXT_PLAIN_TYPE).build());
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt credential presentation verification failed")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
}
|
||||
|
||||
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
|
||||
@@ -92,16 +113,19 @@ public class DonationController {
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
|
||||
if (badgeId == null) {
|
||||
return CompletableFuture.completedFuture(Response.serverError().entity("server does not recognize the requested receipt level").type(MediaType.TEXT_PLAIN_TYPE).build());
|
||||
return CompletableFuture.completedFuture(Response.serverError()
|
||||
.entity("server does not recognize the requested receipt level")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
}
|
||||
return redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.getAccount().getUuid())
|
||||
.thenCompose(receiptMatched -> {
|
||||
if (!receiptMatched) {
|
||||
|
||||
return CompletableFuture.completedFuture(
|
||||
Response.status(Status.BAD_REQUEST).entity("receipt serial is already redeemed")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE).build());
|
||||
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt serial is already redeemed")
|
||||
.type(MediaType.TEXT_PLAIN_TYPE)
|
||||
.build());
|
||||
}
|
||||
|
||||
return accountsManager.updateAsync(auth.getAccount(), a -> {
|
||||
@@ -111,7 +135,7 @@ public class DonationController {
|
||||
}
|
||||
})
|
||||
.thenApply(ignored -> Response.ok().build());
|
||||
});
|
||||
});
|
||||
}).thenCompose(Function.identity());
|
||||
}
|
||||
|
||||
|
||||
+4
@@ -7,12 +7,16 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
|
||||
public class RedeemReceiptRequest {
|
||||
|
||||
@Schema(description = "Presentation of a ZK receipt encoded in standard padded base64", implementation = String.class)
|
||||
private final byte[] receiptCredentialPresentation;
|
||||
@Schema(description = "If true, the corresponding badge should be visible on the profile")
|
||||
private final boolean visible;
|
||||
@Schema(description = "if true, and the new badge is visible, it should be the primary badge on the profile")
|
||||
private final boolean primary;
|
||||
|
||||
@JsonCreator
|
||||
|
||||
@@ -32,6 +32,7 @@ import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
@@ -60,9 +61,15 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
BackupAuthCredentialRequest::new,
|
||||
request.getMediaBackupAuthCredentialRequest().toByteArray());
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
return authenticatedAccount()
|
||||
.flatMap(account -> Mono.fromFuture(
|
||||
backupAuthManager.commitBackupId(account, messagesCredentialRequest, mediaCredentialRequest)))
|
||||
.flatMap(account -> {
|
||||
final Device device = account
|
||||
.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
return Mono.fromFuture(
|
||||
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest));
|
||||
})
|
||||
.thenReturn(SetBackupIdResponse.getDefaultInstance());
|
||||
}
|
||||
|
||||
|
||||
+7
@@ -59,6 +59,10 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
|
||||
public static final String REQUEST_COUNTER_NAME = MetricsRequestEventListener.REQUEST_COUNTER_NAME;
|
||||
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricsRequestEventListener.REQUESTS_BY_VERSION_COUNTER_NAME;
|
||||
@VisibleForTesting
|
||||
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME;
|
||||
@VisibleForTesting
|
||||
static final String REQUEST_BYTES_COUNTER_NAME = MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME;
|
||||
@VisibleForTesting
|
||||
static final String URI_INFO_PROPERTY_NAME = MetricsHttpChannelListener.class.getName() + ".uriInfo";
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -141,6 +145,9 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
|
||||
|
||||
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
|
||||
|
||||
meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(request.getResponse().getContentCount());
|
||||
meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(request.getContentRead());
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(requestInfo.userAgent(), clientReleaseManager).ifPresent(
|
||||
clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
|
||||
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(requestInfo.userAgent()))).increment());
|
||||
|
||||
+25
-1
@@ -15,8 +15,11 @@ import io.micrometer.core.instrument.Tags;
|
||||
import org.glassfish.jersey.server.ContainerResponse;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
|
||||
import org.whispersystems.websocket.WebSocketResourceProvider;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.ArrayList;
|
||||
@@ -24,14 +27,19 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Gathers and reports request-level metrics.
|
||||
* Gathers and reports request-level metrics for WebSocket traffic only.
|
||||
* For HTTP traffic, use {@link MetricsHttpChannelListener}.
|
||||
*/
|
||||
public class MetricsRequestEventListener implements RequestEventListener {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MetricsRequestEventListener.class);
|
||||
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
public static final String REQUEST_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "request");
|
||||
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "requestByVersion");
|
||||
public static final String RESPONSE_BYTES_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "responseBytes");
|
||||
public static final String REQUEST_BYTES_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "requestBytes");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PATH_TAG = "path";
|
||||
@@ -50,6 +58,10 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
|
||||
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
|
||||
|
||||
if (trafficSource == TrafficSource.HTTP) {
|
||||
logger.warn("Use {} for HTTP traffic", MetricsHttpChannelListener.class.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -85,6 +97,18 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
|
||||
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
|
||||
|
||||
Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.REQUEST_LENGTH_PROPERTY))
|
||||
.filter(Integer.class::isInstance)
|
||||
.map(Integer.class::cast)
|
||||
.filter(bytes -> bytes >= 0)
|
||||
.ifPresent(bytes -> meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(bytes));
|
||||
|
||||
Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.RESPONSE_LENGTH_PROPERTY))
|
||||
.filter(Integer.class::isInstance)
|
||||
.map(Integer.class::cast)
|
||||
.filter(bytes -> bytes >= 0)
|
||||
.ifPresent(bytes -> meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(bytes));
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
|
||||
.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
|
||||
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
|
||||
+2
-18
@@ -17,7 +17,6 @@ import java.util.function.BiConsumer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -29,9 +28,6 @@ public class PushNotificationManager {
|
||||
private final APNSender apnSender;
|
||||
private final FcmSender fcmSender;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
public static final String SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT = "scheduleLowUregencyFcmPush";
|
||||
|
||||
private static final String SENT_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "sentPushNotification");
|
||||
private static final String FAILED_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "failedPushNotification");
|
||||
@@ -42,14 +38,12 @@ public class PushNotificationManager {
|
||||
public PushNotificationManager(final AccountsManager accountsManager,
|
||||
final APNSender apnSender,
|
||||
final FcmSender fcmSender,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
final PushNotificationScheduler pushNotificationScheduler) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.apnSender = apnSender;
|
||||
this.fcmSender = fcmSender;
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<SendPushNotificationResult>> sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
|
||||
@@ -107,7 +101,7 @@ public class PushNotificationManager {
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Optional<SendPushNotificationResult>> sendNotification(final PushNotification pushNotification) {
|
||||
if (shouldScheduleNotification(pushNotification)) {
|
||||
if (!pushNotification.urgent()) {
|
||||
// Schedule a notification for some time in the future (possibly even now!) rather than sending a notification
|
||||
// directly
|
||||
return pushNotificationScheduler
|
||||
@@ -156,16 +150,6 @@ public class PushNotificationManager {
|
||||
.thenApply(Optional::of);
|
||||
}
|
||||
|
||||
private boolean shouldScheduleNotification(final PushNotification pushNotification) {
|
||||
return !pushNotification.urgent() && switch (pushNotification.tokenType()) {
|
||||
// APNs imposes a per-device limit on background push notifications
|
||||
case APN -> true;
|
||||
case FCM -> experimentEnrollmentManager.isEnrolled(
|
||||
pushNotification.destination().getUuid(),
|
||||
SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT);
|
||||
};
|
||||
}
|
||||
|
||||
private static <T> BiConsumer<T, Throwable> logErrors() {
|
||||
return (ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
|
||||
+1
-4
@@ -244,11 +244,8 @@ public class MessagePersister implements Managed {
|
||||
|
||||
} while (!messages.isEmpty());
|
||||
|
||||
final boolean inSkipExperiment = device.getGcmId() != null && experimentEnrollmentManager.isEnrolled(
|
||||
accountUuid,
|
||||
PushNotificationManager.SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT);
|
||||
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
|
||||
.tags(Tags.of(platformTag).and("lowUrgencySkip", Boolean.toString(inSkipExperiment)))
|
||||
.tags(Tags.of(platformTag))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(messageCount);
|
||||
|
||||
+6
-13
@@ -13,7 +13,7 @@ import org.eclipse.jetty.websocket.api.UpgradeRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
import org.whispersystems.websocket.auth.AuthenticationException;
|
||||
import org.whispersystems.websocket.auth.InvalidCredentialsException;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
|
||||
|
||||
@@ -22,7 +22,6 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
|
||||
private static final ReusableAuth<AuthenticatedDevice> CREDENTIALS_NOT_PRESENTED = ReusableAuth.anonymous();
|
||||
|
||||
private static final ReusableAuth<AuthenticatedDevice> INVALID_CREDENTIALS_PRESENTED = ReusableAuth.invalid();
|
||||
private final AccountAuthenticator accountAuthenticator;
|
||||
private final PrincipalSupplier<AuthenticatedDevice> principalSupplier;
|
||||
|
||||
@@ -34,23 +33,17 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
|
||||
@Override
|
||||
public ReusableAuth<AuthenticatedDevice> authenticate(final UpgradeRequest request)
|
||||
throws AuthenticationException {
|
||||
try {
|
||||
return authenticatedAccountFromHeaderAuth(request.getHeader(HttpHeaders.AUTHORIZATION));
|
||||
} catch (final Exception e) {
|
||||
// this will be handled and logged upstream
|
||||
// the most likely exception is a transient error connecting to account storage
|
||||
throw new AuthenticationException(e);
|
||||
}
|
||||
}
|
||||
throws InvalidCredentialsException {
|
||||
|
||||
@Nullable final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
|
||||
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader) {
|
||||
if (authHeader == null) {
|
||||
return CREDENTIALS_NOT_PRESENTED;
|
||||
}
|
||||
|
||||
return basicCredentialsFromAuthHeader(authHeader)
|
||||
.flatMap(accountAuthenticator::authenticate)
|
||||
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
|
||||
.orElse(INVALID_CREDENTIALS_PRESENTED);
|
||||
.orElseThrow(InvalidCredentialsException::new);
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -338,13 +338,8 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
|
||||
// Cleared the queue! Send a queue empty message if we need to
|
||||
consecutiveRetries.set(0);
|
||||
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
|
||||
final boolean inSkipExperiment = auth.getAuthenticatedDevice().getGcmId() != null && experimentEnrollmentManager.isEnrolled(
|
||||
auth.getAccount().getUuid(),
|
||||
PushNotificationManager.SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT);
|
||||
|
||||
final Tags tags = Tags
|
||||
.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()))
|
||||
.and("lowUrgencySkip", Boolean.toString(inSkipExperiment));
|
||||
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
final long drainDuration = System.currentTimeMillis() - queueDrainStartTime.get();
|
||||
|
||||
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(sentMessageCounter.sum());
|
||||
|
||||
+1
-5
@@ -33,7 +33,6 @@ import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
@@ -118,9 +117,6 @@ record CommandDependencies(
|
||||
new DynamicConfigurationManager<>(
|
||||
configuration.getDynamicConfig().build(awsCredentialsProvider, dynamicConfigurationExecutor), DynamicConfiguration.class);
|
||||
dynamicConfigurationManager.start();
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager =
|
||||
new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
final ClientResources.Builder redisClientResourcesBuilder = ClientResources.builder();
|
||||
|
||||
FaultTolerantRedisClusterClient cacheCluster = configuration.getCacheClusterConfiguration()
|
||||
@@ -286,7 +282,7 @@ record CommandDependencies(
|
||||
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
|
||||
apnSender, fcmSender, accountsManager, 0, 0);
|
||||
PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager,
|
||||
apnSender, fcmSender, pushNotificationScheduler, experimentEnrollmentManager);
|
||||
apnSender, fcmSender, pushNotificationScheduler);
|
||||
PushNotificationExperimentSamples pushNotificationExperimentSamples =
|
||||
new PushNotificationExperimentSamples(dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
|
||||
|
||||
+34
-3
@@ -61,6 +61,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ExperimentHelper;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
@@ -119,7 +120,7 @@ public class BackupAuthManagerTest {
|
||||
final BackupAuthCredentialRequest messagesCredentialRequest = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
|
||||
final BackupAuthCredentialRequest mediaCredentialRequest = backupAuthTestUtil.getRequest(mediaBackupKey, aci);
|
||||
|
||||
authManager.commitBackupId(account, messagesCredentialRequest, mediaCredentialRequest).join();
|
||||
authManager.commitBackupId(account, primaryDevice(), messagesCredentialRequest, mediaCredentialRequest).join();
|
||||
|
||||
verify(account).setBackupCredentialRequests(messagesCredentialRequest.serialize(), mediaCredentialRequest.serialize());
|
||||
}
|
||||
@@ -135,6 +136,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
final ThrowableAssert.ThrowingCallable commit = () ->
|
||||
authManager.commitBackupId(account,
|
||||
primaryDevice(),
|
||||
backupAuthTestUtil.getRequest(messagesBackupKey, aci),
|
||||
backupAuthTestUtil.getRequest(mediaBackupKey, aci)).join();
|
||||
if (backupLevel == null) {
|
||||
@@ -147,6 +149,24 @@ public class BackupAuthManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitRequiresPrimary() {
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE);
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
|
||||
final ThrowableAssert.ThrowingCallable commit = () ->
|
||||
authManager.commitBackupId(account,
|
||||
linkedDevice(),
|
||||
backupAuthTestUtil.getRequest(messagesBackupKey, aci),
|
||||
backupAuthTestUtil.getRequest(mediaBackupKey, aci)).join();
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(commit)
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.PERMISSION_DENIED);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void getBackupAuthCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
|
||||
@CartesianTest.Enum final BackupCredentialType credentialType) {
|
||||
@@ -504,7 +524,7 @@ public class BackupAuthManagerTest {
|
||||
: storedMediaCredential;
|
||||
|
||||
final boolean expectRateLimit = (changeMedia || changeMessage) && rateLimitBackupId;
|
||||
final CompletableFuture<Void> future = authManager.commitBackupId(account, newMessagesCredential, newMediaCredential);
|
||||
final CompletableFuture<Void> future = authManager.commitBackupId(account, primaryDevice(), newMessagesCredential, newMediaCredential);
|
||||
if (expectRateLimit) {
|
||||
CompletableFutureTestUtil.assertFailsWithCause(RateLimitExceededException.class, future);
|
||||
} else {
|
||||
@@ -538,7 +558,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
// We should get rate limited iff we are out of paid media changes and we changed the media backup-id
|
||||
final boolean expectRateLimit = changeMedia && paid && rateLimitPaidMedia;
|
||||
final CompletableFuture<Void> future = authManager.commitBackupId(account, newMessagesCredential, newMediaCredential);
|
||||
final CompletableFuture<Void> future = authManager.commitBackupId(account, primaryDevice(), newMessagesCredential, newMediaCredential);
|
||||
if (expectRateLimit) {
|
||||
CompletableFutureTestUtil.assertFailsWithCause(RateLimitExceededException.class, future);
|
||||
} else {
|
||||
@@ -562,6 +582,17 @@ public class BackupAuthManagerTest {
|
||||
return account;
|
||||
}
|
||||
|
||||
private Device primaryDevice() {
|
||||
final Device device = mock(Device.class);
|
||||
when(device.isPrimary()).thenReturn(true);
|
||||
return device;
|
||||
}
|
||||
|
||||
private Device linkedDevice() {
|
||||
final Device device = mock(Device.class);
|
||||
when(device.isPrimary()).thenReturn(false);
|
||||
return device;
|
||||
}
|
||||
|
||||
private static String experimentName(@Nullable BackupLevel backupLevel) {
|
||||
return switch (backupLevel) {
|
||||
|
||||
+4
-4
@@ -157,7 +157,7 @@ public class ArchiveControllerTest {
|
||||
|
||||
@Test
|
||||
public void setBackupId() {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid")
|
||||
@@ -170,7 +170,7 @@ public class ArchiveControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
|
||||
verify(backupAuthManager).commitBackupId(AuthHelper.VALID_ACCOUNT,
|
||||
verify(backupAuthManager).commitBackupId(AuthHelper.VALID_ACCOUNT, AuthHelper.VALID_DEVICE,
|
||||
backupAuthTestUtil.getRequest(messagesBackupKey, aci),
|
||||
backupAuthTestUtil.getRequest(mediaBackupKey, aci));
|
||||
}
|
||||
@@ -275,9 +275,9 @@ public class ArchiveControllerTest {
|
||||
@MethodSource
|
||||
public void setBackupIdException(final Exception ex, final boolean sync, final int expectedStatus) {
|
||||
if (sync) {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenThrow(ex);
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenThrow(ex);
|
||||
} else {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
|
||||
}
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid")
|
||||
|
||||
+13
-5
@@ -57,6 +57,7 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@@ -69,7 +70,8 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
backupAuthTestUtil.getRequest(mediaBackupKey, AUTHENTICATED_ACI);
|
||||
final BackupAuthCredentialRequest messagesAuthCredRequest =
|
||||
backupAuthTestUtil.getRequest(messagesBackupKey, AUTHENTICATED_ACI);
|
||||
private final Account account = mock(Account.class);
|
||||
private Account account;
|
||||
private Device device;
|
||||
|
||||
@Mock
|
||||
private BackupAuthManager backupAuthManager;
|
||||
@@ -83,14 +85,19 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
account = mock(Account.class);
|
||||
device = mock(Device.class);
|
||||
when(device.isPrimary()).thenReturn(true);
|
||||
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
when(account.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(device));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void setBackupId() {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
authenticatedServiceStub().setBackupId(
|
||||
SetBackupIdRequest.newBuilder()
|
||||
@@ -98,7 +105,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
|
||||
.build());
|
||||
|
||||
verify(backupAuthManager).commitBackupId(account, messagesAuthCredRequest, mediaAuthCredRequest);
|
||||
verify(backupAuthManager).commitBackupId(account, device, messagesAuthCredRequest, mediaAuthCredRequest);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -147,9 +154,10 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
@MethodSource
|
||||
void setBackupIdException(final Exception ex, final boolean sync, final Status expected) {
|
||||
if (sync) {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenThrow(ex);
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenThrow(ex);
|
||||
} else {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(ex));
|
||||
}
|
||||
|
||||
GrpcTestUtils.assertStatusException(
|
||||
|
||||
+21
-12
@@ -46,6 +46,7 @@ import java.security.Principal;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -83,7 +84,9 @@ class MetricsHttpChannelListenerIntegrationTest {
|
||||
|
||||
private static final TrafficSource TRAFFIC_SOURCE = TrafficSource.HTTP;
|
||||
private static final MeterRegistry METER_REGISTRY = mock(MeterRegistry.class);
|
||||
private static final Counter COUNTER = mock(Counter.class);
|
||||
private static final Counter REQUEST_COUNTER = mock(Counter.class);
|
||||
private static final Counter RESPONSE_BYTES_COUNTER = mock(Counter.class);
|
||||
private static final Counter REQUEST_BYTES_COUNTER = mock(Counter.class);
|
||||
private static final AtomicReference<CountDownLatch> COUNT_DOWN_LATCH_FUTURE_REFERENCE = new AtomicReference<>();
|
||||
|
||||
private static final DropwizardAppExtension<Configuration> EXTENSION = new DropwizardAppExtension<>(
|
||||
@@ -92,7 +95,9 @@ class MetricsHttpChannelListenerIntegrationTest {
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
reset(METER_REGISTRY);
|
||||
reset(COUNTER);
|
||||
reset(REQUEST_COUNTER);
|
||||
reset(RESPONSE_BYTES_COUNTER);
|
||||
reset(REQUEST_BYTES_COUNTER);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -105,11 +110,13 @@ class MetricsHttpChannelListenerIntegrationTest {
|
||||
COUNT_DOWN_LATCH_FUTURE_REFERENCE.set(countDownLatch);
|
||||
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
final Map<String, Counter> counterMap = Map.of(
|
||||
MetricsHttpChannelListener.REQUEST_COUNTER_NAME, REQUEST_COUNTER,
|
||||
MetricsHttpChannelListener.RESPONSE_BYTES_COUNTER_NAME, RESPONSE_BYTES_COUNTER,
|
||||
MetricsHttpChannelListener.REQUEST_BYTES_COUNTER_NAME, REQUEST_BYTES_COUNTER
|
||||
);
|
||||
when(METER_REGISTRY.counter(anyString(), any(Iterable.class)))
|
||||
.thenAnswer(a -> MetricsHttpChannelListener.REQUEST_COUNTER_NAME.equals(a.getArgument(0, String.class))
|
||||
? COUNTER
|
||||
: mock(Counter.class))
|
||||
.thenReturn(COUNTER);
|
||||
.thenAnswer(a -> counterMap.getOrDefault(a.getArgument(0, String.class), mock(Counter.class)));
|
||||
|
||||
Client client = EXTENSION.client();
|
||||
|
||||
@@ -141,7 +148,7 @@ class MetricsHttpChannelListenerIntegrationTest {
|
||||
assertTrue(countDownLatch.await(1000, TimeUnit.MILLISECONDS));
|
||||
|
||||
verify(METER_REGISTRY).counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
|
||||
verify(COUNTER).increment();
|
||||
verify(REQUEST_COUNTER).increment();
|
||||
|
||||
final Iterable<Tag> tagIterable = tagCaptor.getValue();
|
||||
final Set<Tag> tags = new HashSet<>();
|
||||
@@ -186,11 +193,13 @@ class MetricsHttpChannelListenerIntegrationTest {
|
||||
COUNT_DOWN_LATCH_FUTURE_REFERENCE.set(countDownLatch);
|
||||
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
final Map<String, Counter> counterMap = Map.of(
|
||||
MetricsHttpChannelListener.REQUEST_COUNTER_NAME, REQUEST_COUNTER,
|
||||
MetricsHttpChannelListener.RESPONSE_BYTES_COUNTER_NAME, RESPONSE_BYTES_COUNTER,
|
||||
MetricsHttpChannelListener.REQUEST_BYTES_COUNTER_NAME, REQUEST_BYTES_COUNTER
|
||||
);
|
||||
when(METER_REGISTRY.counter(anyString(), any(Iterable.class)))
|
||||
.thenAnswer(a -> MetricsHttpChannelListener.REQUEST_COUNTER_NAME.equals(a.getArgument(0, String.class))
|
||||
? COUNTER
|
||||
: mock(Counter.class))
|
||||
.thenReturn(COUNTER);
|
||||
.thenAnswer(a -> counterMap.getOrDefault(a.getArgument(0, String.class), mock(Counter.class)));
|
||||
|
||||
client.connect(new WebSocketListener() {
|
||||
@Override
|
||||
@@ -203,7 +212,7 @@ class MetricsHttpChannelListenerIntegrationTest {
|
||||
assertTrue(countDownLatch.await(1000, TimeUnit.MILLISECONDS));
|
||||
|
||||
verify(METER_REGISTRY).counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
|
||||
verify(COUNTER).increment();
|
||||
verify(REQUEST_COUNTER).increment();
|
||||
|
||||
final Iterable<Tag> tagIterable = tagCaptor.getValue();
|
||||
final Set<Tag> tags = new HashSet<>();
|
||||
|
||||
+17
@@ -39,6 +39,8 @@ class MetricsHttpChannelListenerTest {
|
||||
private MeterRegistry meterRegistry;
|
||||
private Counter requestCounter;
|
||||
private Counter requestsByVersionCounter;
|
||||
private Counter responseBytesCounter;
|
||||
private Counter requestBytesCounter;
|
||||
private ClientReleaseManager clientReleaseManager;
|
||||
private MetricsHttpChannelListener listener;
|
||||
|
||||
@@ -47,6 +49,8 @@ class MetricsHttpChannelListenerTest {
|
||||
meterRegistry = mock(MeterRegistry.class);
|
||||
requestCounter = mock(Counter.class);
|
||||
requestsByVersionCounter = mock(Counter.class);
|
||||
responseBytesCounter = mock(Counter.class);
|
||||
requestBytesCounter = mock(Counter.class);
|
||||
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestCounter);
|
||||
@@ -54,6 +58,12 @@ class MetricsHttpChannelListenerTest {
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUESTS_BY_VERSION_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestsByVersionCounter);
|
||||
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(responseBytesCounter);
|
||||
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestBytesCounter);
|
||||
|
||||
clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
|
||||
listener = new MetricsHttpChannelListener(meterRegistry, clientReleaseManager, Collections.emptySet());
|
||||
@@ -76,7 +86,9 @@ class MetricsHttpChannelListenerTest {
|
||||
|
||||
final Response response = mock(Response.class);
|
||||
when(response.getStatus()).thenReturn(statusCode);
|
||||
when(response.getContentCount()).thenReturn(1024L);
|
||||
when(request.getResponse()).thenReturn(response);
|
||||
when(request.getContentRead()).thenReturn(512L);
|
||||
final ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class);
|
||||
when(request.getAttribute(MetricsHttpChannelListener.URI_INFO_PROPERTY_NAME)).thenReturn(extendedUriInfo);
|
||||
when(extendedUriInfo.getMatchedTemplates()).thenReturn(List.of(new UriTemplate(path)));
|
||||
@@ -87,6 +99,9 @@ class MetricsHttpChannelListenerTest {
|
||||
|
||||
verify(requestCounter).increment();
|
||||
|
||||
verify(responseBytesCounter).increment(1024L);
|
||||
verify(requestBytesCounter).increment(512L);
|
||||
|
||||
verify(meterRegistry).counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
|
||||
|
||||
final Set<Tag> tags = new HashSet<>();
|
||||
@@ -123,7 +138,9 @@ class MetricsHttpChannelListenerTest {
|
||||
|
||||
final Response response = mock(Response.class);
|
||||
when(response.getStatus()).thenReturn(statusCode);
|
||||
when(response.getContentCount()).thenReturn(1024L);
|
||||
when(request.getResponse()).thenReturn(response);
|
||||
when(request.getContentRead()).thenReturn(512L);
|
||||
final ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class);
|
||||
when(request.getAttribute(MetricsHttpChannelListener.URI_INFO_PROPERTY_NAME)).thenReturn(extendedUriInfo);
|
||||
when(extendedUriInfo.getMatchedTemplates()).thenReturn(List.of(new UriTemplate(path)));
|
||||
|
||||
+21
@@ -62,6 +62,8 @@ class MetricsRequestEventListenerTest {
|
||||
|
||||
private MeterRegistry meterRegistry;
|
||||
private Counter counter;
|
||||
private Counter responseBytesCounter;
|
||||
private Counter requestBytesCounter;
|
||||
private MetricsRequestEventListener listener;
|
||||
|
||||
private static final TrafficSource TRAFFIC_SOURCE = TrafficSource.HTTP;
|
||||
@@ -70,6 +72,8 @@ class MetricsRequestEventListenerTest {
|
||||
void setup() {
|
||||
meterRegistry = mock(MeterRegistry.class);
|
||||
counter = mock(Counter.class);
|
||||
responseBytesCounter = mock(Counter.class);
|
||||
requestBytesCounter = mock(Counter.class);
|
||||
|
||||
final ClientReleaseManager clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
when(clientReleaseManager.isVersionActive(any(), any())).thenReturn(false);
|
||||
@@ -91,6 +95,8 @@ class MetricsRequestEventListenerTest {
|
||||
when(request.getMethod()).thenReturn(method);
|
||||
when(request.getRequestHeader(HttpHeaders.USER_AGENT)).thenReturn(
|
||||
Collections.singletonList("Signal-Android/7.6.2 Android/34 libsignal/0.46.0"));
|
||||
when(request.getProperty(WebSocketResourceProvider.REQUEST_LENGTH_PROPERTY)).thenReturn(512);
|
||||
when(request.getProperty(WebSocketResourceProvider.RESPONSE_LENGTH_PROPERTY)).thenReturn(1024);
|
||||
|
||||
final ContainerResponse response = mock(ContainerResponse.class);
|
||||
when(response.getStatus()).thenReturn(statusCode);
|
||||
@@ -104,10 +110,17 @@ class MetricsRequestEventListenerTest {
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(counter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(responseBytesCounter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestBytesCounter);
|
||||
|
||||
listener.onEvent(event);
|
||||
|
||||
verify(meterRegistry).counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
|
||||
verify(counter).increment();
|
||||
verify(responseBytesCounter).increment(1024L);
|
||||
verify(requestBytesCounter).increment(512L);
|
||||
|
||||
final Iterable<Tag> tagIterable = tagCaptor.getValue();
|
||||
final Set<Tag> tags = new HashSet<>();
|
||||
@@ -155,6 +168,10 @@ class MetricsRequestEventListenerTest {
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(counter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(responseBytesCounter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestBytesCounter);
|
||||
|
||||
provider.onWebSocketConnect(session);
|
||||
|
||||
@@ -216,6 +233,10 @@ class MetricsRequestEventListenerTest {
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class))).thenReturn(
|
||||
counter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(responseBytesCounter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestBytesCounter);
|
||||
|
||||
provider.onWebSocketConnect(session);
|
||||
|
||||
|
||||
+30
-22
@@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -36,7 +35,6 @@ class PushNotificationManagerTest {
|
||||
private APNSender apnSender;
|
||||
private FcmSender fcmSender;
|
||||
private PushNotificationScheduler pushNotificationScheduler;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private PushNotificationManager pushNotificationManager;
|
||||
|
||||
@@ -46,17 +44,15 @@ class PushNotificationManagerTest {
|
||||
apnSender = mock(APNSender.class);
|
||||
fcmSender = mock(FcmSender.class);
|
||||
pushNotificationScheduler = mock(PushNotificationScheduler.class);
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
|
||||
AccountsHelper.setupMockUpdate(accountsManager);
|
||||
|
||||
pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender,
|
||||
pushNotificationScheduler, experimentEnrollmentManager);
|
||||
pushNotificationScheduler);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void sendNewMessageNotification(final boolean urgent) throws NotPushRegisteredException {
|
||||
@Test
|
||||
void sendNewUrgentMessageNotification() throws NotPushRegisteredException {
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
@@ -66,13 +62,30 @@ class PushNotificationManagerTest {
|
||||
when(device.getGcmId()).thenReturn(deviceToken);
|
||||
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
when(fcmSender.sendNotification(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
|
||||
|
||||
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, urgent);
|
||||
verify(fcmSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent));
|
||||
when(fcmSender.sendNotification(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
|
||||
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, true);
|
||||
verify(fcmSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendNewNonUrgentMessageNotification() throws NotPushRegisteredException {
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
final String deviceToken = "token";
|
||||
|
||||
when(device.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(device.getGcmId()).thenReturn(deviceToken);
|
||||
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
when(pushNotificationScheduler.scheduleBackgroundNotification(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, false);
|
||||
verify(pushNotificationScheduler).scheduleBackgroundNotification(PushNotification.TokenType.FCM, account, device);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void sendRegistrationChallengeNotification() {
|
||||
final String deviceToken = "token";
|
||||
@@ -135,9 +148,8 @@ class PushNotificationManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testSendNotificationFcm(final boolean urgent) {
|
||||
@Test
|
||||
void testSendNotificationFcm() {
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
@@ -145,7 +157,7 @@ class PushNotificationManagerTest {
|
||||
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
final PushNotification pushNotification = new PushNotification(
|
||||
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
|
||||
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
|
||||
|
||||
when(fcmSender.sendNotification(pushNotification))
|
||||
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
|
||||
@@ -162,10 +174,9 @@ class PushNotificationManagerTest {
|
||||
@CartesianTest
|
||||
void testSendOrScheduleNotification(
|
||||
@CartesianTest.Enum(PushNotification.TokenType.class) PushNotification.TokenType tokenType,
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean urgent,
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean inExperiment) {
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean urgent) {
|
||||
|
||||
final boolean expectSchedule = !urgent && (tokenType == PushNotification.TokenType.APN || inExperiment);
|
||||
final boolean expectSchedule = !urgent;
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
@@ -175,9 +186,6 @@ class PushNotificationManagerTest {
|
||||
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
|
||||
when(experimentEnrollmentManager.isEnrolled(aci, PushNotificationManager.SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT))
|
||||
.thenReturn(inExperiment);
|
||||
|
||||
final PushNotification pushNotification = new PushNotification(
|
||||
"token", tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
|
||||
|
||||
|
||||
+7
-5
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -26,7 +27,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
import org.whispersystems.websocket.auth.InvalidCredentialsException;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
|
||||
class WebSocketAccountAuthenticatorTest {
|
||||
@@ -73,10 +74,11 @@ class WebSocketAccountAuthenticatorTest {
|
||||
accountAuthenticator,
|
||||
mock(PrincipalSupplier.class));
|
||||
|
||||
final ReusableAuth<AuthenticatedDevice> result = webSocketAuthenticator.authenticate(upgradeRequest);
|
||||
|
||||
assertEquals(expectAccount, result.ref().isPresent());
|
||||
assertEquals(expectInvalid, result.invalidCredentialsProvided());
|
||||
if (expectInvalid) {
|
||||
assertThrows(InvalidCredentialsException.class, () -> webSocketAuthenticator.authenticate(upgradeRequest));
|
||||
} else {
|
||||
assertEquals(expectAccount, webSocketAuthenticator.authenticate(upgradeRequest).ref().isPresent());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testAuthenticate() {
|
||||
|
||||
+1
-2
@@ -58,10 +58,10 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
@@ -151,7 +151,6 @@ class WebSocketConnectionTest {
|
||||
when(upgradeRequest.getParameterMap()).thenReturn(Map.of());
|
||||
account = webSocketAuthenticator.authenticate(upgradeRequest);
|
||||
assertFalse(account.ref().isPresent());
|
||||
assertFalse(account.invalidCredentialsProvided());
|
||||
|
||||
connectListener.onWebSocketConnect(sessionContext);
|
||||
verify(sessionContext, times(2)).addWebsocketClosedListener(
|
||||
|
||||
@@ -59,14 +59,6 @@ public abstract sealed class ReusableAuth<T extends Principal> {
|
||||
*/
|
||||
public abstract Optional<MutableRef<T>> mutableRef();
|
||||
|
||||
public boolean invalidCredentialsProvided() {
|
||||
return switch (this) {
|
||||
case Invalid<T> ignored -> true;
|
||||
case ReusableAuth.Anonymous<T> ignored -> false;
|
||||
case ReusableAuth.Authenticated<T> ignored-> false;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A {@link ReusableAuth} indicating no credential were provided
|
||||
*/
|
||||
@@ -75,14 +67,6 @@ public abstract sealed class ReusableAuth<T extends Principal> {
|
||||
return (ReusableAuth<T>) Anonymous.ANON_RESULT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A {@link ReusableAuth} indicating that invalid credentials were provided
|
||||
*/
|
||||
public static <T extends Principal> ReusableAuth<T> invalid() {
|
||||
//noinspection unchecked
|
||||
return (ReusableAuth<T>) Invalid.INVALID_RESULT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a successfully authenticated {@link ReusableAuth}
|
||||
*
|
||||
@@ -96,23 +80,6 @@ public abstract sealed class ReusableAuth<T extends Principal> {
|
||||
return new Authenticated<>(principal, principalSupplier);
|
||||
}
|
||||
|
||||
|
||||
private static final class Invalid<T extends Principal> extends ReusableAuth<T> {
|
||||
|
||||
@SuppressWarnings({"rawtypes"})
|
||||
private static final ReusableAuth INVALID_RESULT = new Invalid();
|
||||
|
||||
@Override
|
||||
public Optional<T> ref() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<MutableRef<T>> mutableRef() {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Anonymous<T extends Principal> extends ReusableAuth<T> {
|
||||
|
||||
@SuppressWarnings({"rawtypes"})
|
||||
|
||||
+17
@@ -173,18 +173,32 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
|
||||
* {@link org.whispersystems.websocket.ReusableAuth.MutableRef} for us to close when the request is finished
|
||||
*/
|
||||
public static final String RESOLVED_PRINCIPAL_PROPERTY = WebSocketResourceProvider.class.getName() + ".resolvedPrincipal";
|
||||
|
||||
/**
|
||||
* The property name where request byte count is stored for metrics collection
|
||||
*/
|
||||
public static final String REQUEST_LENGTH_PROPERTY = WebSocketResourceProvider.class.getName() + ".requestBytes";
|
||||
|
||||
/**
|
||||
* The property name where response byte count is stored for metrics collection
|
||||
*/
|
||||
public static final String RESPONSE_LENGTH_PROPERTY = WebSocketResourceProvider.class.getName() + ".responseBytes";
|
||||
|
||||
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.headers(getCombinedHeaders(session.getUpgradeRequest().getHeaders(), requestMessage.getHeaders()));
|
||||
|
||||
final int requestBytes = requestMessage.getBody().map(body -> body.length).orElse(0);
|
||||
|
||||
if (requestMessage.getBody().isPresent()) {
|
||||
containerRequest.setEntityStream(new ByteArrayInputStream(requestMessage.getBody().get()));
|
||||
}
|
||||
|
||||
containerRequest.setProperty(remoteAddressPropertyName, remoteAddress);
|
||||
containerRequest.setProperty(REUSABLE_AUTH_PROPERTY, reusableAuth);
|
||||
containerRequest.setProperty(REQUEST_LENGTH_PROPERTY, requestBytes);
|
||||
|
||||
ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
|
||||
CompletableFuture<ContainerResponse> responseFuture = (CompletableFuture<ContainerResponse>) jerseyHandler.apply(
|
||||
@@ -203,6 +217,8 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
|
||||
})
|
||||
.thenAccept(response -> {
|
||||
try {
|
||||
final int responseBytes = responseBody.size();
|
||||
containerRequest.setProperty(RESPONSE_LENGTH_PROPERTY, responseBytes);
|
||||
sendResponse(requestMessage, response, responseBody);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -213,6 +229,7 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
|
||||
logger.warn("Websocket Error: " + requestMessage.getVerb() + " " + requestMessage.getPath() + "\n"
|
||||
+ requestMessage.getBody(), exception);
|
||||
try {
|
||||
containerRequest.setProperty(RESPONSE_LENGTH_PROPERTY, 0);
|
||||
sendErrorResponse(requestMessage, Response.status(500).build());
|
||||
} catch (IOException e) {
|
||||
logger.warn("Failed to send error response", e);
|
||||
|
||||
+15
-15
@@ -22,7 +22,7 @@ import org.glassfish.jersey.CommonProperties;
|
||||
import org.glassfish.jersey.server.ApplicationHandler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.websocket.auth.AuthenticationException;
|
||||
import org.whispersystems.websocket.auth.InvalidCredentialsException;
|
||||
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
|
||||
import org.whispersystems.websocket.auth.WebsocketAuthValueFactoryProvider;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
@@ -45,7 +45,7 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends Jetty
|
||||
this.environment = environment;
|
||||
|
||||
environment.jersey().register(new WebSocketSessionContextValueFactoryProvider.Binder());
|
||||
environment.jersey().register(new WebsocketAuthValueFactoryProvider.Binder<T>(principalClass));
|
||||
environment.jersey().register(new WebsocketAuthValueFactoryProvider.Binder<>(principalClass));
|
||||
environment.jersey().register(new JacksonMessageBodyProvider(environment.getObjectMapper()));
|
||||
|
||||
// Jersey buffers responses (by default up to 8192 bytes) just so it can add a content length to responses. We
|
||||
@@ -64,17 +64,9 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends Jetty
|
||||
try {
|
||||
Optional<WebSocketAuthenticator<T>> authenticator = Optional.ofNullable(environment.getAuthenticator());
|
||||
|
||||
final ReusableAuth<T> authenticated;
|
||||
if (authenticator.isPresent()) {
|
||||
authenticated = authenticator.get().authenticate(request);
|
||||
|
||||
if (authenticated.invalidCredentialsProvided()) {
|
||||
response.sendForbidden("Unauthorized");
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
authenticated = ReusableAuth.anonymous();
|
||||
}
|
||||
final ReusableAuth<T> authenticated = authenticator.isPresent()
|
||||
? authenticator.get().authenticate(request)
|
||||
: ReusableAuth.anonymous();
|
||||
|
||||
Optional.ofNullable(environment.getAuthenticatedWebSocketUpgradeFilter())
|
||||
.ifPresent(filter -> filter.handleAuthentication(authenticated, request, response));
|
||||
@@ -87,11 +79,19 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends Jetty
|
||||
this.environment.getMessageFactory(),
|
||||
ofNullable(this.environment.getConnectListener()),
|
||||
this.environment.getIdleTimeout());
|
||||
} catch (AuthenticationException | IOException e) {
|
||||
} catch (final InvalidCredentialsException e) {
|
||||
try {
|
||||
response.sendForbidden("Unauthorized");
|
||||
} catch (final IOException ignored) {
|
||||
}
|
||||
return null;
|
||||
} catch (final Exception e) {
|
||||
// Authentication may fail for non-incorrect-credential reasons (e.g. we couldn't read from the account database).
|
||||
// If that happens, we don't want to incorrectly tell clients that they provided bad credentials.
|
||||
logger.warn("Authentication failure", e);
|
||||
try {
|
||||
response.sendError(500, "Failure");
|
||||
} catch (IOException ignored) {
|
||||
} catch (final IOException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.websocket.auth;
|
||||
|
||||
public class AuthenticationException extends Exception {
|
||||
|
||||
public AuthenticationException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public AuthenticationException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.websocket.auth;
|
||||
|
||||
public class InvalidCredentialsException extends Exception {
|
||||
|
||||
public InvalidCredentialsException() {
|
||||
super(null, null, true, false);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -5,10 +5,9 @@
|
||||
package org.whispersystems.websocket.auth;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Optional;
|
||||
import org.eclipse.jetty.websocket.api.UpgradeRequest;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
|
||||
public interface WebSocketAuthenticator<T extends Principal> {
|
||||
ReusableAuth<T> authenticate(UpgradeRequest request) throws AuthenticationException;
|
||||
ReusableAuth<T> authenticate(UpgradeRequest request) throws InvalidCredentialsException;
|
||||
}
|
||||
+7
-7
@@ -25,7 +25,7 @@ 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;
|
||||
import org.whispersystems.websocket.auth.AuthenticationException;
|
||||
import org.whispersystems.websocket.auth.InvalidCredentialsException;
|
||||
import org.whispersystems.websocket.auth.PrincipalSupplier;
|
||||
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
|
||||
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
|
||||
@@ -55,9 +55,9 @@ public class WebSocketResourceProviderFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnauthorized() throws AuthenticationException, IOException {
|
||||
void testUnauthorized() throws InvalidCredentialsException, IOException {
|
||||
when(environment.getAuthenticator()).thenReturn(authenticator);
|
||||
when(authenticator.authenticate(eq(request))).thenReturn(ReusableAuth.invalid());
|
||||
when(authenticator.authenticate(eq(request))).thenThrow(new InvalidCredentialsException());
|
||||
when(environment.jersey()).thenReturn(jerseyEnvironment);
|
||||
|
||||
WebSocketResourceProviderFactory<?> factory = new WebSocketResourceProviderFactory<>(environment, Account.class,
|
||||
@@ -70,7 +70,7 @@ public class WebSocketResourceProviderFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidAuthorization() throws AuthenticationException {
|
||||
void testValidAuthorization() throws InvalidCredentialsException {
|
||||
Account account = new Account();
|
||||
|
||||
when(environment.getAuthenticator()).thenReturn(authenticator);
|
||||
@@ -96,9 +96,9 @@ public class WebSocketResourceProviderFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testErrorAuthorization() throws AuthenticationException, IOException {
|
||||
void testErrorAuthorization() throws InvalidCredentialsException, IOException {
|
||||
when(environment.getAuthenticator()).thenReturn(authenticator);
|
||||
when(authenticator.authenticate(eq(request))).thenThrow(new AuthenticationException("database failure"));
|
||||
when(authenticator.authenticate(eq(request))).thenThrow(new RuntimeException("database failure"));
|
||||
when(environment.jersey()).thenReturn(jerseyEnvironment);
|
||||
|
||||
WebSocketResourceProviderFactory<Account> factory = new WebSocketResourceProviderFactory<>(environment,
|
||||
@@ -127,7 +127,7 @@ public class WebSocketResourceProviderFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAuthenticatedWebSocketUpgradeFilter() throws AuthenticationException {
|
||||
void testAuthenticatedWebSocketUpgradeFilter() throws InvalidCredentialsException {
|
||||
final Account account = new Account();
|
||||
final ReusableAuth<Account> reusableAuth =
|
||||
ReusableAuth.authenticated(account, PrincipalSupplier.forImmutablePrincipal());
|
||||
|
||||
Reference in new issue
Block a user