Compare commits

..
8 Commits
29 changed files with 461 additions and 266 deletions

No files matched your search

@@ -342,7 +342,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
Keys keys = new Keys(dynamoDbClient, config.getDynamoDbTables().getKeys().getTableName());
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient,
config.getDynamoDbTables().getMessages().getTableName(),
config.getDynamoDbTables().getMessages().getExpiration(), dynamicConfigurationManager);
config.getDynamoDbTables().getMessages().getExpiration());
RemoteConfigs remoteConfigs = new RemoteConfigs(dynamoDbClient,
config.getDynamoDbTables().getRemoteConfig().getTableName());
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
@@ -64,10 +64,6 @@ public class DynamicConfiguration {
@Valid
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
@JsonProperty
@Valid
DynamicMessageTableConfiguration messageTable = new DynamicMessageTableConfiguration();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -130,8 +126,4 @@ public class DynamicConfiguration {
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
return messagePersister;
}
public DynamicMessageTableConfiguration getMessageTableConfiguration() {
return messageTable;
}
}
@@ -1,18 +0,0 @@
/*
* Copyright 2013-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
public class DynamicMessageTableConfiguration {
@JsonProperty
private boolean writeEnvelopes = false;
public boolean isWriteEnvelopes() {
return writeEnvelopes;
}
}
@@ -239,7 +239,7 @@ public class MessageController {
if (destinationDevice.isPresent()) {
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
sendMessage(source, destination.get(), destinationDevice.get(), destinationUuid, messages.timestamp(), messages.online(), incomingMessage, userAgent);
sendMessage(source, destination.get(), destinationDevice.get(), destinationUuid, messages.timestamp(), messages.online(), messages.urgent(), incomingMessage, userAgent);
}
}
@@ -446,8 +446,8 @@ public class MessageController {
long size = 0;
for (final OutgoingMessageEntity message : messageList.messages()) {
size += message.content() == null ? 0 : message.content().length;
size += Util.isEmpty(message.source()) ? 0 : message.source().length();
size += message.content() == null ? 0 : message.content().length;
size += message.sourceUuid() == null ? 0 : 36;
}
return size;
@@ -467,7 +467,9 @@ public class MessageController {
if (deletedMessage.hasSourceUuid() && deletedMessage.getType() != Type.SERVER_DELIVERY_RECEIPT) {
try {
receiptSender.sendReceipt(auth, UUID.fromString(deletedMessage.getSourceUuid()), deletedMessage.getTimestamp());
receiptSender.sendReceipt(
UUID.fromString(deletedMessage.getDestinationUuid()), auth.getAuthenticatedDevice().getId(),
UUID.fromString(deletedMessage.getSourceUuid()), deletedMessage.getTimestamp());
} catch (Exception e) {
logger.warn("Failed to send delivery receipt", e);
}
@@ -521,6 +523,7 @@ public class MessageController {
UUID destinationUuid,
long timestamp,
boolean online,
boolean urgent,
IncomingMessage incomingMessage,
String userAgentString)
throws NoSuchUserException {
@@ -531,7 +534,8 @@ public class MessageController {
envelope = incomingMessage.toEnvelope(destinationUuid,
source.map(AuthenticatedAccount::getAccount).orElse(null),
source.map(authenticatedAccount -> authenticatedAccount.getAuthenticatedDevice().getId()).orElse(null),
timestamp == 0 ? System.currentTimeMillis() : timestamp);
timestamp == 0 ? System.currentTimeMillis() : timestamp,
urgent);
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
@@ -5,15 +5,20 @@
package org.whispersystems.textsecuregcm.entities;
import com.google.protobuf.ByteString;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.storage.Account;
import javax.annotation.Nullable;
import java.util.Base64;
import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.storage.Account;
public record IncomingMessage(int type, long destinationDeviceId, int destinationRegistrationId, String content) {
public MessageProtos.Envelope toEnvelope(final UUID destinationUuid, @Nullable Account sourceAccount, @Nullable Long sourceDeviceId, final long timestamp) {
public MessageProtos.Envelope toEnvelope(final UUID destinationUuid,
@Nullable Account sourceAccount,
@Nullable Long sourceDeviceId,
final long timestamp,
final boolean urgent) {
final MessageProtos.Envelope.Type envelopeType = MessageProtos.Envelope.Type.forNumber(type());
if (envelopeType == null) {
@@ -25,11 +30,11 @@ public record IncomingMessage(int type, long destinationDeviceId, int destinatio
envelopeBuilder.setType(envelopeType)
.setTimestamp(timestamp)
.setServerTimestamp(System.currentTimeMillis())
.setDestinationUuid(destinationUuid.toString());
.setDestinationUuid(destinationUuid.toString())
.setUrgent(urgent);
if (sourceAccount != null && sourceDeviceId != null) {
envelopeBuilder.setSource(sourceAccount.getNumber())
.setSourceUuid(sourceAccount.getUuid().toString())
envelopeBuilder.setSourceUuid(sourceAccount.getUuid().toString())
.setSourceDevice(sourceDeviceId.intValue());
}
@@ -4,9 +4,21 @@
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
public record IncomingMessageList(@NotNull @Valid List<@NotNull IncomingMessage> messages, boolean online, long timestamp) {
public record IncomingMessageList(@NotNull @Valid List<@NotNull IncomingMessage> messages,
boolean online, boolean urgent, long timestamp) {
@JsonCreator
public IncomingMessageList(@JsonProperty("messages") @NotNull @Valid List<@NotNull IncomingMessage> messages,
@JsonProperty("online") boolean online,
@JsonProperty("urgent") Boolean urgent,
@JsonProperty("timestamp") long timestamp) {
this(messages, online, urgent == null || urgent, timestamp);
}
}
@@ -6,15 +6,14 @@
package org.whispersystems.textsecuregcm.entities;
import com.google.protobuf.ByteString;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import javax.annotation.Nullable;
public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullable String source,
@Nullable UUID sourceUuid, int sourceDevice, UUID destinationUuid,
@Nullable UUID updatedPni, byte[] content, long serverTimestamp) {
public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullable UUID sourceUuid, int sourceDevice,
UUID destinationUuid, @Nullable UUID updatedPni, byte[] content,
long serverTimestamp, boolean urgent) {
public MessageProtos.Envelope toEnvelope() {
final MessageProtos.Envelope.Builder builder = MessageProtos.Envelope.newBuilder()
@@ -22,15 +21,12 @@ public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullab
.setTimestamp(timestamp())
.setServerTimestamp(serverTimestamp())
.setDestinationUuid(destinationUuid().toString())
.setServerGuid(guid().toString());
.setServerGuid(guid().toString())
.setUrgent(urgent);
if (StringUtils.isNotEmpty(source())) {
builder.setSource(source())
.setSourceDevice(sourceDevice());
if (sourceUuid() != null) {
builder.setSourceUuid(sourceUuid().toString());
}
if (sourceUuid() != null) {
builder.setSourceUuid(sourceUuid().toString());
builder.setSourceDevice(sourceDevice());
}
if (content() != null) {
@@ -49,13 +45,13 @@ public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullab
UUID.fromString(envelope.getServerGuid()),
envelope.getType().getNumber(),
envelope.getTimestamp(),
envelope.getSource(),
envelope.hasSourceUuid() ? UUID.fromString(envelope.getSourceUuid()) : null,
envelope.getSourceDevice(),
envelope.hasDestinationUuid() ? UUID.fromString(envelope.getDestinationUuid()) : null,
envelope.hasUpdatedPni() ? UUID.fromString(envelope.getUpdatedPni()) : null,
envelope.getContent().toByteArray(),
envelope.getServerTimestamp());
envelope.getServerTimestamp(),
envelope.getUrgent());
}
@Override
@@ -68,15 +64,15 @@ public record OutgoingMessageEntity(UUID guid, int type, long timestamp, @Nullab
}
final OutgoingMessageEntity that = (OutgoingMessageEntity) o;
return type == that.type && timestamp == that.timestamp && sourceDevice == that.sourceDevice
&& serverTimestamp == that.serverTimestamp && guid.equals(that.guid) && Objects.equals(source, that.source)
&& serverTimestamp == that.serverTimestamp && guid.equals(that.guid)
&& Objects.equals(sourceUuid, that.sourceUuid) && destinationUuid.equals(that.destinationUuid)
&& Objects.equals(updatedPni, that.updatedPni) && Arrays.equals(content, that.content);
&& Objects.equals(updatedPni, that.updatedPni) && Arrays.equals(content, that.content) && urgent == that.urgent;
}
@Override
public int hashCode() {
int result = Objects.hash(guid, type, timestamp, source, sourceUuid, sourceDevice, destinationUuid, updatedPni,
serverTimestamp);
int result = Objects.hash(guid, type, timestamp, sourceUuid, sourceDevice, destinationUuid, updatedPni,
serverTimestamp, urgent);
result = 31 * result + Arrays.hashCode(content);
return result;
}
@@ -12,7 +12,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.controllers.NoSuchUserException;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
@@ -38,9 +37,9 @@ public class ReceiptSender {
MetricsUtil.name(ReceiptSender.class, "executor"));
}
public CompletableFuture<Void> sendReceipt(AuthenticatedAccount source, UUID destinationUuid, long messageId) throws NoSuchUserException {
final Account sourceAccount = source.getAccount();
if (sourceAccount.getUuid().equals(destinationUuid)) {
public CompletableFuture<Void> sendReceipt(UUID sourceUuid, long sourceDeviceId, UUID destinationUuid, long messageId)
throws NoSuchUserException {
if (sourceUuid.equals(destinationUuid)) {
return CompletableFuture.completedFuture(null);
}
@@ -49,9 +48,8 @@ public class ReceiptSender {
final Envelope.Builder message = Envelope.newBuilder()
.setServerTimestamp(System.currentTimeMillis())
.setSource(sourceAccount.getNumber())
.setSourceUuid(sourceAccount.getUuid().toString())
.setSourceDevice((int) source.getAuthenticatedDevice().getId())
.setSourceUuid(sourceUuid.toString())
.setSourceDevice((int) sourceDeviceId)
.setDestinationUuid(destinationUuid.toString())
.setTimestamp(messageId)
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT);
@@ -6,12 +6,6 @@ package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -25,6 +19,12 @@ import org.whispersystems.textsecuregcm.entities.SignedPreKey;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class ChangeNumberManager {
private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
@@ -92,10 +92,10 @@ public class ChangeNumberManager {
void sendMessageToSelf(
Account sourceAndDestinationAccount, Optional<Device> destinationDevice, IncomingMessage message) {
Optional<byte[]> contents = MessageController.getMessageContent(message);
if (!contents.isPresent()) {
if (contents.isEmpty()) {
logger.debug("empty message contents sending to self, ignoring");
return;
} else if (!destinationDevice.isPresent()) {
} else if (destinationDevice.isEmpty()) {
logger.debug("destination device not present");
return;
}
@@ -107,7 +107,6 @@ public class ChangeNumberManager {
.setServerTimestamp(serverTimestamp)
.setDestinationUuid(sourceAndDestinationAccount.getUuid().toString())
.setContent(ByteString.copyFrom(contents.get()))
.setSource(sourceAndDestinationAccount.getNumber())
.setSourceUuid(sourceAndDestinationAccount.getUuid().toString())
.setSourceDevice((int) Device.MASTER_ID)
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
@@ -12,7 +12,15 @@ package org.whispersystems.textsecuregcm.storage;
*/
public interface MessageAvailabilityListener {
void handleNewMessagesAvailable();
/**
* @return whether the listener is still active. {@code false} indicates the listener can no longer handle messages
* and may be discarded
*/
boolean handleNewMessagesAvailable();
void handleMessagesPersisted();
/**
* @return whether the listener is still active. {@code false} indicates the listener can no longer handle messages
* and may be discarded
*/
boolean handleMessagesPersisted();
}
@@ -351,7 +351,11 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
newMessageNotificationCounter.increment();
notificationExecutorService.execute(() -> {
try {
findListener(channel).ifPresent(MessageAvailabilityListener::handleNewMessagesAvailable);
findListener(channel).ifPresent(listener -> {
if (!listener.handleNewMessagesAvailable()) {
removeMessageAvailabilityListener(listener);
}
});
} catch (final Exception e) {
logger.warn("Unexpected error handling new message", e);
}
@@ -360,7 +364,11 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
queuePersistedNotificationCounter.increment();
notificationExecutorService.execute(() -> {
try {
findListener(channel).ifPresent(MessageAvailabilityListener::handleMessagesPersisted);
findListener(channel).ifPresent(listener -> {
if (!listener.handleMessagesPersisted()) {
removeMessageAvailabilityListener(listener);
}
});
} catch (final Exception e) {
logger.warn("Unexpected error handling messages persisted", e);
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.storage;
import static com.codahale.metrics.MetricRegistry.name;
import static io.micrometer.core.instrument.Metrics.timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.InvalidProtocolBufferException;
import io.micrometer.core.instrument.Counter;
@@ -24,7 +25,6 @@ import java.util.stream.Collectors;
import javax.annotation.Nonnull;
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.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.util.AttributeValues;
@@ -48,17 +48,29 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private static final String LOCAL_INDEX_MESSAGE_UUID_NAME = "Message_UUID_Index";
private static final String LOCAL_INDEX_MESSAGE_UUID_KEY_SORT = "U";
private static final String KEY_TYPE = "T";
private static final String KEY_TIMESTAMP = "TS";
private static final String KEY_SOURCE = "SN";
private static final String KEY_SOURCE_UUID = "SU";
private static final String KEY_SOURCE_DEVICE = "SD";
private static final String KEY_DESTINATION_UUID = "DU";
private static final String KEY_UPDATED_PNI = "UP";
private static final String KEY_CONTENT = "C";
private static final String KEY_TTL = "E";
private static final String KEY_ENVELOPE_BYTES = "EB";
// TODO Stop reading messages by attribute value after DATE
@Deprecated
private static final String KEY_TYPE = "T";
@Deprecated
private static final String KEY_TIMESTAMP = "TS";
private static final String KEY_SOURCE_UUID = "SU";
@Deprecated
private static final String KEY_SOURCE_DEVICE = "SD";
@Deprecated
private static final String KEY_DESTINATION_UUID = "DU";
@Deprecated
private static final String KEY_UPDATED_PNI = "UP";
@Deprecated
private static final String KEY_CONTENT = "C";
private final Timer storeTimer = timer(name(getClass(), "store"));
private final Timer loadTimer = timer(name(getClass(), "load"));
private final Timer deleteByGuid = timer(name(getClass(), "delete", "guid"));
@@ -69,20 +81,16 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private final String tableName;
private final Duration timeToLive;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private static final Counter GET_MESSAGE_WITH_ATTRIBUTES_COUNTER = Metrics.counter(name(MessagesDynamoDb.class, "loadMessage"), "format", "attributes");
private static final Counter GET_MESSAGE_WITH_ENVELOPE_COUNTER = Metrics.counter(name(MessagesDynamoDb.class, "loadMessage"), "format", "envelope");
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
public MessagesDynamoDb(DynamoDbClient dynamoDb, String tableName, Duration timeToLive,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
public MessagesDynamoDb(DynamoDbClient dynamoDb, String tableName, Duration timeToLive) {
super(dynamoDb);
this.tableName = tableName;
this.timeToLive = timeToLive;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid, final long destinationDeviceId) {
@@ -103,31 +111,8 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
.put(KEY_PARTITION, partitionKey)
.put(KEY_SORT, convertSortKey(destinationDeviceId, message.getServerTimestamp(), messageUuid))
.put(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)));
if (dynamicConfigurationManager.getConfiguration().getMessageTableConfiguration().isWriteEnvelopes()) {
item.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(message.toByteArray())).build());
} else {
item.put(KEY_TYPE, AttributeValues.fromInt(message.getType().getNumber()))
.put(KEY_TIMESTAMP, AttributeValues.fromLong(message.getTimestamp()))
.put(KEY_DESTINATION_UUID, AttributeValues.fromUUID(UUID.fromString(message.getDestinationUuid())));
if (message.hasUpdatedPni()) {
item.put(KEY_UPDATED_PNI, AttributeValues.fromUUID(UUID.fromString(message.getUpdatedPni())));
}
if (message.hasSource()) {
item.put(KEY_SOURCE, AttributeValues.fromString(message.getSource()));
}
if (message.hasSourceUuid()) {
item.put(KEY_SOURCE_UUID, AttributeValues.fromUUID(UUID.fromString(message.getSourceUuid())));
}
if (message.hasSourceDevice()) {
item.put(KEY_SOURCE_DEVICE, AttributeValues.fromInt(message.getSourceDevice()));
}
if (message.hasContent()) {
item.put(KEY_CONTENT, AttributeValues.fromByteArray(message.getContent().toByteArray()));
}
}
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)))
.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(message.toByteArray())).build());
writeItems.add(WriteRequest.builder().putRequest(PutRequest.builder()
.item(item.build())
@@ -272,7 +257,8 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
});
}
private MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item)
@VisibleForTesting
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item)
throws InvalidProtocolBufferException {
final MessageProtos.Envelope envelope;
@@ -285,15 +271,14 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
final UUID messageUuid = convertLocalIndexMessageUuidSortKey(item.get(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT).b().asByteArray());
final int type = AttributeValues.getInt(item, KEY_TYPE, 0);
final long timestamp = AttributeValues.getLong(item, KEY_TIMESTAMP, 0L);
final String source = AttributeValues.getString(item, KEY_SOURCE, null);
final UUID sourceUuid = AttributeValues.getUUID(item, KEY_SOURCE_UUID, null);
final int sourceDevice = AttributeValues.getInt(item, KEY_SOURCE_DEVICE, 0);
final UUID destinationUuid = AttributeValues.getUUID(item, KEY_DESTINATION_UUID, null);
final byte[] content = AttributeValues.getByteArray(item, KEY_CONTENT, null);
final UUID updatedPni = AttributeValues.getUUID(item, KEY_UPDATED_PNI, null);
envelope = new OutgoingMessageEntity(messageUuid, type, timestamp, source, sourceUuid, sourceDevice, destinationUuid,
updatedPni, content, sortKey.getServerTimestamp()).toEnvelope();
envelope = new OutgoingMessageEntity(messageUuid, type, timestamp, sourceUuid, sourceDevice, destinationUuid,
updatedPni, content, sortKey.getServerTimestamp(), true).toEnvelope();
GET_MESSAGE_WITH_ATTRIBUTES_COUNTER.increment();
}
@@ -39,8 +39,6 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.NoSuchUserException;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.DisplacedPresenceListener;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
@@ -59,24 +57,33 @@ import org.whispersystems.websocket.messages.WebSocketResponseMessage;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class WebSocketConnection implements MessageAvailabilityListener, DisplacedPresenceListener {
private static final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
private static final Histogram messageTime = metricRegistry.histogram(name(MessageController.class, "message_delivery_duration"));
private static final Histogram primaryDeviceMessageTime = metricRegistry.histogram(name(MessageController.class, "primary_device_message_delivery_duration"));
private static final Meter sendMessageMeter = metricRegistry.meter(name(WebSocketConnection.class, "send_message"));
private static final Meter messageAvailableMeter = metricRegistry.meter(name(WebSocketConnection.class, "messagesAvailable"));
private static final Meter messagesPersistedMeter = metricRegistry.meter(name(WebSocketConnection.class, "messagesPersisted"));
private static final Meter bytesSentMeter = metricRegistry.meter(name(WebSocketConnection.class, "bytes_sent"));
private static final Meter sendFailuresMeter = metricRegistry.meter(name(WebSocketConnection.class, "send_failures"));
private static final Meter discardedMessagesMeter = metricRegistry.meter(name(WebSocketConnection.class, "discardedMessages"));
private static final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
private static final Histogram messageTime = metricRegistry.histogram(
name(MessageController.class, "message_delivery_duration"));
private static final Histogram primaryDeviceMessageTime = metricRegistry.histogram(
name(MessageController.class, "primary_device_message_delivery_duration"));
private static final Meter sendMessageMeter = metricRegistry.meter(name(WebSocketConnection.class, "send_message"));
private static final Meter messageAvailableMeter = metricRegistry.meter(
name(WebSocketConnection.class, "messagesAvailable"));
private static final Meter messagesPersistedMeter = metricRegistry.meter(
name(WebSocketConnection.class, "messagesPersisted"));
private static final Meter bytesSentMeter = metricRegistry.meter(name(WebSocketConnection.class, "bytes_sent"));
private static final Meter sendFailuresMeter = metricRegistry.meter(name(WebSocketConnection.class, "send_failures"));
private static final Meter discardedMessagesMeter = metricRegistry.meter(
name(WebSocketConnection.class, "discardedMessages"));
private static final String INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME = name(WebSocketConnection.class, "initialQueueLength");
private static final String INITIAL_QUEUE_DRAIN_TIMER_NAME = name(WebSocketConnection.class, "drainInitialQueue");
private static final String SLOW_QUEUE_DRAIN_COUNTER_NAME = name(WebSocketConnection.class, "slowQueueDrain");
private static final String QUEUE_DRAIN_RETRY_COUNTER_NAME = name(WebSocketConnection.class, "queueDrainRetry");
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
private static final String NON_SUCCESS_RESPONSE_COUNTER_NAME = name(WebSocketConnection.class, "clientNonSuccessResponse");
private static final String STATUS_CODE_TAG = "status";
private static final String STATUS_MESSAGE_TAG = "message";
private static final String INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME = name(WebSocketConnection.class,
"initialQueueLength");
private static final String INITIAL_QUEUE_DRAIN_TIMER_NAME = name(WebSocketConnection.class, "drainInitialQueue");
private static final String SLOW_QUEUE_DRAIN_COUNTER_NAME = name(WebSocketConnection.class, "slowQueueDrain");
private static final String QUEUE_DRAIN_RETRY_COUNTER_NAME = name(WebSocketConnection.class, "queueDrainRetry");
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
private static final String NON_SUCCESS_RESPONSE_COUNTER_NAME = name(WebSocketConnection.class,
"clientNonSuccessResponse");
private static final String CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class,
"messageAvailableAfterClientClosed");
private static final String STATUS_CODE_TAG = "status";
private static final String STATUS_MESSAGE_TAG = "message";
private static final long SLOW_DRAIN_THRESHOLD = 10_000;
@@ -228,10 +235,14 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
}
private void sendDeliveryReceiptFor(Envelope message) {
if (!message.hasSource()) return;
if (!message.hasSourceUuid()) {
return;
}
try {
receiptSender.sendReceipt(auth, UUID.fromString(message.getSourceUuid()), message.getTimestamp());
receiptSender.sendReceipt(UUID.fromString(message.getDestinationUuid()),
auth.getAuthenticatedDevice().getId(), UUID.fromString(message.getSourceUuid()),
message.getTimestamp());
} catch (NoSuchUserException e) {
logger.info("No longer registered: {}", e.getMessage());
} catch (WebApplicationException e) {
@@ -283,11 +294,12 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
}
} else {
if (client.isOpen()) {
logger.debug("Failed to clear queue", cause);
if (consecutiveRetries.incrementAndGet() > MAX_CONSECUTIVE_RETRIES) {
logger.warn("Max consecutive retries exceeded", cause);
client.close(1011, "Failed to retrieve messages");
} else {
logger.debug("Failed to clear queue", cause);
final List<Tag> tags = List.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
Metrics.counter(QUEUE_DRAIN_RETRY_COUNTER_NAME, tags).increment();
@@ -348,19 +360,34 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
}
@Override
public void handleNewMessagesAvailable() {
public boolean handleNewMessagesAvailable() {
if (!client.isOpen()) {
// The client may become closed without successful removal of references to the `MessageAvailabilityListener`
Metrics.counter(CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME).increment();
return false;
}
messageAvailableMeter.mark();
storedMessageState.compareAndSet(StoredMessageState.EMPTY, StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE);
processStoredMessages();
return true;
}
@Override
public void handleMessagesPersisted() {
public boolean handleMessagesPersisted() {
if (!client.isOpen()) {
// The client may become without successful removal of references to the `MessageAvailabilityListener`
Metrics.counter(CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME).increment();
return false;
}
messagesPersistedMeter.mark();
storedMessageState.set(StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
processStoredMessages();
return true;
}
@Override
@@ -369,7 +396,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)));
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags);
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
final int code;
final String message;
@@ -152,7 +152,7 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
configuration.getDynamoDbTables().getKeys().getTableName());
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient,
configuration.getDynamoDbTables().getMessages().getTableName(),
configuration.getDynamoDbTables().getMessages().getExpiration(), dynamicConfigurationManager);
configuration.getDynamoDbTables().getMessages().getExpiration());
FaultTolerantRedisCluster messageInsertCacheCluster = new FaultTolerantRedisCluster("message_insert_cluster",
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
FaultTolerantRedisCluster messageReadDeleteCluster = new FaultTolerantRedisCluster("message_read_delete_cluster",
@@ -155,7 +155,7 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
configuration.getDynamoDbTables().getKeys().getTableName());
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient,
configuration.getDynamoDbTables().getMessages().getTableName(),
configuration.getDynamoDbTables().getMessages().getExpiration(), dynamicConfigurationManager);
configuration.getDynamoDbTables().getMessages().getExpiration());
FaultTolerantRedisCluster messageInsertCacheCluster = new FaultTolerantRedisCluster("message_insert_cluster",
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
FaultTolerantRedisCluster messageReadDeleteCluster = new FaultTolerantRedisCluster("message_read_delete_cluster",
@@ -158,7 +158,7 @@ public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperSer
configuration.getDynamoDbTables().getKeys().getTableName());
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient,
configuration.getDynamoDbTables().getMessages().getTableName(),
configuration.getDynamoDbTables().getMessages().getExpiration(), dynamicConfigurationManager);
configuration.getDynamoDbTables().getMessages().getExpiration());
FaultTolerantRedisCluster messageInsertCacheCluster = new FaultTolerantRedisCluster("message_insert_cluster",
configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
FaultTolerantRedisCluster messageReadDeleteCluster = new FaultTolerantRedisCluster("message_read_delete_cluster",
+1 -1
View File
@@ -32,7 +32,6 @@ message Envelope {
}
optional Type type = 1;
optional string source = 2;
optional string source_uuid = 11;
optional uint32 source_device = 7;
optional uint64 timestamp = 5;
@@ -41,6 +40,7 @@ message Envelope {
optional uint64 server_timestamp = 10;
optional bool ephemeral = 12; // indicates that the message should not be persisted if the recipient is offline
optional string destination_uuid = 13;
optional bool urgent = 14 [default=true];
optional string updated_pni = 15;
// next: 16
}
@@ -34,7 +34,6 @@ import io.dropwizard.testing.junit5.ResourceExtension;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -44,7 +43,6 @@ import java.util.stream.Stream;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -207,8 +205,30 @@ class MessageControllerTest {
ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(1)).sendMessage(any(Account.class), any(Device.class), captor.capture(), eq(false));
assertTrue(captor.getValue().hasSource());
assertTrue(captor.getValue().hasSourceUuid());
assertTrue(captor.getValue().hasSourceDevice());
assertTrue(captor.getValue().getUrgent());
}
@Test
void testSingleDeviceCurrentNotUrgent() throws Exception {
Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_single_device_not_urgent.json"),
IncomingMessageList.class),
MediaType.APPLICATION_JSON_TYPE));
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(1)).sendMessage(any(Account.class), any(Device.class), captor.capture(), eq(false));
assertTrue(captor.getValue().hasSourceUuid());
assertTrue(captor.getValue().hasSourceDevice());
assertFalse(captor.getValue().getUrgent());
}
@Test
@@ -227,7 +247,7 @@ class MessageControllerTest {
ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(1)).sendMessage(any(Account.class), any(Device.class), captor.capture(), eq(false));
assertTrue(captor.getValue().hasSource());
assertTrue(captor.getValue().hasSourceUuid());
assertTrue(captor.getValue().hasSourceDevice());
}
@@ -260,7 +280,7 @@ class MessageControllerTest {
ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(1)).sendMessage(any(Account.class), any(Device.class), captor.capture(), eq(false));
assertFalse(captor.getValue().hasSource());
assertFalse(captor.getValue().hasSourceUuid());
assertFalse(captor.getValue().hasSourceDevice());
}
@@ -330,7 +350,31 @@ class MessageControllerTest {
assertThat("Good Response Code", response.getStatus(), is(equalTo(200)));
verify(messageSender, times(2)).sendMessage(any(Account.class), any(Device.class), any(Envelope.class), eq(false));
final ArgumentCaptor<Envelope> envelopeCaptor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(2)).sendMessage(any(Account.class), any(Device.class), envelopeCaptor.capture(), eq(false));
envelopeCaptor.getAllValues().forEach(envelope -> assertTrue(envelope.getUrgent()));
}
@Test
void testMultiDeviceNotUrgent() throws Exception {
Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_multi_device_not_urgent.json"),
IncomingMessageList.class),
MediaType.APPLICATION_JSON_TYPE));
assertThat("Good Response Code", response.getStatus(), is(equalTo(200)));
final ArgumentCaptor<Envelope> envelopeCaptor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(2)).sendMessage(any(Account.class), any(Device.class), envelopeCaptor.capture(), eq(false));
envelopeCaptor.getAllValues().forEach(envelope -> assertFalse(envelope.getUrgent()));
}
@Test
@@ -381,8 +425,10 @@ class MessageControllerTest {
final UUID updatedPniOne = UUID.randomUUID();
List<Envelope> messages = List.of(
generateEnvelope(messageGuidOne, Envelope.Type.CIPHERTEXT_VALUE, timestampOne, "+14152222222", sourceUuid, 2, AuthHelper.VALID_UUID, updatedPniOne, "hi there".getBytes(), 0),
generateEnvelope(messageGuidTwo, Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, timestampTwo, "+14152222222", sourceUuid, 2, AuthHelper.VALID_UUID, null, null, 0)
generateEnvelope(messageGuidOne, Envelope.Type.CIPHERTEXT_VALUE, timestampOne, sourceUuid, 2,
AuthHelper.VALID_UUID, updatedPniOne, "hi there".getBytes(), 0),
generateEnvelope(messageGuidTwo, Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, timestampTwo, sourceUuid, 2,
AuthHelper.VALID_UUID, null, null, 0)
);
OutgoingMessageEntityList messagesList = new OutgoingMessageEntityList(messages.stream()
@@ -420,8 +466,10 @@ class MessageControllerTest {
final long timestampTwo = 313388;
final List<Envelope> messages = List.of(
generateEnvelope(UUID.randomUUID(), Envelope.Type.CIPHERTEXT_VALUE, timestampOne, "+14152222222", UUID.randomUUID(), 2, AuthHelper.VALID_UUID, null, "hi there".getBytes(), 0),
generateEnvelope(UUID.randomUUID(), Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, timestampTwo, "+14152222222", UUID.randomUUID(), 2, AuthHelper.VALID_UUID, null, null, 0)
generateEnvelope(UUID.randomUUID(), Envelope.Type.CIPHERTEXT_VALUE, timestampOne, UUID.randomUUID(), 2,
AuthHelper.VALID_UUID, null, "hi there".getBytes(), 0),
generateEnvelope(UUID.randomUUID(), Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE, timestampTwo,
UUID.randomUUID(), 2, AuthHelper.VALID_UUID, null, null, 0)
);
when(messagesManager.getMessagesForDevice(eq(AuthHelper.VALID_UUID), eq(1L), anyString(), anyBoolean()))
@@ -446,12 +494,12 @@ class MessageControllerTest {
UUID uuid1 = UUID.randomUUID();
when(messagesManager.delete(AuthHelper.VALID_UUID, 1, uuid1, null)).thenReturn(Optional.of(generateEnvelope(
uuid1, Envelope.Type.CIPHERTEXT_VALUE,
timestamp, "+14152222222", sourceUuid, 1, AuthHelper.VALID_UUID, null, "hi".getBytes(), 0)));
timestamp, sourceUuid, 1, AuthHelper.VALID_UUID, null, "hi".getBytes(), 0)));
UUID uuid2 = UUID.randomUUID();
when(messagesManager.delete(AuthHelper.VALID_UUID, 1, uuid2, null)).thenReturn(Optional.of(generateEnvelope(
uuid2, Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE,
System.currentTimeMillis(), "+14152222222", sourceUuid, 1, AuthHelper.VALID_UUID, null, null, 0)));
System.currentTimeMillis(), sourceUuid, 1, AuthHelper.VALID_UUID, null, null, 0)));
UUID uuid3 = UUID.randomUUID();
when(messagesManager.delete(AuthHelper.VALID_UUID, 1, uuid3, null)).thenReturn(Optional.empty());
@@ -463,7 +511,8 @@ class MessageControllerTest {
.delete();
assertThat("Good Response Code", response.getStatus(), is(equalTo(204)));
verify(receiptSender).sendReceipt(any(AuthenticatedAccount.class), eq(sourceUuid), eq(timestamp));
verify(receiptSender).sendReceipt(eq(AuthHelper.VALID_UUID), eq(1L),
eq(sourceUuid), eq(timestamp));
response = resources.getJerseyTest()
.target(String.format("/v1/messages/uuid/%s", uuid2))
@@ -592,7 +641,7 @@ class MessageControllerTest {
.request()
.header(OptionalAccess.UNIDENTIFIED, Base64.getEncoder().encodeToString("1234".getBytes()))
.put(Entity.entity(new IncomingMessageList(
List.of(new IncomingMessage(1, 1L, 1, new String(contentBytes))), false,
List.of(new IncomingMessage(1, 1L, 1, new String(contentBytes))), false, true,
System.currentTimeMillis()),
MediaType.APPLICATION_JSON_TYPE));
@@ -631,8 +680,8 @@ class MessageControllerTest {
Arguments.of("fixtures/current_message_single_device_server_receipt_type.json", false)
);
}
private static Envelope generateEnvelope(UUID guid, int type, long timestamp, String source, UUID sourceUuid,
private static Envelope generateEnvelope(UUID guid, int type, long timestamp, UUID sourceUuid,
int sourceDevice, UUID destinationUuid, UUID updatedPni, byte[] content, long serverTimestamp) {
final MessageProtos.Envelope.Builder builder = MessageProtos.Envelope.newBuilder()
@@ -642,13 +691,9 @@ class MessageControllerTest {
.setDestinationUuid(destinationUuid.toString())
.setServerGuid(guid.toString());
if (StringUtils.isNotEmpty(source)) {
builder.setSource(source)
.setSourceDevice(sourceDevice);
if (sourceUuid != null) {
builder.setSourceUuid(sourceUuid.toString());
}
if (sourceUuid != null) {
builder.setSourceUuid(sourceUuid.toString());
builder.setSourceDevice(sourceDevice);
}
if (content != null) {
@@ -0,0 +1,51 @@
/*
* Copyright 2013-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import static org.junit.jupiter.api.Assertions.*;
class IncomingMessageListTest {
@Test
void fromJson() throws JsonProcessingException {
{
final String incomingMessageListJson = """
{
"messages": [],
"timestamp": 123456789,
"online": true,
"urgent": false
}
""";
final IncomingMessageList incomingMessageList =
SystemMapper.getMapper().readValue(incomingMessageListJson, IncomingMessageList.class);
assertTrue(incomingMessageList.online());
assertFalse(incomingMessageList.urgent());
}
{
final String incomingMessageListJson = """
{
"messages": [],
"timestamp": 123456789,
"online": true
}
""";
final IncomingMessageList incomingMessageList =
SystemMapper.getMapper().readValue(incomingMessageListJson, IncomingMessageList.class);
assertTrue(incomingMessageList.online());
assertTrue(incomingMessageList.urgent());
}
}
}
@@ -20,7 +20,7 @@ class OutgoingMessageEntityTest {
@ParameterizedTest
@MethodSource
void toFromEnvelope(@Nullable final String source, @Nullable final UUID sourceUuid, @Nullable final UUID updatedPni) {
void toFromEnvelope(@Nullable final UUID sourceUuid, @Nullable final UUID updatedPni) {
final byte[] messageContent = new byte[16];
new Random().nextBytes(messageContent);
@@ -30,21 +30,21 @@ class OutgoingMessageEntityTest {
final OutgoingMessageEntity outgoingMessageEntity = new OutgoingMessageEntity(UUID.randomUUID(),
MessageProtos.Envelope.Type.CIPHERTEXT_VALUE,
messageTimestamp,
"+18005551234",
UUID.randomUUID(),
source != null ? (int) Device.MASTER_ID : 0,
UUID.randomUUID(),
sourceUuid != null ? (int) Device.MASTER_ID : 0,
UUID.randomUUID(),
updatedPni,
messageContent,
serverTimestamp);
serverTimestamp,
true);
assertEquals(outgoingMessageEntity, OutgoingMessageEntity.fromEnvelope(outgoingMessageEntity.toEnvelope()));
}
private static Stream<Arguments> toFromEnvelope() {
return Stream.of(
Arguments.of("+18005551234", UUID.randomUUID(), UUID.randomUUID()),
Arguments.of("+18005551234", UUID.randomUUID(), null),
Arguments.of(null, null, UUID.randomUUID()));
Arguments.of(UUID.randomUUID(), UUID.randomUUID()),
Arguments.of(UUID.randomUUID(), null),
Arguments.of(null, UUID.randomUUID()));
}
}
@@ -130,7 +130,6 @@ public class ChangeNumberManagerTest {
assertEquals(aci, UUID.fromString(envelope.getDestinationUuid()));
assertEquals(aci, UUID.fromString(envelope.getSourceUuid()));
assertEquals(changedE164, envelope.getSource());
assertEquals(Device.MASTER_ID, envelope.getSourceDevice());
assertEquals(updatedPhoneNumberIdentifiersByAccount.get(account), UUID.fromString(envelope.getUpdatedPni()));
}
@@ -7,17 +7,18 @@ package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import io.lettuce.core.cluster.SlotHash;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
@@ -31,13 +32,10 @@ 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.entities.MessageProtos.Envelope.Type;
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbExtension;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
class MessagePersisterIntegrationTest {
@@ -66,8 +64,10 @@ class MessagePersisterIntegrationTest {
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
final MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbExtension.getDynamoDbClient(),
MessagesDynamoDbExtension.TABLE_NAME, Duration.ofDays(14), dynamicConfigurationManager);
MessagesDynamoDbExtension.TABLE_NAME, Duration.ofDays(14));
final AccountsManager accountsManager = mock(AccountsManager.class);
notificationExecutorService = Executors.newSingleThreadExecutor();
@@ -124,14 +124,16 @@ class MessagePersisterIntegrationTest {
messagesManager.addMessageAvailabilityListener(account.getUuid(), 1, new MessageAvailabilityListener() {
@Override
public void handleNewMessagesAvailable() {
public boolean handleNewMessagesAvailable() {
return true;
}
@Override
public void handleMessagesPersisted() {
public boolean handleMessagesPersisted() {
synchronized (messagesPersisted) {
messagesPersisted.set(true);
messagesPersisted.notifyAll();
return true;
}
}
});
@@ -146,20 +148,19 @@ class MessagePersisterIntegrationTest {
messagePersister.stop();
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(messageCount);
DynamoDbClient dynamoDB = dynamoDbExtension.getDynamoDbClient();
for (Map<String, AttributeValue> item : dynamoDB
.scan(ScanRequest.builder().tableName(MessagesDynamoDbExtension.TABLE_NAME).build()).items()) {
persistedMessages.add(MessageProtos.Envelope.newBuilder()
.setServerGuid(AttributeValues.getUUID(item, "U", null).toString())
.setType(Type.forNumber(AttributeValues.getInt(item, "T", -1)))
.setTimestamp(AttributeValues.getLong(item, "TS", -1))
.setServerTimestamp(extractServerTimestamp(AttributeValues.getByteArray(item, "S", null)))
.setContent(ByteString.copyFrom(AttributeValues.getByteArray(item, "C", null)))
.setDestinationUuid(AttributeValues.getUUID(item, "DU", null).toString())
.build());
}
final List<MessageProtos.Envelope> persistedMessages =
dynamoDB.scan(ScanRequest.builder().tableName(MessagesDynamoDbExtension.TABLE_NAME).build()).items().stream()
.map(item -> {
try {
return MessagesDynamoDb.convertItemToEnvelope(item);
} catch (InvalidProtocolBufferException e) {
fail("Could not parse stored message", e);
return null;
}
})
.toList();
assertEquals(expectedMessages, persistedMessages);
});
@@ -21,10 +21,12 @@ import java.util.List;
import java.util.Optional;
import java.util.Random;
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.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
@@ -227,7 +229,7 @@ class MessagesCacheTest {
if (!sealedSender) {
envelopeBuilder.setSourceDevice(random.nextInt(256))
.setSource("+1" + RandomStringUtils.randomNumeric(10));
.setSourceUuid(UUID.randomUUID().toString());
}
return envelopeBuilder.build();
@@ -287,15 +289,18 @@ class MessagesCacheTest {
final MessageAvailabilityListener listener = new MessageAvailabilityListener() {
@Override
public void handleNewMessagesAvailable() {
public boolean handleNewMessagesAvailable() {
synchronized (notified) {
notified.set(true);
notified.notifyAll();
return true;
}
}
@Override
public void handleMessagesPersisted() {
public boolean handleMessagesPersisted() {
return true;
}
};
@@ -320,14 +325,17 @@ class MessagesCacheTest {
final MessageAvailabilityListener listener = new MessageAvailabilityListener() {
@Override
public void handleNewMessagesAvailable() {
public boolean handleNewMessagesAvailable() {
return true;
}
@Override
public void handleMessagesPersisted() {
public boolean handleMessagesPersisted() {
synchronized (notified) {
notified.set(true);
notified.notifyAll();
return true;
}
}
};
@@ -348,4 +356,72 @@ class MessagesCacheTest {
});
}
/**
* Helper class that implements {@link MessageAvailabilityListener#handleNewMessagesAvailable()} by always returning
* {@code false}. Its {@code counter} field tracks how many times {@code handleNewMessagesAvailable} has been called.
* <p>
* It uses a parameterized {@code AtomicBoolean} for asynchronous observation. It <em>must</em> be reset to
* {@code false} between observations.
*/
private static class NewMessagesAvailabilityClosedListener implements MessageAvailabilityListener {
private int counter;
private final Consumer<Integer> messageHandledCallback;
private final CompletableFuture<Void> firstMessageHandled = new CompletableFuture<>();
private NewMessagesAvailabilityClosedListener(final Consumer<Integer> messageHandledCallback) {
this.messageHandledCallback = messageHandledCallback;
}
@Override
public boolean handleNewMessagesAvailable() {
counter++;
messageHandledCallback.accept(counter);
firstMessageHandled.complete(null);
return false;
}
@Override
public boolean handleMessagesPersisted() {
return true;
}
}
@Test
void testAvailabilityListenerResponses() {
final NewMessagesAvailabilityClosedListener listener1 = new NewMessagesAvailabilityClosedListener(
count -> assertEquals(1, count));
final NewMessagesAvailabilityClosedListener listener2 = new NewMessagesAvailabilityClosedListener(
count -> assertEquals(1, count));
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
messagesCache.addMessageAvailabilityListener(DESTINATION_UUID, DESTINATION_DEVICE_ID, listener1);
final UUID messageGuid1 = UUID.randomUUID();
messagesCache.insert(messageGuid1, DESTINATION_UUID, DESTINATION_DEVICE_ID,
generateRandomMessage(messageGuid1, true));
listener1.firstMessageHandled.get();
// Avoid a race condition by blocking on the message handled future *and* the current notification executor task—
// the notification executor task includes unsubscribing `listener1`, and, if we don’t wait, sometimes
// `listener2` will get subscribed before `listener1` is cleaned up
notificationExecutorService.submit(() -> listener1.firstMessageHandled.get()).get();
final UUID messageGuid2 = UUID.randomUUID();
messagesCache.insert(messageGuid2, DESTINATION_UUID, DESTINATION_DEVICE_ID,
generateRandomMessage(messageGuid2, true));
messagesCache.addMessageAvailabilityListener(DESTINATION_UUID, DESTINATION_DEVICE_ID, listener2);
final UUID messageGuid3 = UUID.randomUUID();
messagesCache.insert(messageGuid3, DESTINATION_UUID, DESTINATION_DEVICE_ID,
generateRandomMessage(messageGuid3, true));
listener2.firstMessageHandled.get();
});
}
}
@@ -6,8 +6,6 @@
package org.whispersystems.textsecuregcm.storage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import java.time.Duration;
@@ -17,10 +15,6 @@ import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessageTableConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbExtension;
@@ -45,7 +39,6 @@ class MessagesDynamoDbTest {
MESSAGE1 = builder.build();
builder.setType(MessageProtos.Envelope.Type.CIPHERTEXT);
builder.setSource("12348675309");
builder.setSourceUuid(UUID.randomUUID().toString());
builder.setSourceDevice(1);
builder.setContent(ByteString.copyFromUtf8("MOO"));
@@ -56,7 +49,6 @@ class MessagesDynamoDbTest {
MESSAGE2 = builder.build();
builder.setType(MessageProtos.Envelope.Type.UNIDENTIFIED_SENDER);
builder.clearSource();
builder.clearSourceUuid();
builder.clearSourceDevice();
builder.setContent(ByteString.copyFromUtf8("COW"));
@@ -67,7 +59,6 @@ class MessagesDynamoDbTest {
MESSAGE3 = builder.build();
}
private DynamicMessageTableConfiguration dynamicMessageTableConfiguration;
private MessagesDynamoDb messagesDynamoDb;
@@ -76,24 +67,12 @@ class MessagesDynamoDbTest {
@BeforeEach
void setup() {
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
dynamicMessageTableConfiguration = mock(DynamicMessageTableConfiguration.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getMessageTableConfiguration()).thenReturn(dynamicMessageTableConfiguration);
messagesDynamoDb = new MessagesDynamoDb(dynamoDbExtension.getDynamoDbClient(), MessagesDynamoDbExtension.TABLE_NAME,
Duration.ofDays(14), dynamicConfigurationManager);
Duration.ofDays(14));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testSimpleFetchAfterInsert(final boolean writeEnvelopes) {
when(dynamicMessageTableConfiguration.isWriteEnvelopes()).thenReturn(writeEnvelopes);
@Test
void testSimpleFetchAfterInsert() {
final UUID destinationUuid = UUID.randomUUID();
final int destinationDeviceId = random.nextInt(255) + 1;
messagesDynamoDb.store(List.of(MESSAGE1, MESSAGE2, MESSAGE3), destinationUuid, destinationDeviceId);
@@ -28,10 +28,8 @@ class MessagesManagerTest {
@Test
void insert() {
final String sourceNumber = "+12025551212";
final UUID sourceAci = UUID.randomUUID();
final Envelope message = Envelope.newBuilder()
.setSource(sourceNumber)
.setSourceUuid(sourceAci.toString())
.build();
@@ -41,8 +41,6 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessageTableConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
@@ -50,7 +48,6 @@ import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.MessagesCache;
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
@@ -86,21 +83,11 @@ class WebSocketConnectionIntegrationTest {
@BeforeEach
void setUp() throws Exception {
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
final DynamicMessageTableConfiguration dynamicMessageTableConfiguration = mock(DynamicMessageTableConfiguration.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getMessageTableConfiguration()).thenReturn(dynamicMessageTableConfiguration);
executorService = Executors.newSingleThreadExecutor();
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
REDIS_CLUSTER_EXTENSION.getRedisCluster(), executorService);
messagesDynamoDb = new MessagesDynamoDb(dynamoDbExtension.getDynamoDbClient(), MessagesDynamoDbExtension.TABLE_NAME,
Duration.ofDays(7), dynamicConfigurationManager);
Duration.ofDays(7));
reportMessageManager = mock(ReportMessageManager.class);
account = mock(Account.class);
device = mock(Device.class);
@@ -68,10 +68,12 @@ import org.whispersystems.websocket.session.WebSocketSessionContext;
class WebSocketConnectionTest {
private static final String VALID_USER = "+14152222222";
private static final String VALID_USER = "+14152222222";
private static final String INVALID_USER = "+14151111111";
private static final String VALID_PASSWORD = "secure";
private static final int SOURCE_DEVICE_ID = 1;
private static final String VALID_PASSWORD = "secure";
private static final String INVALID_PASSWORD = "insecure";
private AccountAuthenticator accountAuthenticator;
@@ -138,15 +140,16 @@ class WebSocketConnectionTest {
void testOpen() throws Exception {
MessagesManager storedMessages = mock(MessagesManager.class);
UUID accountUuid = UUID.randomUUID();
UUID accountUuid = UUID.randomUUID();
UUID senderOneUuid = UUID.randomUUID();
UUID senderTwoUuid = UUID.randomUUID();
List<Envelope> outgoingMessages = List.of(createMessage("sender1", senderOneUuid, UUID.randomUUID(), 1111, "first"),
createMessage("sender1", senderOneUuid, UUID.randomUUID(), 2222, "second"),
createMessage("sender2", senderTwoUuid, UUID.randomUUID(), 3333, "third"));
List<Envelope> outgoingMessages = List.of(createMessage("sender1", senderOneUuid, accountUuid, 1111, "first"),
createMessage("sender1", senderOneUuid, accountUuid, 2222, "second"),
createMessage("sender2", senderTwoUuid, accountUuid, 3333, "third"));
when(device.getId()).thenReturn(2L);
final long deviceId = 2L;
when(device.getId()).thenReturn(deviceId);
when(account.getNumber()).thenReturn("+14152222222");
when(account.getUuid()).thenReturn(accountUuid);
@@ -196,8 +199,10 @@ class WebSocketConnectionTest {
futures.get(0).completeExceptionally(new IOException());
futures.get(2).completeExceptionally(new IOException());
verify(storedMessages, times(1)).delete(eq(accountUuid), eq(2L), eq(UUID.fromString(outgoingMessages.get(1).getServerGuid())), eq(outgoingMessages.get(1).getServerTimestamp()));
verify(receiptSender, times(1)).sendReceipt(eq(auth), eq(senderOneUuid), eq(2222L));
verify(storedMessages, times(1)).delete(eq(accountUuid), eq(deviceId),
eq(UUID.fromString(outgoingMessages.get(1).getServerGuid())), eq(outgoingMessages.get(1).getServerTimestamp()));
verify(receiptSender, times(1)).sendReceipt(eq(accountUuid), eq(deviceId), eq(senderOneUuid),
eq(2222L));
connection.stop();
verify(client).close(anyInt(), anyString());
@@ -215,6 +220,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(accountUuid);
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
when(messagesManager.getMessagesForDevice(eq(accountUuid), eq(1L), eq("Test-UA"), anyBoolean()))
@@ -268,13 +274,13 @@ class WebSocketConnectionTest {
void testPendingSend() throws Exception {
MessagesManager storedMessages = mock(MessagesManager.class);
final UUID accountUuid = UUID.randomUUID();
final UUID senderTwoUuid = UUID.randomUUID();
final Envelope firstMessage = Envelope.newBuilder()
.setServerGuid(UUID.randomUUID().toString())
.setSource("sender1")
.setSourceUuid(UUID.randomUUID().toString())
.setDestinationUuid(UUID.randomUUID().toString())
.setDestinationUuid(accountUuid.toString())
.setUpdatedPni(UUID.randomUUID().toString())
.setTimestamp(System.currentTimeMillis())
.setSourceDevice(1)
@@ -283,9 +289,8 @@ class WebSocketConnectionTest {
final Envelope secondMessage = Envelope.newBuilder()
.setServerGuid(UUID.randomUUID().toString())
.setSource("sender2")
.setSourceUuid(senderTwoUuid.toString())
.setDestinationUuid(UUID.randomUUID().toString())
.setDestinationUuid(accountUuid.toString())
.setTimestamp(System.currentTimeMillis())
.setSourceDevice(2)
.setType(Envelope.Type.CIPHERTEXT)
@@ -293,10 +298,11 @@ class WebSocketConnectionTest {
final List<Envelope> pendingMessages = List.of(firstMessage, secondMessage);
when(device.getId()).thenReturn(2L);
final long deviceId = 2L;
when(device.getId()).thenReturn(deviceId);
when(account.getNumber()).thenReturn("+14152222222");
when(account.getUuid()).thenReturn(UUID.randomUUID());
when(account.getUuid()).thenReturn(accountUuid);
final Device sender1device = mock(Device.class);
@@ -338,7 +344,8 @@ class WebSocketConnectionTest {
futures.get(1).complete(response);
futures.get(0).completeExceptionally(new IOException());
verify(receiptSender, times(1)).sendReceipt(eq(auth), eq(senderTwoUuid), eq(secondMessage.getTimestamp()));
verify(receiptSender, times(1)).sendReceipt(eq(account.getUuid()), eq(deviceId), eq(senderTwoUuid),
eq(secondMessage.getTimestamp()));
connection.stop();
verify(client).close(anyInt(), anyString());
@@ -354,6 +361,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(UUID.randomUUID());
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
final AtomicBoolean threadWaiting = new AtomicBoolean(false);
@@ -420,6 +428,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(UUID.randomUUID());
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
final List<Envelope> firstPageMessages =
@@ -463,6 +472,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(UUID.randomUUID());
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
final UUID senderUuid = UUID.randomUUID();
@@ -519,6 +529,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(accountUuid);
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
when(messagesManager.getMessagesForDevice(eq(accountUuid), eq(1L), eq("Test-UA"), anyBoolean()))
@@ -548,6 +559,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(accountUuid);
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
final List<Envelope> firstPageMessages =
@@ -596,6 +608,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(accountUuid);
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
when(messagesManager.getMessagesForDevice(eq(accountUuid), eq(1L), eq("Test-UA"), anyBoolean()))
@@ -629,6 +642,7 @@ class WebSocketConnectionTest {
when(account.getNumber()).thenReturn("+18005551234");
when(account.getUuid()).thenReturn(accountUuid);
when(device.getId()).thenReturn(1L);
when(client.isOpen()).thenReturn(true);
when(client.getUserAgent()).thenReturn("Test-UA");
when(messagesManager.getMessagesForDevice(eq(accountUuid), eq(1L), eq("Test-UA"), anyBoolean()))
@@ -854,9 +868,8 @@ class WebSocketConnectionTest {
.setType(Envelope.Type.CIPHERTEXT)
.setTimestamp(timestamp)
.setServerTimestamp(0)
.setSource(sender)
.setSourceUuid(senderUuid.toString())
.setSourceDevice(1)
.setSourceDevice(SOURCE_DEVICE_ID)
.setDestinationUuid(destinationUuid.toString())
.setContent(ByteString.copyFrom(content.getBytes(StandardCharsets.UTF_8)))
.build();
@@ -0,0 +1,19 @@
{
"urgent": false,
"messages": [
{
"type": 1,
"destinationDeviceId": 1,
"destinationRegistrationId": 222,
"content": "Zm9vYmFyego",
"timestamp": 1234
},
{
"type": 1,
"destinationDeviceId": 2,
"destinationRegistrationId": 333,
"content": "Zm9vYmFyego",
"timestamp": 1234
}
]
}
@@ -0,0 +1,11 @@
{
"urgent": false,
"messages": [
{
"type": 1,
"destinationDeviceId": 1,
"content": "Zm9vYmFyego",
"timestamp": 1234
}
]
}