mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 03:36:47 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58ad647d29 | ||
|
|
099073356c | ||
|
|
37038c4a63 | ||
|
|
ffa98e5b34 | ||
|
|
6013d00654 | ||
|
|
c03d63acb8 | ||
|
|
c6689ca07a | ||
|
|
1d0e2d29a7 | ||
|
|
d83d826236 | ||
|
|
2efe687b4b |
No files matched your search
@@ -185,6 +185,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.TlsCertificateExpirationUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
|
||||
@@ -365,6 +366,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.forEach(connectorFactory -> {
|
||||
if (connectorFactory instanceof HttpsConnectorFactory h) {
|
||||
h.setKeyStorePassword(config.getTlsKeyStoreConfiguration().password().value());
|
||||
|
||||
TlsCertificateExpirationUtil.configureMetrics(h.getKeyStorePath(), h.getKeyStorePassword(), h.getKeyStoreType(), h.getKeyStoreProvider());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+30
-26
@@ -43,12 +43,12 @@ import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
@@ -93,8 +93,8 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "200", description = "The phone number associated with the authenticated account was changed successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
|
||||
@ApiResponse(responseCode = "409", description = "Mismatched number of devices or device ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
|
||||
@ApiResponse(responseCode = "410", description = "Mismatched registration ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = StaleDevices.class)))
|
||||
@ApiResponse(responseCode = "409", description = "Mismatched number of devices or device ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "410", description = "Mismatched registration ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "423", content = @Content(schema = @Schema(implementation = RegistrationLockFailure.class)))
|
||||
@@ -150,16 +150,18 @@ public class AccountControllerV2 {
|
||||
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
|
||||
.build());
|
||||
} else {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
|
||||
e.getMismatchedDevices().extraDeviceIds()))
|
||||
.build());
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException(e);
|
||||
} catch (MessageTooLargeException e) {
|
||||
@@ -178,9 +180,9 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "403", description = "This endpoint can only be invoked from the account's primary device.")
|
||||
@ApiResponse(responseCode = "422", description = "The request body failed validation.")
|
||||
@ApiResponse(responseCode = "409", description = "The set of devices specified in the request does not match the set of devices active on the account.",
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "410", description = "The registration IDs provided for some devices do not match those stored on the server.",
|
||||
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
|
||||
content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
|
||||
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
|
||||
@Mutable @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@@ -207,16 +209,18 @@ public class AccountControllerV2 {
|
||||
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
|
||||
.build());
|
||||
} else {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
|
||||
e.getMismatchedDevices().extraDeviceIds()))
|
||||
.build());
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException(e);
|
||||
} catch (MessageTooLargeException e) {
|
||||
|
||||
+172
-299
@@ -10,7 +10,6 @@ import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.micrometer.core.instrument.Timer.Sample;
|
||||
@@ -44,14 +43,12 @@ import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.Response.Status;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -62,7 +59,6 @@ import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.protocol.util.Pair;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
|
||||
@@ -81,13 +77,13 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope.Type;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
|
||||
import org.whispersystems.textsecuregcm.entities.SendMessageResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.SpamReport;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -113,7 +109,6 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -155,31 +150,25 @@ public class MessageController {
|
||||
|
||||
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
|
||||
|
||||
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
|
||||
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
|
||||
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
|
||||
|
||||
private static final String SEND_MESSAGE_LATENCY_TIMER_NAME = MetricsUtil.name(MessageController.class, "sendMessageLatency");
|
||||
private static final Timer INDIVIDUAL_MESSAGE_LATENCY_TIMER;
|
||||
private static final Timer MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER;
|
||||
|
||||
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
private static final String SENDER_TYPE_TAG_NAME = "senderType";
|
||||
private static final String AUTH_TYPE_TAG_NAME = "authType";
|
||||
private static final String SENDER_COUNTRY_TAG_NAME = "senderCountry";
|
||||
private static final String RATE_LIMIT_REASON_TAG_NAME = "rateLimitReason";
|
||||
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
|
||||
private static final String ENDPOINT_TYPE_TAG_NAME = "endpoint";
|
||||
static {
|
||||
final String timerName = MetricsUtil.name(MessageController.class, "sendMessageLatency");
|
||||
final String multiRecipientTagName = "multiRecipient";
|
||||
|
||||
private static final String SENDER_TYPE_IDENTIFIED = "identified";
|
||||
private static final String SENDER_TYPE_UNIDENTIFIED = "unidentified";
|
||||
private static final String SENDER_TYPE_SELF = "self";
|
||||
INDIVIDUAL_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
|
||||
.tags(multiRecipientTagName, "false")
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final String AUTH_TYPE_IDENTIFIED = "identified";
|
||||
private static final String AUTH_TYPE_ACCESS_KEY = "accessKey";
|
||||
private static final String AUTH_TYPE_GROUP_SEND_TOKEN = "groupSendToken";
|
||||
private static final String AUTH_TYPE_STORY = "story";
|
||||
|
||||
private static final String ENDPOINT_TYPE_SINGLE = "single";
|
||||
private static final String ENDPOINT_TYPE_MULTI = "multi";
|
||||
MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
|
||||
.tags(multiRecipientTagName, "true")
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry);
|
||||
}
|
||||
|
||||
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
|
||||
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
@@ -245,10 +234,10 @@ public class MessageController {
|
||||
description="The message is not a story and some the recipient service ID does not correspond to a registered Signal user")
|
||||
@ApiResponse(
|
||||
responseCode = "409", description = "Incorrect set of devices supplied for recipient",
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
|
||||
@ApiResponse(
|
||||
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
|
||||
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
|
||||
content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
|
||||
@ApiResponse(
|
||||
responseCode="428",
|
||||
description="The sender should complete a challenge before proceeding")
|
||||
@@ -286,13 +275,11 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
final String senderType = source.map(
|
||||
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
|
||||
.orElse(SENDER_TYPE_UNIDENTIFIED);
|
||||
|
||||
final Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
final boolean isSyncMessage = senderType.equals(SENDER_TYPE_SELF);
|
||||
final boolean isSyncMessage =
|
||||
source.map(s -> s.getAccount().isIdentifiedBy(destinationIdentifier)).orElse(false);
|
||||
|
||||
if (isSyncMessage && destinationIdentifier.identityType() == IdentityType.PNI) {
|
||||
throw new WebApplicationException(Status.FORBIDDEN);
|
||||
@@ -318,7 +305,7 @@ public class MessageController {
|
||||
}
|
||||
|
||||
final SpamCheckResult<Response> spamCheckResult =
|
||||
spamChecker.checkForIndividualRecipientSpamHttp(messageType, context, source, maybeDestination, Optional.of(destinationIdentifier));
|
||||
spamChecker.checkForIndividualRecipientSpamHttp(messageType, context, source, maybeDestination, destinationIdentifier);
|
||||
|
||||
if (spamCheckResult.response().isPresent()) {
|
||||
return spamCheckResult.response().get();
|
||||
@@ -326,21 +313,10 @@ public class MessageController {
|
||||
|
||||
final Optional<byte[]> reportSpamToken = spamCheckResult.token();
|
||||
|
||||
int totalContentLength = 0;
|
||||
|
||||
for (final IncomingMessage message : messages.messages()) {
|
||||
final int contentLength = message.content().length;
|
||||
|
||||
try {
|
||||
MessageSender.validateContentLength(contentLength, false, isSyncMessage, isStory, userAgent);
|
||||
} catch (final MessageTooLargeException e) {
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
totalContentLength += contentLength;
|
||||
}
|
||||
|
||||
try {
|
||||
final int totalContentLength =
|
||||
messages.messages().stream().mapToInt(message -> message.content().length).sum();
|
||||
|
||||
rateLimiters.getInboundMessageBytes().validate(destinationIdentifier.uuid(), totalContentLength);
|
||||
} catch (final RateLimitExceededException e) {
|
||||
messageByteLimitEstimator.add(destinationIdentifier.uuid().toString());
|
||||
@@ -374,21 +350,13 @@ public class MessageController {
|
||||
final Account destination = maybeDestination.orElseThrow();
|
||||
|
||||
if (source.isPresent() && !isSyncMessage) {
|
||||
checkMessageRateLimit(source.get(), destination, userAgent);
|
||||
rateLimiters.getMessagesLimiter().validate(source.get().getAccount().getUuid(), destination.getUuid());
|
||||
}
|
||||
|
||||
if (isStory) {
|
||||
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
|
||||
}
|
||||
|
||||
final Set<Byte> excludedDeviceIds;
|
||||
|
||||
if (isSyncMessage) {
|
||||
excludedDeviceIds = Set.of(source.get().getAuthenticatedDevice().getId());
|
||||
} else {
|
||||
excludedDeviceIds = Collections.emptySet();
|
||||
}
|
||||
|
||||
final Map<Byte, Envelope> messagesByDeviceId = messages.messages().stream()
|
||||
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> {
|
||||
try {
|
||||
@@ -407,55 +375,30 @@ public class MessageController {
|
||||
}
|
||||
}));
|
||||
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(destination,
|
||||
messagesByDeviceId.keySet(),
|
||||
excludedDeviceIds);
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId = messages.messages().stream()
|
||||
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, IncomingMessage::destinationRegistrationId));
|
||||
|
||||
DestinationDeviceValidator.validateRegistrationIds(destination,
|
||||
messages.messages(),
|
||||
IncomingMessage::destinationDeviceId,
|
||||
IncomingMessage::destinationRegistrationId,
|
||||
destination.getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
|
||||
|
||||
final String authType;
|
||||
if (SENDER_TYPE_IDENTIFIED.equals(senderType)) {
|
||||
authType = AUTH_TYPE_IDENTIFIED;
|
||||
} else if (isStory) {
|
||||
authType = AUTH_TYPE_STORY;
|
||||
} else if (groupSendToken != null) {
|
||||
authType = AUTH_TYPE_GROUP_SEND_TOKEN;
|
||||
} else {
|
||||
authType = AUTH_TYPE_ACCESS_KEY;
|
||||
}
|
||||
|
||||
messageSender.sendMessages(destination, messagesByDeviceId);
|
||||
|
||||
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, List.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_SINGLE),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(messages.online())),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, senderType),
|
||||
Tag.of(AUTH_TYPE_TAG_NAME, authType),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name())))
|
||||
.increment(messagesByDeviceId.size());
|
||||
messageSender.sendMessages(destination, destinationIdentifier, messagesByDeviceId, registrationIdsByDeviceId, userAgent);
|
||||
|
||||
return Response.ok(new SendMessageResponse(needsSync)).build();
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (final StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
|
||||
.build());
|
||||
} else {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
|
||||
e.getMismatchedDevices().extraDeviceIds()))
|
||||
.build());
|
||||
}
|
||||
} catch (final MessageTooLargeException e) {
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
} finally {
|
||||
sample.stop(Timer.builder(SEND_MESSAGE_LATENCY_TIMER_NAME)
|
||||
.tags(SENDER_TYPE_TAG_NAME, senderType)
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry));
|
||||
sample.stop(INDIVIDUAL_MESSAGE_LATENCY_TIMER);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,15 +465,6 @@ public class MessageController {
|
||||
throw new BadRequestException("Recipient list is empty");
|
||||
}
|
||||
|
||||
// Verify that the message isn't too large before performing more expensive validations
|
||||
multiRecipientMessage.getRecipients().values().forEach(recipient -> {
|
||||
try {
|
||||
MessageSender.validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient), true, false, isStory, userAgent);
|
||||
} catch (final MessageTooLargeException e) {
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
});
|
||||
|
||||
// Check that the request is well-formed and doesn't contain repeated entries for the same device for the same
|
||||
// recipient
|
||||
{
|
||||
@@ -549,188 +483,144 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
final SpamCheckResult<Response> spamCheckResult = spamChecker.checkForMultiRecipientSpamHttp(
|
||||
isStory ? MessageType.MULTI_RECIPIENT_STORY : MessageType.MULTI_RECIPIENT_SEALED_SENDER,
|
||||
context);
|
||||
|
||||
if (spamCheckResult.response().isPresent()) {
|
||||
return spamCheckResult.response().get();
|
||||
}
|
||||
|
||||
if (groupSendToken == null && accessKeys == null && !isStory) {
|
||||
throw new NotAuthorizedException("A group send endorsement token or unidentified access key is required for non-story messages");
|
||||
}
|
||||
if (groupSendToken != null) {
|
||||
if (accessKeys != null) {
|
||||
throw new BadRequestException("Only one of group send endorsement token and unidentified access key may be provided");
|
||||
} else if (isStory) {
|
||||
throw new BadRequestException("Stories should not provide a group send endorsement token");
|
||||
}
|
||||
}
|
||||
|
||||
if (groupSendToken != null) {
|
||||
// Group send endorsements are checked before we even attempt to resolve any accounts, since
|
||||
// the lists of service IDs in the envelope are all that we need to check against
|
||||
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendToken);
|
||||
}
|
||||
|
||||
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
|
||||
// message. Attempt to resolve the destination service identifiers to Signal accounts.
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
|
||||
Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
|
||||
.flatMap(serviceIdAndRecipient -> {
|
||||
final ServiceIdentifier serviceIdentifier =
|
||||
ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.switchIfEmpty(isStory || groupSendToken != null ? Mono.empty() : Mono.error(NotFoundException::new))
|
||||
.map(account -> Tuples.of(serviceIdAndRecipient.getValue(), account));
|
||||
}, MAX_FETCH_ACCOUNT_CONCURRENCY)
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.blockOptional()
|
||||
.orElse(Collections.emptyMap());
|
||||
|
||||
// Access keys are checked against the UAK in the resolved accounts, so we have to check after resolving accounts above.
|
||||
// Group send endorsements are checked earlier; for stories, we don't check permissions at all because only clients check them
|
||||
if (groupSendToken == null && !isStory) {
|
||||
checkAccessKeys(accessKeys, multiRecipientMessage, resolvedRecipients);
|
||||
}
|
||||
|
||||
// We might filter out all the recipients of a story (if none exist).
|
||||
// In this case there is no error so we should just return 200 now.
|
||||
if (isStory) {
|
||||
if (resolvedRecipients.isEmpty()) {
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(List.of())).build();
|
||||
}
|
||||
|
||||
try {
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(account -> account.getIdentifier(IdentityType.ACI))
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toList()
|
||||
.toArray(EMPTY_FUTURE_ARRAY))
|
||||
.join();
|
||||
} catch (final Exception e) {
|
||||
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException rateLimitExceededException) {
|
||||
throw rateLimitExceededException;
|
||||
} else {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final Collection<AccountMismatchedDevices> accountMismatchedDevices = new ArrayList<>();
|
||||
final Collection<AccountStaleDevices> accountStaleDevices = new ArrayList<>();
|
||||
|
||||
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
|
||||
if (!resolvedRecipients.containsKey(recipient)) {
|
||||
// When sending stories, we might not be able to resolve all recipients to existing accounts. That's okay! We
|
||||
// can just skip them.
|
||||
return;
|
||||
}
|
||||
|
||||
final Account account = resolvedRecipients.get(recipient);
|
||||
|
||||
try {
|
||||
final Map<Byte, Short> deviceIdsToRegistrationIds = recipient.getDevicesAndRegistrationIds()
|
||||
.collect(Collectors.toMap(Pair<Byte, Short>::first, Pair<Byte, Short>::second));
|
||||
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(account, deviceIdsToRegistrationIds.keySet(),
|
||||
Collections.emptySet());
|
||||
|
||||
DestinationDeviceValidator.validateRegistrationIds(
|
||||
account,
|
||||
deviceIdsToRegistrationIds.entrySet(),
|
||||
Map.Entry<Byte, Short>::getKey,
|
||||
e -> Integer.valueOf(e.getValue()),
|
||||
serviceId instanceof ServiceId.Pni);
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
accountMismatchedDevices.add(
|
||||
new AccountMismatchedDevices(
|
||||
ServiceIdentifier.fromLibsignal(serviceId),
|
||||
new MismatchedDevices(e.getMissingDevices(), e.getExtraDevices())));
|
||||
} catch (final StaleDevicesException e) {
|
||||
accountStaleDevices.add(
|
||||
new AccountStaleDevices(ServiceIdentifier.fromLibsignal(serviceId), new StaleDevices(e.getStaleDevices())));
|
||||
}
|
||||
});
|
||||
|
||||
if (!accountMismatchedDevices.isEmpty()) {
|
||||
return Response
|
||||
.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(accountMismatchedDevices)
|
||||
.build();
|
||||
}
|
||||
if (!accountStaleDevices.isEmpty()) {
|
||||
return Response
|
||||
.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(accountStaleDevices)
|
||||
.build();
|
||||
}
|
||||
|
||||
final String authType;
|
||||
if (isStory) {
|
||||
authType = AUTH_TYPE_STORY;
|
||||
} else if (groupSendToken != null) {
|
||||
authType = AUTH_TYPE_GROUP_SEND_TOKEN;
|
||||
} else {
|
||||
authType = AUTH_TYPE_ACCESS_KEY;
|
||||
}
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
if (!resolvedRecipients.isEmpty()) {
|
||||
messageSender.sendMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, timestamp, isStory, online, isUrgent).get();
|
||||
final SpamCheckResult<Response> spamCheckResult = spamChecker.checkForMultiRecipientSpamHttp(
|
||||
isStory ? MessageType.MULTI_RECIPIENT_STORY : MessageType.MULTI_RECIPIENT_SEALED_SENDER,
|
||||
context);
|
||||
|
||||
if (spamCheckResult.response().isPresent()) {
|
||||
return spamCheckResult.response().get();
|
||||
}
|
||||
|
||||
final List<ServiceIdentifier> unresolvedRecipientServiceIds;
|
||||
if (AUTH_TYPE_GROUP_SEND_TOKEN.equals(authType)) {
|
||||
unresolvedRecipientServiceIds = multiRecipientMessage.getRecipients().entrySet().stream()
|
||||
.filter(entry -> !resolvedRecipients.containsKey(entry.getValue()))
|
||||
.map(entry -> ServiceIdentifier.fromLibsignal(entry.getKey()))
|
||||
.toList();
|
||||
} else {
|
||||
unresolvedRecipientServiceIds = List.of();
|
||||
if (groupSendToken == null && accessKeys == null && !isStory) {
|
||||
throw new NotAuthorizedException("A group send endorsement token or unidentified access key is required for non-story messages");
|
||||
}
|
||||
if (groupSendToken != null) {
|
||||
if (accessKeys != null) {
|
||||
throw new BadRequestException("Only one of group send endorsement token and unidentified access key may be provided");
|
||||
} else if (isStory) {
|
||||
throw new BadRequestException("Stories should not provide a group send endorsement token");
|
||||
}
|
||||
}
|
||||
|
||||
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
|
||||
if (!resolvedRecipients.containsKey(recipient)) {
|
||||
// We skipped sending to this recipient because we couldn't resolve the recipient to an
|
||||
// existing account; don't increment the counter for this recipient. If the client was
|
||||
// using a GSE, track the missing recipients to include in the response.
|
||||
return;
|
||||
if (groupSendToken != null) {
|
||||
// Group send endorsements are checked before we even attempt to resolve any accounts, since
|
||||
// the lists of service IDs in the envelope are all that we need to check against
|
||||
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendToken);
|
||||
}
|
||||
|
||||
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
|
||||
// message. Attempt to resolve the destination service identifiers to Signal accounts.
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
|
||||
Flux.fromIterable(multiRecipientMessage.getRecipients().entrySet())
|
||||
.flatMap(serviceIdAndRecipient -> {
|
||||
final ServiceIdentifier serviceIdentifier =
|
||||
ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.switchIfEmpty(isStory || groupSendToken != null ? Mono.empty() : Mono.error(NotFoundException::new))
|
||||
.map(account -> Tuples.of(serviceIdAndRecipient.getValue(), account));
|
||||
}, MAX_FETCH_ACCOUNT_CONCURRENCY)
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.blockOptional()
|
||||
.orElse(Collections.emptyMap());
|
||||
|
||||
// Access keys are checked against the UAK in the resolved accounts, so we have to check after resolving accounts above.
|
||||
// Group send endorsements are checked earlier; for stories, we don't check permissions at all because only clients check them
|
||||
if (groupSendToken == null && !isStory) {
|
||||
checkAccessKeys(accessKeys, multiRecipientMessage, resolvedRecipients);
|
||||
}
|
||||
|
||||
// We might filter out all the recipients of a story (if none exist).
|
||||
// In this case there is no error so we should just return 200 now.
|
||||
if (isStory) {
|
||||
if (resolvedRecipients.isEmpty()) {
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(List.of())).build();
|
||||
}
|
||||
|
||||
final String identityType = switch (serviceId) {
|
||||
case ServiceId.Aci ignored -> "ACI";
|
||||
case ServiceId.Pni ignored -> "PNI";
|
||||
default -> "unknown";
|
||||
};
|
||||
try {
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(account -> account.getIdentifier(IdentityType.ACI))
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toList()
|
||||
.toArray(EMPTY_FUTURE_ARRAY))
|
||||
.join();
|
||||
} catch (final Exception e) {
|
||||
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException rateLimitExceededException) {
|
||||
throw rateLimitExceededException;
|
||||
} else {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(ENDPOINT_TYPE_TAG_NAME, ENDPOINT_TYPE_MULTI),
|
||||
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
|
||||
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
|
||||
Tag.of(AUTH_TYPE_TAG_NAME, authType),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, identityType)))
|
||||
.increment(recipient.getDevices().length);
|
||||
});
|
||||
try {
|
||||
if (!resolvedRecipients.isEmpty()) {
|
||||
messageSender.sendMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, timestamp, isStory, online, isUrgent, userAgent).get();
|
||||
}
|
||||
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(unresolvedRecipientServiceIds)).build();
|
||||
} catch (InterruptedException e) {
|
||||
logger.error("interrupted while delivering multi-recipient messages", e);
|
||||
throw new InternalServerErrorException("interrupted during delivery");
|
||||
} catch (CancellationException e) {
|
||||
logger.error("cancelled while delivering multi-recipient messages", e);
|
||||
throw new InternalServerErrorException("delivery cancelled");
|
||||
} catch (ExecutionException e) {
|
||||
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
|
||||
throw new InternalServerErrorException("failure during delivery");
|
||||
final List<ServiceIdentifier> unresolvedRecipientServiceIds;
|
||||
if (groupSendToken != null) {
|
||||
unresolvedRecipientServiceIds = multiRecipientMessage.getRecipients().entrySet().stream()
|
||||
.filter(entry -> !resolvedRecipients.containsKey(entry.getValue()))
|
||||
.map(entry -> ServiceIdentifier.fromLibsignal(entry.getKey()))
|
||||
.toList();
|
||||
} else {
|
||||
unresolvedRecipientServiceIds = List.of();
|
||||
}
|
||||
|
||||
return Response.ok(new SendMultiRecipientMessageResponse(unresolvedRecipientServiceIds)).build();
|
||||
} catch (InterruptedException e) {
|
||||
logger.error("interrupted while delivering multi-recipient messages", e);
|
||||
throw new InternalServerErrorException("interrupted during delivery");
|
||||
} catch (CancellationException e) {
|
||||
logger.error("cancelled while delivering multi-recipient messages", e);
|
||||
throw new InternalServerErrorException("delivery cancelled");
|
||||
} catch (ExecutionException e) {
|
||||
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
|
||||
throw new InternalServerErrorException("failure during delivery");
|
||||
} catch (MultiRecipientMismatchedDevicesException e) {
|
||||
final List<AccountMismatchedDevices> accountMismatchedDevices =
|
||||
e.getMismatchedDevicesByServiceIdentifier().entrySet().stream()
|
||||
.filter(entry -> !entry.getValue().missingDeviceIds().isEmpty() || !entry.getValue().extraDeviceIds().isEmpty())
|
||||
.map(entry -> new AccountMismatchedDevices(entry.getKey(),
|
||||
new MismatchedDevicesResponse(entry.getValue().missingDeviceIds(), entry.getValue().extraDeviceIds())))
|
||||
.toList();
|
||||
|
||||
if (!accountMismatchedDevices.isEmpty()) {
|
||||
return Response
|
||||
.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(accountMismatchedDevices)
|
||||
.build();
|
||||
}
|
||||
|
||||
final List<AccountStaleDevices> accountStaleDevices =
|
||||
e.getMismatchedDevicesByServiceIdentifier().entrySet().stream()
|
||||
.filter(entry -> !entry.getValue().staleDeviceIds().isEmpty())
|
||||
.map(entry -> new AccountStaleDevices(entry.getKey(),
|
||||
new StaleDevicesResponse(entry.getValue().staleDeviceIds())))
|
||||
.toList();
|
||||
|
||||
if (!accountStaleDevices.isEmpty()) {
|
||||
return Response
|
||||
.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(accountStaleDevices)
|
||||
.build();
|
||||
}
|
||||
|
||||
throw new RuntimeException(e);
|
||||
} catch (final MessageTooLargeException e) {
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
} finally {
|
||||
sample.stop(MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -921,21 +811,4 @@ public class MessageController {
|
||||
return Response.status(Status.ACCEPTED)
|
||||
.build();
|
||||
}
|
||||
|
||||
private void checkMessageRateLimit(AuthenticatedDevice source, Account destination, String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
final String senderCountryCode = Util.getCountryCode(source.getAccount().getNumber());
|
||||
|
||||
try {
|
||||
rateLimiters.getMessagesLimiter().validate(source.getAccount().getUuid(), destination.getUuid());
|
||||
} catch (final RateLimitExceededException e) {
|
||||
Metrics.counter(RATE_LIMITED_MESSAGE_COUNTER_NAME,
|
||||
Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(SENDER_COUNTRY_TAG_NAME, senderCountryCode),
|
||||
Tag.of(RATE_LIMIT_REASON_TAG_NAME, "singleDestinationRate"))).increment();
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public record MismatchedDevices(Set<Byte> missingDeviceIds, Set<Byte> extraDeviceIds, Set<Byte> staleDeviceIds) {
|
||||
}
|
||||
+5
-13
@@ -5,23 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class MismatchedDevicesException extends Exception {
|
||||
|
||||
private final List<Byte> missingDevices;
|
||||
private final List<Byte> extraDevices;
|
||||
private final MismatchedDevices mismatchedDevices;
|
||||
|
||||
public MismatchedDevicesException(List<Byte> missingDevices, List<Byte> extraDevices) {
|
||||
this.missingDevices = missingDevices;
|
||||
this.extraDevices = extraDevices;
|
||||
public MismatchedDevicesException(final MismatchedDevices mismatchedDevices) {
|
||||
this.mismatchedDevices = mismatchedDevices;
|
||||
}
|
||||
|
||||
public List<Byte> getMissingDevices() {
|
||||
return missingDevices;
|
||||
}
|
||||
|
||||
public List<Byte> getExtraDevices() {
|
||||
return extraDevices;
|
||||
public MismatchedDevices getMismatchedDevices() {
|
||||
return mismatchedDevices;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import java.util.Map;
|
||||
|
||||
public class MultiRecipientMismatchedDevicesException extends Exception {
|
||||
|
||||
private final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier;
|
||||
|
||||
public MultiRecipientMismatchedDevicesException(
|
||||
final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier) {
|
||||
|
||||
this.mismatchedDevicesByServiceIdentifier = mismatchedDevicesByServiceIdentifier;
|
||||
}
|
||||
|
||||
public Map<ServiceIdentifier, MismatchedDevices> getMismatchedDevicesByServiceIdentifier() {
|
||||
return mismatchedDevicesByServiceIdentifier;
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class StaleDevicesException extends Exception {
|
||||
|
||||
private final List<Byte> staleDevices;
|
||||
|
||||
public StaleDevicesException(List<Byte> staleDevices) {
|
||||
this.staleDevices = staleDevices;
|
||||
}
|
||||
|
||||
public List<Byte> getStaleDevices() {
|
||||
return staleDevices;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -14,5 +14,5 @@ public record AccountMismatchedDevices(@JsonSerialize(using = ServiceIdentifierA
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
MismatchedDevices devices) {
|
||||
MismatchedDevicesResponse devices) {
|
||||
}
|
||||
+1
-1
@@ -14,5 +14,5 @@ public record AccountStaleDevices(@JsonSerialize(using = ServiceIdentifierAdapte
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
StaleDevices devices) {
|
||||
StaleDevicesResponse devices) {
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record MismatchedDevices(@JsonProperty
|
||||
@Schema(description = "Devices present on the account but absent in the request")
|
||||
List<Byte> missingDevices,
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "Devices absent on the request but present in the account")
|
||||
List<Byte> extraDevices) {
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public record MismatchedDevicesResponse(@JsonProperty
|
||||
@Schema(description = "Devices present on the account but absent in the request")
|
||||
Set<Byte> missingDevices,
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "Devices absent on the request but present in the account")
|
||||
Set<Byte> extraDevices) {
|
||||
}
|
||||
+4
-4
@@ -8,9 +8,9 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public record StaleDevices(@JsonProperty
|
||||
@Schema(description = "Devices that are no longer active")
|
||||
List<Byte> staleDevices) {
|
||||
public record StaleDevicesResponse(@JsonProperty
|
||||
@Schema(description = "Devices that are no longer active")
|
||||
Set<Byte> staleDevices) {
|
||||
}
|
||||
+1
-1
@@ -18,7 +18,7 @@ import org.whispersystems.textsecuregcm.util.HttpServletRequestUtil;
|
||||
|
||||
/**
|
||||
* Sets a {@link HttpServletRequest} attribute (that will also be available as a
|
||||
* {@link javax.ws.rs.container.ContainerRequestContext} property) with the remote address of the connection, using
|
||||
* {@link jakarta.ws.rs.container.ContainerRequestContext} property) with the remote address of the connection, using
|
||||
* {@link HttpServletRequest#getRemoteAddr()}.
|
||||
*/
|
||||
public class RemoteAddressFilter implements Filter {
|
||||
|
||||
+12
-22
@@ -15,12 +15,14 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import static io.lettuce.core.ExpireArgs.Builder.nx;
|
||||
|
||||
/**
|
||||
* Estimate the number of unique items seen over a configurable period and update a metric
|
||||
*/
|
||||
public class CardinalityEstimator {
|
||||
|
||||
private volatile double uniqueElementCount;
|
||||
private volatile long uniqueElementCount;
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
private final String hllName;
|
||||
private final Duration period;
|
||||
@@ -36,41 +38,29 @@ public class CardinalityEstimator {
|
||||
obj -> obj.uniqueElementCount);
|
||||
}
|
||||
|
||||
public void add(String element) {
|
||||
public void add(final String element) {
|
||||
addAsync(element).toCompletableFuture().join();
|
||||
}
|
||||
|
||||
public CompletionStage<Void> addAsync(String element) {
|
||||
public CompletionStage<Void> addAsync(final String element) {
|
||||
return redisCluster.withCluster(connection -> connection.async()
|
||||
.pfadd(hllName, element)
|
||||
.thenCompose(modCount -> {
|
||||
if (modCount == 0) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
// The hll hasn't changed - return our current view of cardinality
|
||||
return CompletableFuture.completedFuture(uniqueElementCount);
|
||||
}
|
||||
|
||||
// The hll changed - update our local view of the cardinality, and
|
||||
// initialize the TTL if required
|
||||
return connection.async()
|
||||
.pfcount(hllName)
|
||||
.thenCompose(count -> {
|
||||
uniqueElementCount = count;
|
||||
// check if this is a new hll with no TTL set
|
||||
return connection.async().ttl(hllName).thenApply(ttl -> ttl == -1);
|
||||
});
|
||||
return connection.async().pfcount(hllName);
|
||||
})
|
||||
.thenCompose(isNewHll -> {
|
||||
if (!isNewHll) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
// If this is a new hll, we need to set the TTL. This could be
|
||||
// a single atomic op in redis 7.x with EXPIRE NX
|
||||
return connection.async().expire(hllName, period).thenRun(Util.NOOP);
|
||||
.thenCompose(newUniqueElementCount -> {
|
||||
uniqueElementCount = newUniqueElementCount;
|
||||
return connection.async().expire(hllName, period, nx()).thenRun(Util.NOOP);
|
||||
}));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
long estimate() {
|
||||
return (long) this.uniqueElementCount;
|
||||
return this.uniqueElementCount;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -34,7 +34,7 @@ import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
|
||||
|
||||
/**
|
||||
* Gathers and reports HTTP request metrics at the Jetty container level, which sits above Jersey. In order to get
|
||||
* templated Jersey request paths, it implements {@link javax.ws.rs.container.ContainerResponseFilter}, in order to give
|
||||
* templated Jersey request paths, it implements {@link jakarta.ws.rs.container.ContainerResponseFilter}, in order to give
|
||||
* itself access to the template. It is limited to {@link TrafficSource#HTTP} requests.
|
||||
* <p>
|
||||
* It implements {@link LifeCycle.Listener} without overriding methods, so that it can be an event listener that
|
||||
|
||||
@@ -83,7 +83,7 @@ public class MetricsUtil {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static MeterRegistry.Config configureMeterFilters(MeterRegistry.Config config,
|
||||
static void configureMeterFilters(MeterRegistry.Config config,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
|
||||
.percentiles(.75, .95, .99, .999)
|
||||
@@ -91,8 +91,7 @@ public class MetricsUtil {
|
||||
|
||||
final String awsSdkMetricNamePrefix = MetricsUtil.name(MicrometerAwsSdkMetricPublisher.class);
|
||||
|
||||
return config
|
||||
.meterFilter(new MeterFilter() {
|
||||
config.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Gauge;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateParsingException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.eclipse.jetty.util.resource.Resource;
|
||||
import org.eclipse.jetty.util.security.CertificateUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class TlsCertificateExpirationUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TlsCertificateExpirationUtil.class);
|
||||
|
||||
private static final String CERTIFICATE_EXPIRATION_GAUGE_NAME = name(TlsCertificateExpirationUtil.class,
|
||||
"secondsUntilExpiration");
|
||||
|
||||
public static void configureMetrics(final String keyStorePath, final String keyStorePassword, final String keyStoreType, final String keyStoreProvider) {
|
||||
|
||||
final KeyStore keyStore;
|
||||
try {
|
||||
keyStore = CertificateUtils.getKeyStore(Resource.newResource(keyStorePath), keyStoreType, keyStoreProvider,
|
||||
keyStorePassword);
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to load keystore " + keyStorePath, e);
|
||||
}
|
||||
|
||||
getIdentifiersAndExpirations(keyStore, keyStorePassword)
|
||||
.forEach((id, expiration) ->
|
||||
Gauge.builder(CERTIFICATE_EXPIRATION_GAUGE_NAME, expiration,
|
||||
then -> Duration.between(Instant.now(), then).toSeconds())
|
||||
.tags("id", id)
|
||||
.strongReference(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Map<String, Instant> getIdentifiersAndExpirations(final KeyStore keyStore, final String password) {
|
||||
|
||||
final Map<String, Instant> identifiersAndExpirations = new HashMap<>();
|
||||
|
||||
try {
|
||||
for (final Iterator<String> it = keyStore.aliases().asIterator(); it.hasNext(); ) {
|
||||
|
||||
final Certificate certificate = keyStore.getCertificate(it.next());
|
||||
if (certificate instanceof X509Certificate x509Certificate) {
|
||||
|
||||
final String name = getName(x509Certificate);
|
||||
final String algorithm = x509Certificate.getPublicKey().getAlgorithm();
|
||||
final Instant notAfter = Instant.ofEpochMilli(x509Certificate.getNotAfter().getTime());
|
||||
|
||||
final String identifier = name + ":" + algorithm;
|
||||
identifiersAndExpirations.put(identifier, notAfter);
|
||||
|
||||
} else {
|
||||
logger.warn("Unexpected certificate type: {}", certificate.getClass().getName());
|
||||
}
|
||||
}
|
||||
} catch (final KeyStoreException e) {
|
||||
// This should never happen - this exception is thrown if the keystore is not initialized, which
|
||||
// CertificateUtils#getKeyStore does.
|
||||
throw new RuntimeException("Failed to read keystore", e);
|
||||
} catch (final CertificateParsingException e) {
|
||||
throw new IllegalArgumentException("Failed to parse certificate", e);
|
||||
}
|
||||
|
||||
return identifiersAndExpirations;
|
||||
}
|
||||
|
||||
private static String getName(X509Certificate x509Certificate) throws CertificateParsingException {
|
||||
return Optional.ofNullable(x509Certificate.getSubjectAlternativeNames())
|
||||
.flatMap(sans -> sans.stream().findFirst())
|
||||
.map(altNames -> {
|
||||
|
||||
// each list should be a tuple of
|
||||
// alternative name type ID (integer), name
|
||||
if (altNames.size() != 2) {
|
||||
logger.warn("Unexpected subject alternative name: {}", altNames);
|
||||
return null;
|
||||
}
|
||||
|
||||
return switch ((Integer) altNames.getFirst()) {
|
||||
case 2, 7 -> // dns, ip
|
||||
altNames.getLast().toString();
|
||||
default -> null;
|
||||
};
|
||||
|
||||
})
|
||||
.orElse("unknown");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,6 +8,8 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
@@ -23,11 +25,18 @@ public class UserAgentTagUtil {
|
||||
public static final String VERSION_TAG = "clientVersion";
|
||||
public static final String LIBSIGNAL_TAG = "libsignal";
|
||||
|
||||
public static final String SERVER_UA =
|
||||
String.format("Signal-Server/%s (%s)", WhisperServerVersion.getServerVersion(), UUID.randomUUID());
|
||||
|
||||
private UserAgentTagUtil() {
|
||||
}
|
||||
|
||||
public static Tag getPlatformTag(final String userAgentString) {
|
||||
|
||||
if (SERVER_UA.equals(userAgentString)) {
|
||||
return Tag.of(PLATFORM_TAG, "server");
|
||||
}
|
||||
|
||||
UserAgent userAgent = null;
|
||||
|
||||
try {
|
||||
|
||||
@@ -11,19 +11,31 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* A MessageSender sends Signal messages to destination devices. Messages may be "normal" user-to-user messages,
|
||||
@@ -43,20 +55,21 @@ public class MessageSender {
|
||||
|
||||
// Note that these names deliberately reference `MessageController` for metric continuity
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageController.class, "rejectOversizeMessage");
|
||||
private static final String LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageController.class, "largeMessage");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
|
||||
|
||||
private static final String SEND_COUNTER_NAME = name(MessageSender.class, "sendMessage");
|
||||
private static final String CHANNEL_TAG_NAME = "channel";
|
||||
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
private static final String CLIENT_ONLINE_TAG_NAME = "clientOnline";
|
||||
private static final String URGENT_TAG_NAME = "urgent";
|
||||
private static final String STORY_TAG_NAME = "story";
|
||||
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
|
||||
private static final String MULTI_RECIPIENT_TAG_NAME = "multiRecipient";
|
||||
|
||||
@VisibleForTesting
|
||||
public static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
|
||||
private static final long LARGE_MESSAGE_SIZE = DataSize.kibibytes(8).toBytes();
|
||||
|
||||
@VisibleForTesting
|
||||
static final byte NO_EXCLUDED_DEVICE_ID = -1;
|
||||
|
||||
public MessageSender(final MessagesManager messagesManager, final PushNotificationManager pushNotificationManager) {
|
||||
this.messagesManager = messagesManager;
|
||||
@@ -68,29 +81,70 @@ public class MessageSender {
|
||||
* notification token and does not have an active connection to a Signal server, then this method will also send a
|
||||
* push notification to that device to announce the availability of new messages.
|
||||
*
|
||||
* @param account the account to which to send messages
|
||||
* @param destination the account to which to send messages
|
||||
* @param destinationIdentifier the service identifier to which the messages are addressed
|
||||
* @param messagesByDeviceId a map of device IDs to message payloads
|
||||
* @param registrationIdsByDeviceId a map of device IDs to device registration IDs
|
||||
* @param userAgent the User-Agent string for the sender; may be {@code null} if not known
|
||||
*
|
||||
* @throws MismatchedDevicesException if the given bundle of messages did not include a message for all required
|
||||
* devices, contained messages for devices not linked to the destination account, or devices with outdated
|
||||
* registration IDs
|
||||
* @throws MessageTooLargeException if the given message payload is too large
|
||||
*/
|
||||
public void sendMessages(final Account account, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
messagesManager.insert(account.getIdentifier(IdentityType.ACI), messagesByDeviceId)
|
||||
public void sendMessages(final Account destination,
|
||||
final ServiceIdentifier destinationIdentifier,
|
||||
final Map<Byte, Envelope> messagesByDeviceId,
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId,
|
||||
@Nullable final String userAgent) throws MismatchedDevicesException, MessageTooLargeException {
|
||||
|
||||
if (messagesByDeviceId.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!destination.isIdentifiedBy(destinationIdentifier)) {
|
||||
throw new IllegalArgumentException("Destination account not identified by destination service identifier");
|
||||
}
|
||||
|
||||
final Envelope firstMessage = messagesByDeviceId.values().iterator().next();
|
||||
|
||||
final boolean isSyncMessage = StringUtils.isNotBlank(firstMessage.getSourceServiceId()) &&
|
||||
destination.isIdentifiedBy(ServiceIdentifier.valueOf(firstMessage.getSourceServiceId()));
|
||||
|
||||
final boolean isStory = firstMessage.getStory();
|
||||
|
||||
validateIndividualMessageContentLength(messagesByDeviceId.values(), isSyncMessage, isStory, userAgent);
|
||||
|
||||
final Optional<MismatchedDevices> maybeMismatchedDevices = getMismatchedDevices(destination,
|
||||
destinationIdentifier,
|
||||
registrationIdsByDeviceId,
|
||||
isSyncMessage ? (byte) firstMessage.getSourceDevice() : NO_EXCLUDED_DEVICE_ID);
|
||||
|
||||
if (maybeMismatchedDevices.isPresent()) {
|
||||
throw new MismatchedDevicesException(maybeMismatchedDevices.get());
|
||||
}
|
||||
|
||||
messagesManager.insert(destination.getIdentifier(IdentityType.ACI), messagesByDeviceId)
|
||||
.forEach((deviceId, destinationPresent) -> {
|
||||
final Envelope message = messagesByDeviceId.get(deviceId);
|
||||
|
||||
if (!destinationPresent && !message.getEphemeral()) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, deviceId, message.getUrgent());
|
||||
pushNotificationManager.sendNewMessageNotification(destination, deviceId, message.getUrgent());
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME,
|
||||
CHANNEL_TAG_NAME, account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
|
||||
final Tags tags = Tags.of(
|
||||
EPHEMERAL_TAG_NAME, String.valueOf(message.getEphemeral()),
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(destinationPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
|
||||
STORY_TAG_NAME, String.valueOf(message.getStory()),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
|
||||
.increment();
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()),
|
||||
MULTI_RECIPIENT_TAG_NAME, "false")
|
||||
.and(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -98,6 +152,10 @@ public class MessageSender {
|
||||
* Sends messages to a group of recipients. If a destination device has a valid push notification token and does not
|
||||
* have an active connection to a Signal server, then this method will also send a push notification to that device to
|
||||
* announce the availability of new messages.
|
||||
* <p>
|
||||
* This method sends messages to all <em>resolved</em> recipients. In some cases, a caller may not be able to resolve
|
||||
* all recipients to active accounts, but may still choose to send the message. Callers are responsible for rejecting
|
||||
* the message if they require full resolution of all recipients, but some recipients could not be resolved.
|
||||
*
|
||||
* @param multiRecipientMessage the multi-recipient message to send to the given recipients
|
||||
* @param resolvedRecipients a map of recipients to resolved Signal accounts
|
||||
@@ -106,15 +164,48 @@ public class MessageSender {
|
||||
* @param isEphemeral {@code true} if the message should only be delivered to devices with active connections or
|
||||
* {@code false otherwise}
|
||||
* @param isUrgent {@code true} if the message is urgent or {@code false otherwise}
|
||||
* @param userAgent the User-Agent string for the sender; may be {@code null} if not known
|
||||
*
|
||||
* @return a future that completes when all messages have been inserted into delivery queues
|
||||
*
|
||||
* @throws MultiRecipientMismatchedDevicesException if the given multi-recipient message had did not have all required
|
||||
* recipient devices for a recipient account, contained recipients for devices not linked to a destination account, or
|
||||
* recipient devices with outdated registration IDs
|
||||
* @throws MessageTooLargeException if the given message payload is too large
|
||||
*/
|
||||
public CompletableFuture<Void> sendMultiRecipientMessage(final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients,
|
||||
final long clientTimestamp,
|
||||
final boolean isStory,
|
||||
final boolean isEphemeral,
|
||||
final boolean isUrgent) {
|
||||
final boolean isUrgent,
|
||||
@Nullable final String userAgent) throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
|
||||
|
||||
validateMultiRecipientMessageContentLength(multiRecipientMessage, isStory, userAgent);
|
||||
|
||||
final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier = new HashMap<>();
|
||||
|
||||
multiRecipientMessage.getRecipients().forEach((serviceId, recipient) -> {
|
||||
if (!resolvedRecipients.containsKey(recipient)) {
|
||||
// Callers are responsible for rejecting messages if they're missing recipients in a problematic way. If we run
|
||||
// into an unresolved recipient here, just skip it.
|
||||
return;
|
||||
}
|
||||
|
||||
final Account account = resolvedRecipients.get(recipient);
|
||||
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceId);
|
||||
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId = recipient.getDevicesAndRegistrationIds()
|
||||
.collect(Collectors.toMap(Pair::first, pair -> (int) pair.second()));
|
||||
|
||||
getMismatchedDevices(account, serviceIdentifier, registrationIdsByDeviceId, NO_EXCLUDED_DEVICE_ID)
|
||||
.ifPresent(mismatchedDevices ->
|
||||
mismatchedDevicesByServiceIdentifier.put(serviceIdentifier, mismatchedDevices));
|
||||
});
|
||||
|
||||
if (!mismatchedDevicesByServiceIdentifier.isEmpty()) {
|
||||
throw new MultiRecipientMismatchedDevicesException(mismatchedDevicesByServiceIdentifier);
|
||||
}
|
||||
|
||||
return messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp,
|
||||
isStory, isEphemeral, isUrgent)
|
||||
@@ -128,33 +219,22 @@ public class MessageSender {
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME,
|
||||
CHANNEL_TAG_NAME,
|
||||
account.getDevice(deviceId).map(MessageSender::getDeliveryChannelName).orElse("unknown"),
|
||||
final Tags tags = Tags.of(
|
||||
EPHEMERAL_TAG_NAME, String.valueOf(isEphemeral),
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(isUrgent),
|
||||
STORY_TAG_NAME, String.valueOf(isStory),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(true))
|
||||
.increment();
|
||||
SEALED_SENDER_TAG_NAME, "true",
|
||||
MULTI_RECIPIENT_TAG_NAME, "true")
|
||||
.and(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
|
||||
})))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getDeliveryChannelName(final Device device) {
|
||||
if (device.getGcmId() != null) {
|
||||
return "gcm";
|
||||
} else if (device.getApnId() != null) {
|
||||
return "apn";
|
||||
} else if (device.getFetchesMessages()) {
|
||||
return "websocket";
|
||||
} else {
|
||||
return "none";
|
||||
}
|
||||
}
|
||||
|
||||
public static void validateContentLength(final int contentLength,
|
||||
static void validateContentLength(final int contentLength,
|
||||
final boolean isMultiRecipientMessage,
|
||||
final boolean isSyncMessage,
|
||||
final boolean isStory,
|
||||
@@ -181,12 +261,75 @@ public class MessageSender {
|
||||
|
||||
throw new MessageTooLargeException();
|
||||
}
|
||||
}
|
||||
|
||||
if (contentLength > LARGE_MESSAGE_SIZE) {
|
||||
Metrics.counter(
|
||||
LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER_NAME,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage))))
|
||||
.increment();
|
||||
@VisibleForTesting
|
||||
static Optional<MismatchedDevices> getMismatchedDevices(final Account account,
|
||||
final ServiceIdentifier serviceIdentifier,
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId,
|
||||
final byte excludedDeviceId) {
|
||||
|
||||
final Set<Byte> accountDeviceIds = account.getDevices().stream()
|
||||
.map(Device::getId)
|
||||
.filter(deviceId -> deviceId != excludedDeviceId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
final Set<Byte> missingDeviceIds = new HashSet<>(accountDeviceIds);
|
||||
missingDeviceIds.removeAll(registrationIdsByDeviceId.keySet());
|
||||
|
||||
final Set<Byte> extraDeviceIds = new HashSet<>(registrationIdsByDeviceId.keySet());
|
||||
extraDeviceIds.removeAll(accountDeviceIds);
|
||||
|
||||
final Set<Byte> staleDeviceIds = registrationIdsByDeviceId.entrySet().stream()
|
||||
// Filter out device IDs that aren't associated with the given account
|
||||
.filter(entry -> !extraDeviceIds.contains(entry.getKey()))
|
||||
.filter(entry -> {
|
||||
final byte deviceId = entry.getKey();
|
||||
final int registrationId = entry.getValue();
|
||||
|
||||
// We know the device must be present because we've already filtered out device IDs that aren't associated
|
||||
// with the given account
|
||||
final Device device = account.getDevice(deviceId).orElseThrow();
|
||||
|
||||
final int expectedRegistrationId = switch (serviceIdentifier.identityType()) {
|
||||
case ACI -> device.getRegistrationId();
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId().orElseGet(device::getRegistrationId);
|
||||
};
|
||||
|
||||
return registrationId != expectedRegistrationId;
|
||||
})
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
return (!missingDeviceIds.isEmpty() || !extraDeviceIds.isEmpty() || !staleDeviceIds.isEmpty())
|
||||
? Optional.of(new MismatchedDevices(missingDeviceIds, extraDeviceIds, staleDeviceIds))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
private static void validateIndividualMessageContentLength(final Iterable<Envelope> messages,
|
||||
final boolean isSyncMessage,
|
||||
final boolean isStory,
|
||||
@Nullable final String userAgent) throws MessageTooLargeException {
|
||||
|
||||
for (final Envelope message : messages) {
|
||||
MessageSender.validateContentLength(message.getContent().size(),
|
||||
false,
|
||||
isSyncMessage,
|
||||
isStory,
|
||||
userAgent);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateMultiRecipientMessageContentLength(final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
final boolean isStory,
|
||||
@Nullable final String userAgent) throws MessageTooLargeException {
|
||||
|
||||
for (final SealedSenderMultiRecipientMessage.Recipient recipient : multiRecipientMessage.getRecipients().values()) {
|
||||
MessageSender.validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipient),
|
||||
true,
|
||||
false,
|
||||
isStory,
|
||||
userAgent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
@@ -15,6 +16,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
@@ -54,9 +56,21 @@ public class ReceiptSender {
|
||||
.setUrgent(false)
|
||||
.build();
|
||||
|
||||
final Map<Byte, Envelope> messagesByDeviceId = destinationAccount.getDevices().stream()
|
||||
.collect(Collectors.toMap(Device::getId, ignored -> message));
|
||||
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId = destinationAccount.getDevices().stream()
|
||||
.collect(Collectors.toMap(Device::getId, device -> switch (destinationIdentifier.identityType()) {
|
||||
case ACI -> device.getRegistrationId();
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId().orElseGet(device::getRegistrationId);
|
||||
}));
|
||||
|
||||
try {
|
||||
messageSender.sendMessages(destinationAccount, destinationAccount.getDevices().stream()
|
||||
.collect(Collectors.toMap(Device::getId, ignored -> message)));
|
||||
messageSender.sendMessages(destinationAccount,
|
||||
destinationIdentifier,
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
UserAgentTagUtil.SERVER_UA);
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Could not send delivery receipt", e);
|
||||
}
|
||||
|
||||
@@ -19,10 +19,12 @@ public interface SpamChecker {
|
||||
/**
|
||||
* Determine if a message sent to an individual recipient via HTTP may be spam.
|
||||
*
|
||||
* @param requestContext The request context for a message send attempt
|
||||
* @param maybeSource The sender of the message, could be empty if this as message sent with sealed sender
|
||||
* @param maybeDestination The destination of the message, could be empty if the destination does not exist or could
|
||||
* @param messageType the type of message to check
|
||||
* @param requestContext the request context for a message send attempt
|
||||
* @param maybeSource the sender of the message, could be empty if this as message sent with sealed sender
|
||||
* @param maybeDestination the destination of the message, could be empty if the destination does not exist or could
|
||||
* not be retrieved
|
||||
* @param destinationIdentifier the service identifier for the destination account
|
||||
* @return A {@link SpamCheckResult}
|
||||
*/
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@@ -31,12 +33,13 @@ public interface SpamChecker {
|
||||
final ContainerRequestContext requestContext,
|
||||
final Optional<? extends AccountAndAuthenticatedDeviceHolder> maybeSource,
|
||||
final Optional<Account> maybeDestination,
|
||||
final Optional<ServiceIdentifier> maybeDestinationIdentifier);
|
||||
final ServiceIdentifier destinationIdentifier);
|
||||
|
||||
/**
|
||||
* Determine if a message sent to multiple recipients via HTTP may be spam.
|
||||
*
|
||||
* @param requestContext The request context for a message send attempt
|
||||
* @param messageType the type of message to check
|
||||
* @param requestContext the request context for a message send attempt
|
||||
* @return A {@link SpamCheckResult}
|
||||
*/
|
||||
SpamCheckResult<Response> checkForMultiRecipientSpamHttp(
|
||||
@@ -46,9 +49,11 @@ public interface SpamChecker {
|
||||
/**
|
||||
* Determine if a message sent to an individual recipient via gRPC may be spam.
|
||||
*
|
||||
* @param maybeSource The sender of the message, could be empty if this as message sent with sealed sender
|
||||
* @param maybeDestination The destination of the message, could be empty if the destination does not exist or could
|
||||
* @param messageType the type of message to check
|
||||
* @param maybeSource the sender of the message, could be empty if this as message sent with sealed sender
|
||||
* @param maybeDestination the destination of the message, could be empty if the destination does not exist or could
|
||||
* not be retrieved
|
||||
* @param destinationIdentifier the service identifier for the destination account
|
||||
* @return A {@link SpamCheckResult}
|
||||
*/
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@@ -56,11 +61,13 @@ public interface SpamChecker {
|
||||
final MessageType messageType,
|
||||
final Optional<org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice> maybeSource,
|
||||
final Optional<Account> maybeDestination,
|
||||
final Optional<ServiceIdentifier> maybeDestinationIdentifier);
|
||||
final ServiceIdentifier destinationIdentifier);
|
||||
|
||||
/**
|
||||
* Determine if a message sent to multiple recipients via gRPC may be spam.
|
||||
*
|
||||
* @param messageType the type of message to check
|
||||
*
|
||||
* @return A {@link SpamCheckResult}
|
||||
*/
|
||||
SpamCheckResult<GrpcResponse<SendMultiRecipientMessageResponse>> checkForMultiRecipientSpamGrpc(final MessageType messageType);
|
||||
@@ -74,7 +81,7 @@ public interface SpamChecker {
|
||||
final ContainerRequestContext requestContext,
|
||||
final Optional<? extends AccountAndAuthenticatedDeviceHolder> maybeSource,
|
||||
final Optional<Account> maybeDestination,
|
||||
final Optional<ServiceIdentifier> maybeDestinationIdentifier) {
|
||||
final ServiceIdentifier destinationIdentifier) {
|
||||
|
||||
return new SpamCheckResult<>(Optional.empty(), Optional.empty());
|
||||
}
|
||||
@@ -90,7 +97,7 @@ public interface SpamChecker {
|
||||
public SpamCheckResult<GrpcResponse<SendMessageResponse>> checkForIndividualRecipientSpamGrpc(final MessageType messageType,
|
||||
final Optional<AuthenticatedDevice> maybeSource,
|
||||
final Optional<Account> maybeDestination,
|
||||
final Optional<ServiceIdentifier> maybeDestinationIdentifier) {
|
||||
final ServiceIdentifier destinationIdentifier) {
|
||||
|
||||
return new SpamCheckResult<>(Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
+25
-13
@@ -37,10 +37,12 @@ import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -55,6 +57,7 @@ import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.Mac;
|
||||
@@ -67,6 +70,7 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
@@ -83,7 +87,6 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -780,24 +783,33 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
// Check that all including primary ID are in signed pre-keys
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(
|
||||
account,
|
||||
pniSignedPreKeys.keySet(),
|
||||
Collections.emptySet());
|
||||
validateCompleteDeviceList(account, pniSignedPreKeys.keySet());
|
||||
|
||||
// Check that all including primary ID are in Pq pre-keys
|
||||
if (pniPqLastResortPreKeys != null) {
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(
|
||||
account,
|
||||
pniPqLastResortPreKeys.keySet(),
|
||||
Collections.emptySet());
|
||||
validateCompleteDeviceList(account, pniPqLastResortPreKeys.keySet());
|
||||
}
|
||||
|
||||
// Check that all devices are accounted for in the map of new PNI registration IDs
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(
|
||||
account,
|
||||
pniRegistrationIds.keySet(),
|
||||
Collections.emptySet());
|
||||
validateCompleteDeviceList(account, pniRegistrationIds.keySet());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static void validateCompleteDeviceList(final Account account, final Set<Byte> deviceIds) throws MismatchedDevicesException {
|
||||
final Set<Byte> accountDeviceIds = account.getDevices().stream()
|
||||
.map(Device::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
final Set<Byte> missingDeviceIds = new HashSet<>(accountDeviceIds);
|
||||
missingDeviceIds.removeAll(deviceIds);
|
||||
|
||||
final Set<Byte> extraDeviceIds = new HashSet<>(deviceIds);
|
||||
extraDeviceIds.removeAll(accountDeviceIds);
|
||||
|
||||
if (!missingDeviceIds.isEmpty() || !extraDeviceIds.isEmpty()) {
|
||||
throw new MismatchedDevicesException(
|
||||
new MismatchedDevices(missingDeviceIds, extraDeviceIds, Collections.emptySet()));
|
||||
}
|
||||
}
|
||||
|
||||
public record UsernameReservation(Account account, byte[] reservedUsernameHash){}
|
||||
|
||||
+16
-41
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ObjectUtils;
|
||||
@@ -15,15 +14,14 @@ import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
|
||||
public class ChangeNumberManager {
|
||||
|
||||
@@ -45,12 +43,10 @@ public class ChangeNumberManager {
|
||||
@Nullable final List<IncomingMessage> deviceMessages,
|
||||
@Nullable final Map<Byte, Integer> pniRegistrationIds,
|
||||
@Nullable final String senderUserAgent)
|
||||
throws InterruptedException, MismatchedDevicesException, StaleDevicesException, MessageTooLargeException {
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException {
|
||||
|
||||
if (ObjectUtils.allNotNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds)) {
|
||||
// AccountsManager validates the device set on deviceSignedPreKeys and pniRegistrationIds
|
||||
validateDeviceMessages(account, deviceMessages);
|
||||
} else if (!ObjectUtils.allNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds)) {
|
||||
if (!(ObjectUtils.allNotNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds) ||
|
||||
ObjectUtils.allNull(pniIdentityKey, deviceSignedPreKeys, deviceMessages, pniRegistrationIds))) {
|
||||
throw new IllegalArgumentException("PNI identity key, signed pre-keys, device messages, and registration IDs must be all null or all non-null");
|
||||
}
|
||||
|
||||
@@ -84,9 +80,7 @@ public class ChangeNumberManager {
|
||||
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
|
||||
final List<IncomingMessage> deviceMessages,
|
||||
final Map<Byte, Integer> pniRegistrationIds,
|
||||
final String senderUserAgent) throws MismatchedDevicesException, StaleDevicesException, MessageTooLargeException {
|
||||
|
||||
validateDeviceMessages(account, deviceMessages);
|
||||
final String senderUserAgent) throws MismatchedDevicesException, MessageTooLargeException {
|
||||
|
||||
// Don't try to be smart about ignoring unnecessary retries. If we make literally no change we will skip the ddb
|
||||
// write anyway. Linked devices can handle some wasted extra key rotations.
|
||||
@@ -97,51 +91,32 @@ public class ChangeNumberManager {
|
||||
return updatedAccount;
|
||||
}
|
||||
|
||||
private void validateDeviceMessages(final Account account,
|
||||
final List<IncomingMessage> deviceMessages) throws MismatchedDevicesException, StaleDevicesException {
|
||||
// Check that all except primary ID are in device messages
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(
|
||||
account,
|
||||
deviceMessages.stream().map(IncomingMessage::destinationDeviceId).collect(Collectors.toSet()),
|
||||
Set.of(Device.PRIMARY_ID));
|
||||
|
||||
// check that all sync messages are to the current registration ID for the matching device
|
||||
DestinationDeviceValidator.validateRegistrationIds(
|
||||
account,
|
||||
deviceMessages,
|
||||
IncomingMessage::destinationDeviceId,
|
||||
IncomingMessage::destinationRegistrationId,
|
||||
false);
|
||||
}
|
||||
|
||||
private void sendDeviceMessages(final Account account,
|
||||
final List<IncomingMessage> deviceMessages,
|
||||
final String senderUserAgent) throws MessageTooLargeException {
|
||||
|
||||
for (final IncomingMessage message : deviceMessages) {
|
||||
MessageSender.validateContentLength(message.content().length,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
senderUserAgent);
|
||||
}
|
||||
final String senderUserAgent) throws MessageTooLargeException, MismatchedDevicesException {
|
||||
|
||||
try {
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getUuid());
|
||||
|
||||
messageSender.sendMessages(account, deviceMessages.stream()
|
||||
final Map<Byte, Envelope> messagesByDeviceId = deviceMessages.stream()
|
||||
.collect(Collectors.toMap(IncomingMessage::destinationDeviceId, message -> Envelope.newBuilder()
|
||||
.setType(Envelope.Type.forNumber(message.type()))
|
||||
.setClientTimestamp(serverTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setDestinationServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
|
||||
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
|
||||
.setContent(ByteString.copyFrom(message.content()))
|
||||
.setSourceServiceId(new AciServiceIdentifier(account.getUuid()).toServiceIdentifierString())
|
||||
.setSourceServiceId(serviceIdentifier.toServiceIdentifierString())
|
||||
.setSourceDevice(Device.PRIMARY_ID)
|
||||
.setUpdatedPni(account.getPhoneNumberIdentifier().toString())
|
||||
.setUrgent(true)
|
||||
.setEphemeral(false)
|
||||
.build())));
|
||||
.build()));
|
||||
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId = account.getDevices().stream()
|
||||
.collect(Collectors.toMap(Device::getId, Device::getRegistrationId));
|
||||
|
||||
messageSender.sendMessages(account, serviceIdentifier, messagesByDeviceId, registrationIdsByDeviceId, senderUserAgent);
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
|
||||
throw e;
|
||||
|
||||
-108
@@ -1,108 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
public class DestinationDeviceValidator {
|
||||
|
||||
/**
|
||||
* @see #validateRegistrationIds(Account, Stream, boolean)
|
||||
*/
|
||||
public static <T> void validateRegistrationIds(final Account account,
|
||||
final Collection<T> messages,
|
||||
Function<T, Byte> getDeviceId,
|
||||
Function<T, Integer> getRegistrationId,
|
||||
boolean usePhoneNumberIdentity) throws StaleDevicesException {
|
||||
|
||||
validateRegistrationIds(account,
|
||||
messages.stream().map(m -> new Pair<>(getDeviceId.apply(m), getRegistrationId.apply(m))),
|
||||
usePhoneNumberIdentity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the given device ID/registration ID pairs exactly match the corresponding device ID/registration ID
|
||||
* pairs in the given destination account. This method does <em>not</em> validate that all devices associated with the
|
||||
* destination account are present in the given device ID/registration ID pairs.
|
||||
*
|
||||
* @param account the destination account against which to check the given device
|
||||
* ID/registration ID pairs
|
||||
* @param deviceIdAndRegistrationIdStream a stream of device ID and registration ID pairs
|
||||
* @param usePhoneNumberIdentity if {@code true}, compare provided registration IDs against device
|
||||
* registration IDs associated with the account's PNI (if available); compare
|
||||
* against the ACI-associated registration ID otherwise
|
||||
* @throws StaleDevicesException if the device ID/registration ID pairs contained an entry for which the destination
|
||||
* account does not have a corresponding device or if the registration IDs do not match
|
||||
*/
|
||||
public static void validateRegistrationIds(final Account account,
|
||||
final Stream<Pair<Byte, Integer>> deviceIdAndRegistrationIdStream,
|
||||
final boolean usePhoneNumberIdentity) throws StaleDevicesException {
|
||||
|
||||
final List<Byte> staleDevices = deviceIdAndRegistrationIdStream
|
||||
.filter(deviceIdAndRegistrationId -> deviceIdAndRegistrationId.second() > 0)
|
||||
.filter(deviceIdAndRegistrationId -> {
|
||||
final byte deviceId = deviceIdAndRegistrationId.first();
|
||||
final int registrationId = deviceIdAndRegistrationId.second();
|
||||
boolean registrationIdMatches = account.getDevice(deviceId)
|
||||
.map(device -> registrationId == (usePhoneNumberIdentity
|
||||
? device.getPhoneNumberIdentityRegistrationId().orElse(device.getRegistrationId())
|
||||
: device.getRegistrationId()))
|
||||
.orElse(false);
|
||||
return !registrationIdMatches;
|
||||
})
|
||||
.map(Pair::first)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (!staleDevices.isEmpty()) {
|
||||
throw new StaleDevicesException(staleDevices);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the given set of device IDs from a set of messages matches the set of device IDs associated with the
|
||||
* given destination account in preparation for sending those messages to the destination account. In general, the set
|
||||
* of device IDs must exactly match the set of active devices associated with the destination account. When sending a
|
||||
* "sync," message, though, the authenticated account is sending messages from one of their devices to all other
|
||||
* devices; in that case, callers must pass the ID of the sending device in the set of {@code excludedDeviceIds}.
|
||||
*
|
||||
* @param account the destination account against which to check the given set of device IDs
|
||||
* @param messageDeviceIds the set of device IDs to check against the destination account
|
||||
* @param excludedDeviceIds a set of device IDs that may be associated with the destination account, but must not be
|
||||
* present in the given set of device IDs (i.e. the device that is sending a sync message)
|
||||
* @throws MismatchedDevicesException if the given set of device IDs contains entries not currently associated with
|
||||
* the destination account or is missing entries associated with the destination
|
||||
* account
|
||||
*/
|
||||
public static void validateCompleteDeviceList(final Account account,
|
||||
final Set<Byte> messageDeviceIds,
|
||||
final Set<Byte> excludedDeviceIds) throws MismatchedDevicesException {
|
||||
|
||||
final Set<Byte> accountDeviceIds = account.getDevices().stream()
|
||||
.map(Device::getId)
|
||||
.filter(deviceId -> !excludedDeviceIds.contains(deviceId))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
final Set<Byte> missingDeviceIds = new HashSet<>(accountDeviceIds);
|
||||
missingDeviceIds.removeAll(messageDeviceIds);
|
||||
|
||||
final Set<Byte> extraDeviceIds = new HashSet<>(messageDeviceIds);
|
||||
extraDeviceIds.removeAll(accountDeviceIds);
|
||||
|
||||
if (!missingDeviceIds.isEmpty() || !extraDeviceIds.isEmpty()) {
|
||||
throw new MismatchedDevicesException(new ArrayList<>(missingDeviceIds), new ArrayList<>(extraDeviceIds));
|
||||
}
|
||||
}
|
||||
}
|
||||
+196
-80
@@ -20,6 +20,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.anyBoolean;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
@@ -39,6 +40,7 @@ import jakarta.ws.rs.client.Invocation;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
@@ -55,6 +57,7 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.hamcrest.Matcher;
|
||||
@@ -72,16 +75,15 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
|
||||
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.SpamReport;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
@@ -94,6 +96,7 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
@@ -195,10 +198,10 @@ class MessageControllerTest {
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
void setup() throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
|
||||
reset(pushNotificationScheduler);
|
||||
|
||||
when(messageSender.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean()))
|
||||
when(messageSender.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final List<Device> singleDeviceList = List.of(
|
||||
@@ -287,7 +290,7 @@ class MessageControllerTest {
|
||||
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(messageSender).sendMessages(any(), captor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, captor.getValue().size());
|
||||
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
|
||||
@@ -332,7 +335,7 @@ class MessageControllerTest {
|
||||
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(messageSender).sendMessages(any(), captor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, captor.getValue().size());
|
||||
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
|
||||
@@ -357,7 +360,7 @@ class MessageControllerTest {
|
||||
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(messageSender).sendMessages(any(), captor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, captor.getValue().size());
|
||||
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
|
||||
@@ -395,7 +398,7 @@ class MessageControllerTest {
|
||||
assertThat("Good Response", response.getStatus(), is(equalTo(200)));
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(messageSender).sendMessages(any(), captor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, captor.getValue().size());
|
||||
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
|
||||
@@ -434,7 +437,7 @@ class MessageControllerTest {
|
||||
assertThat("Good Response", response.getStatus(), is(equalTo(expectedResponse)));
|
||||
if (expectedResponse == 200) {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(messageSender).sendMessages(any(), captor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), captor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, captor.getValue().size());
|
||||
final Envelope message = captor.getValue().values().stream().findFirst().orElseThrow();
|
||||
@@ -530,6 +533,9 @@ class MessageControllerTest {
|
||||
|
||||
@Test
|
||||
void testMultiDeviceMissing() throws Exception {
|
||||
doThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of((byte) 2, (byte) 3), Collections.emptySet(), Collections.emptySet())))
|
||||
.when(messageSender).sendMessages(any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
|
||||
@@ -542,15 +548,16 @@ class MessageControllerTest {
|
||||
assertThat("Good Response Code", response.getStatus(), is(equalTo(409)));
|
||||
|
||||
assertThat("Good Response Body",
|
||||
asJson(response.readEntity(MismatchedDevices.class)),
|
||||
asJson(response.readEntity(MismatchedDevicesResponse.class)),
|
||||
is(equalTo(jsonFixture("fixtures/missing_device_response.json"))));
|
||||
|
||||
verifyNoMoreInteractions(messageSender);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultiDeviceExtra() throws Exception {
|
||||
doThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of((byte) 2), Set.of((byte) 4), Collections.emptySet())))
|
||||
.when(messageSender).sendMessages(any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
|
||||
@@ -563,10 +570,8 @@ class MessageControllerTest {
|
||||
assertThat("Good Response Code", response.getStatus(), is(equalTo(409)));
|
||||
|
||||
assertThat("Good Response Body",
|
||||
asJson(response.readEntity(MismatchedDevices.class)),
|
||||
asJson(response.readEntity(MismatchedDevicesResponse.class)),
|
||||
is(equalTo(jsonFixture("fixtures/missing_device_response2.json"))));
|
||||
|
||||
verifyNoMoreInteractions(messageSender);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -602,7 +607,7 @@ class MessageControllerTest {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
verify(messageSender).sendMessages(any(Account.class), envelopeCaptor.capture());
|
||||
verify(messageSender).sendMessages(any(Account.class), any(), envelopeCaptor.capture(), any(), any());
|
||||
|
||||
assertEquals(3, envelopeCaptor.getValue().size());
|
||||
|
||||
@@ -626,7 +631,7 @@ class MessageControllerTest {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
verify(messageSender).sendMessages(any(Account.class), envelopeCaptor.capture());
|
||||
verify(messageSender).sendMessages(any(Account.class), any(), envelopeCaptor.capture(), any(), any());
|
||||
|
||||
assertEquals(3, envelopeCaptor.getValue().size());
|
||||
|
||||
@@ -648,12 +653,18 @@ class MessageControllerTest {
|
||||
assertThat("Good Response Code", response.getStatus(), is(equalTo(200)));
|
||||
|
||||
verify(messageSender).sendMessages(any(Account.class),
|
||||
argThat(messagesByDeviceId -> messagesByDeviceId.size() == 3));
|
||||
any(),
|
||||
argThat(messagesByDeviceId -> messagesByDeviceId.size() == 3),
|
||||
any(),
|
||||
any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRegistrationIdMismatch() throws Exception {
|
||||
doThrow(new MismatchedDevicesException(new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of((byte) 2))))
|
||||
.when(messageSender).sendMessages(any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response =
|
||||
resources.getJerseyTest().target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
|
||||
.request()
|
||||
@@ -665,10 +676,8 @@ class MessageControllerTest {
|
||||
assertThat("Good Response Code", response.getStatus(), is(equalTo(410)));
|
||||
|
||||
assertThat("Good Response Body",
|
||||
asJson(response.readEntity(StaleDevices.class)),
|
||||
asJson(response.readEntity(StaleDevicesResponse.class)),
|
||||
is(equalTo(jsonFixture("fixtures/mismatched_registration_id.json"))));
|
||||
|
||||
verifyNoMoreInteractions(messageSender);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1078,24 +1087,19 @@ class MessageControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateContentLength() {
|
||||
final int contentLength = Math.toIntExact(MessageSender.MAX_MESSAGE_SIZE + 1);
|
||||
final byte[] contentBytes = new byte[contentLength];
|
||||
Arrays.fill(contentBytes, (byte) 1);
|
||||
void testValidateContentLength() throws MismatchedDevicesException, MessageTooLargeException, IOException {
|
||||
doThrow(new MessageTooLargeException()).when(messageSender).sendMessages(any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
|
||||
.request()
|
||||
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
|
||||
.put(Entity.entity(new IncomingMessageList(
|
||||
List.of(new IncomingMessage(1, (byte) 1, 1, contentBytes)), false, true,
|
||||
System.currentTimeMillis()),
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(SystemMapper.jsonMapper().readValue(jsonFixture("fixtures/current_message_single_device.json"),
|
||||
IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat("Bad response", response.getStatus(), is(equalTo(413)));
|
||||
|
||||
verify(messageSender, never()).sendMessages(any(), any());
|
||||
assertThat(response.getStatus(), is(equalTo(413)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1113,10 +1117,10 @@ class MessageControllerTest {
|
||||
|
||||
if (expectOk) {
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(messageSender).sendMessages(any(), any());
|
||||
verify(messageSender).sendMessages(any(), any(), any(), any(), any());
|
||||
} else {
|
||||
assertEquals(422, response.getStatus());
|
||||
verify(messageSender, never()).sendMessages(any(), any());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1140,7 +1144,9 @@ class MessageControllerTest {
|
||||
final Optional<String> maybeGroupSendToken,
|
||||
final int expectedStatus,
|
||||
final Set<Account> expectedResolvedAccounts,
|
||||
final Set<ServiceIdentifier> expectedUuids404) {
|
||||
final Set<ServiceIdentifier> expectedUuids404,
|
||||
@Nullable final MultiRecipientMismatchedDevicesException mismatchedDevicesException)
|
||||
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
|
||||
|
||||
clock.pin(START_OF_DAY);
|
||||
|
||||
@@ -1151,6 +1157,11 @@ class MessageControllerTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)))));
|
||||
|
||||
if (mismatchedDevicesException != null) {
|
||||
doThrow(mismatchedDevicesException)
|
||||
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
final boolean ephemeral = true;
|
||||
final boolean urgent = false;
|
||||
|
||||
@@ -1187,16 +1198,18 @@ class MessageControllerTest {
|
||||
assertThat(Set.copyOf(entity.uuids404()), equalTo(expectedUuids404));
|
||||
}
|
||||
|
||||
if (expectedStatus == 200 && !expectedResolvedAccounts.isEmpty()) {
|
||||
if ((expectedStatus == 200 && !expectedResolvedAccounts.isEmpty()) || mismatchedDevicesException != null) {
|
||||
verify(messageSender).sendMultiRecipientMessage(any(),
|
||||
argThat(resolvedRecipients ->
|
||||
new HashSet<>(resolvedRecipients.values()).equals(expectedResolvedAccounts)),
|
||||
anyLong(),
|
||||
eq(isStory),
|
||||
eq(ephemeral),
|
||||
eq(urgent));
|
||||
eq(urgent),
|
||||
any());
|
||||
} else {
|
||||
verify(messageSender, never()).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean());
|
||||
verify(messageSender, never())
|
||||
.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1267,7 +1280,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
200,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Multi-recipient message with combined UAKs",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1279,7 +1293,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
200,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Multi-recipient message with group send endorsement",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1291,7 +1306,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
200,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Incorrect combined UAK",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1303,7 +1319,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
401,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Incorrect group send endorsement",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1317,7 +1334,8 @@ class MessageControllerTest {
|
||||
START_OF_DAY.plus(Duration.ofDays(1)))),
|
||||
401,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
// Stories don't require credentials of any kind, but for historical reasons, we don't reject a combined UAK if
|
||||
// provided
|
||||
@@ -1331,7 +1349,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
200,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Story with group send endorsement",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1343,7 +1362,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
400,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Conflicting credentials",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1355,7 +1375,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
400,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("No credentials",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1367,23 +1388,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
401,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
|
||||
Arguments.argumentSet("Oversized payload",
|
||||
accountsByServiceIdentifier,
|
||||
MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
|
||||
new TestRecipient(new AciServiceIdentifier(singleDeviceAccountAci), Device.PRIMARY_ID, singleDevicePrimaryRegistrationId, new byte[48]),
|
||||
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), Device.PRIMARY_ID, multiDevicePrimaryRegistrationId, new byte[48]),
|
||||
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), (byte) (Device.PRIMARY_ID + 1), multiDeviceLinkedRegistrationId, new byte[48])),
|
||||
MultiRecipientMessageProvider.MAX_MESSAGE_SIZE),
|
||||
clock.instant().toEpochMilli(),
|
||||
false,
|
||||
false,
|
||||
Optional.empty(),
|
||||
Optional.of(groupSendEndorsement),
|
||||
413,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Negative timestamp",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1395,7 +1401,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
400,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Excessive timestamp",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1407,7 +1414,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
400,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Empty recipient list",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1421,7 +1429,8 @@ class MessageControllerTest {
|
||||
START_OF_DAY.plus(Duration.ofDays(1)))),
|
||||
400,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Story with empty recipient list",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1433,7 +1442,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
400,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Duplicate recipient",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1447,7 +1457,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
400,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Missing account",
|
||||
Map.of(),
|
||||
@@ -1459,7 +1470,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
200,
|
||||
Collections.emptySet(),
|
||||
Set.of(new AciServiceIdentifier(singleDeviceAccountAci), new AciServiceIdentifier(multiDeviceAccountAci))),
|
||||
Set.of(new AciServiceIdentifier(singleDeviceAccountAci), new AciServiceIdentifier(multiDeviceAccountAci)),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("One missing and one existing account",
|
||||
Map.of(new AciServiceIdentifier(singleDeviceAccountAci), singleDeviceAccount),
|
||||
@@ -1471,7 +1483,8 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
200,
|
||||
Set.of(singleDeviceAccount),
|
||||
Set.of(new AciServiceIdentifier(multiDeviceAccountAci))),
|
||||
Set.of(new AciServiceIdentifier(multiDeviceAccountAci)),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Missing account for story",
|
||||
Map.of(),
|
||||
@@ -1483,7 +1496,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
200,
|
||||
Collections.emptySet(),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("One missing and one existing account for story",
|
||||
Map.of(new AciServiceIdentifier(singleDeviceAccountAci), singleDeviceAccount),
|
||||
@@ -1495,7 +1509,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
200,
|
||||
Set.of(singleDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Missing device",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1509,7 +1524,9 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
409,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
new MultiRecipientMismatchedDevicesException(Map.of(new AciServiceIdentifier(multiDeviceAccountAci),
|
||||
new MismatchedDevices(Set.of((byte) (Device.PRIMARY_ID + 1)), Collections.emptySet(), Collections.emptySet())))),
|
||||
|
||||
Arguments.argumentSet("Extra device",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1525,7 +1542,9 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
409,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
new MultiRecipientMismatchedDevicesException(Map.of(new AciServiceIdentifier(multiDeviceAccountAci),
|
||||
new MismatchedDevices(Collections.emptySet(), Set.of((byte) (Device.PRIMARY_ID + 2)), Collections.emptySet())))),
|
||||
|
||||
Arguments.argumentSet("Stale registration ID",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1540,7 +1559,9 @@ class MessageControllerTest {
|
||||
Optional.of(groupSendEndorsement),
|
||||
410,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
new MultiRecipientMismatchedDevicesException(Map.of(new AciServiceIdentifier(multiDeviceAccountAci),
|
||||
new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of((byte) (Device.PRIMARY_ID + 1)))))),
|
||||
|
||||
Arguments.argumentSet("Rate-limited story",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1552,7 +1573,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
429,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Story to PNI recipients",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1567,7 +1589,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
200,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Multi-recipient message to PNI recipients with UAK",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1582,7 +1605,8 @@ class MessageControllerTest {
|
||||
Optional.empty(),
|
||||
401,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of()),
|
||||
Set.of(),
|
||||
null),
|
||||
|
||||
Arguments.argumentSet("Multi-recipient message to PNI recipients with group send endorsement",
|
||||
accountsByServiceIdentifier,
|
||||
@@ -1599,10 +1623,102 @@ class MessageControllerTest {
|
||||
START_OF_DAY.plus(Duration.ofDays(1)))),
|
||||
200,
|
||||
Set.of(singleDeviceAccount, multiDeviceAccount),
|
||||
Set.of())
|
||||
Set.of(),
|
||||
null)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendMultiRecipientMessageOversized() throws Exception {
|
||||
|
||||
clock.pin(START_OF_DAY);
|
||||
|
||||
final UUID singleDeviceAccountAci = UUID.randomUUID();
|
||||
final UUID singleDeviceAccountPni = UUID.randomUUID();
|
||||
final UUID multiDeviceAccountAci = UUID.randomUUID();
|
||||
final UUID multiDeviceAccountPni = UUID.randomUUID();
|
||||
|
||||
final byte[] singleDeviceAccountUak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
final byte[] multiDeviceAccountUak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
final int singleDevicePrimaryRegistrationId = 1;
|
||||
final int multiDevicePrimaryRegistrationId = 2;
|
||||
final int multiDeviceLinkedRegistrationId = 3;
|
||||
|
||||
final Device singleDeviceAccountPrimary = mock(Device.class);
|
||||
when(singleDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(singleDeviceAccountPrimary.getRegistrationId()).thenReturn(singleDevicePrimaryRegistrationId);
|
||||
|
||||
final Device multiDeviceAccountPrimary = mock(Device.class);
|
||||
when(multiDeviceAccountPrimary.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(multiDeviceAccountPrimary.getRegistrationId()).thenReturn(multiDevicePrimaryRegistrationId);
|
||||
|
||||
final Device multiDeviceAccountLinked = mock(Device.class);
|
||||
when(multiDeviceAccountLinked.getId()).thenReturn((byte) (Device.PRIMARY_ID + 1));
|
||||
when(multiDeviceAccountLinked.getRegistrationId()).thenReturn(multiDeviceLinkedRegistrationId);
|
||||
|
||||
final Account singleDeviceAccount = mock(Account.class);
|
||||
when(singleDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(singleDeviceAccountAci);
|
||||
when(singleDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(singleDeviceAccountUak));
|
||||
when(singleDeviceAccount.getDevices()).thenReturn(List.of(singleDeviceAccountPrimary));
|
||||
when(singleDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty());
|
||||
when(singleDeviceAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(singleDeviceAccountPrimary));
|
||||
|
||||
final Account multiDeviceAccount = mock(Account.class);
|
||||
when(multiDeviceAccount.getIdentifier(IdentityType.ACI)).thenReturn(multiDeviceAccountAci);
|
||||
when(multiDeviceAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(multiDeviceAccountUak));
|
||||
when(multiDeviceAccount.getDevices()).thenReturn(List.of(multiDeviceAccountPrimary, multiDeviceAccountLinked));
|
||||
when(multiDeviceAccount.getDevice(anyByte())).thenReturn(Optional.empty());
|
||||
when(multiDeviceAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(multiDeviceAccountPrimary));
|
||||
when(multiDeviceAccount.getDevice((byte) (Device.PRIMARY_ID + 1))).thenReturn(Optional.of(multiDeviceAccountLinked));
|
||||
|
||||
final Map<ServiceIdentifier, Account> accountsByServiceIdentifier = Map.of(
|
||||
new AciServiceIdentifier(singleDeviceAccountAci), singleDeviceAccount,
|
||||
new AciServiceIdentifier(multiDeviceAccountAci), multiDeviceAccount,
|
||||
new PniServiceIdentifier(singleDeviceAccountPni), singleDeviceAccount,
|
||||
new PniServiceIdentifier(multiDeviceAccountPni), multiDeviceAccount);
|
||||
|
||||
final byte[] aciMessage = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
|
||||
new TestRecipient(new AciServiceIdentifier(singleDeviceAccountAci), Device.PRIMARY_ID, singleDevicePrimaryRegistrationId, new byte[48]),
|
||||
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), Device.PRIMARY_ID, multiDevicePrimaryRegistrationId, new byte[48]),
|
||||
new TestRecipient(new AciServiceIdentifier(multiDeviceAccountAci), (byte) (Device.PRIMARY_ID + 1), multiDeviceLinkedRegistrationId, new byte[48])));
|
||||
|
||||
when(accountsManager.getByServiceIdentifierAsync(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
accountsByServiceIdentifier.forEach(((serviceIdentifier, account) ->
|
||||
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)))));
|
||||
|
||||
final boolean ephemeral = true;
|
||||
final boolean urgent = false;
|
||||
final boolean story = false;
|
||||
|
||||
final Invocation.Builder invocationBuilder = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/messages/multi_recipient")
|
||||
.queryParam("ts", clock.millis())
|
||||
.queryParam("online", ephemeral)
|
||||
.queryParam("story", story)
|
||||
.queryParam("urgent", urgent)
|
||||
.request()
|
||||
.header(HeaderUtils.GROUP_SEND_TOKEN, AuthHelper.validGroupSendTokenHeader(serverSecretParams,
|
||||
List.of(new AciServiceIdentifier(singleDeviceAccountAci), new AciServiceIdentifier(multiDeviceAccountAci)),
|
||||
START_OF_DAY.plus(Duration.ofDays(1))));
|
||||
|
||||
when(rateLimiter.validateAsync(any(UUID.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
doThrow(new MessageTooLargeException())
|
||||
.when(messageSender).sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
|
||||
|
||||
try (final Response response = invocationBuilder
|
||||
.put(Entity.entity(aciMessage, MultiRecipientMessageProvider.MEDIA_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(413)));
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
private static Envelope generateEnvelope(UUID guid, int type, long timestamp, UUID sourceUuid,
|
||||
byte sourceDevice, UUID destinationUuid, UUID updatedPni, byte[] content, long serverTimestamp) {
|
||||
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.security.KeyStore;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import org.eclipse.jetty.util.resource.Resource;
|
||||
import org.eclipse.jetty.util.security.CertificateUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.util.jetty.TestResource;
|
||||
|
||||
class TlsCertificateExpirationUtilTest {
|
||||
|
||||
// Please note that this certificate is used only for testing and is not used anywhere outside of this test.
|
||||
// It was generated with:
|
||||
//
|
||||
// ```shell
|
||||
// #!/bin/bash
|
||||
//
|
||||
// export PASSWORD=test123
|
||||
//
|
||||
// openssl req -newkey rsa:2048 -keyout test-root.key -nodes -x509 -days 36500 -out test-root.crt \
|
||||
// -subj "/CN=test-root" \
|
||||
// -addext "basicConstraints=critical,CA:TRUE"
|
||||
//
|
||||
// openssl req -new -newkey rsa:2048 -keyout test-rsa.key -out test-rsa.csr -passout env:PASSWORD \
|
||||
// -subj "/CN=localhost" \
|
||||
// -addext "subjectAltName = DNS:localhost"
|
||||
//
|
||||
// openssl req -new -newkey ED25519 -keyout test-ed25519.key -out test-ed25519.csr -passout env:PASSWORD \
|
||||
// -subj "/CN=localhost" \
|
||||
// -addext "subjectAltName = DNS:localhost"
|
||||
//
|
||||
// openssl x509 -req -CAkey test-root.key -CA test-root.crt -days 36500 -copy_extensions copyall \
|
||||
// -in test-rsa.csr \
|
||||
// -out test-rsa.crt
|
||||
//
|
||||
// # create unique timestamps
|
||||
// sleep 3
|
||||
//
|
||||
// openssl x509 -req -CAkey test-root.key -CA test-root.crt -days 36500 -copy_extensions copyall \
|
||||
// -in test-ed25519.csr \
|
||||
// -out test-ed25519.crt
|
||||
//
|
||||
// cat test-root.crt >> test-rsa.crt
|
||||
//
|
||||
// openssl pkcs12 -export -in test-ed25519.crt -inkey test-ed25519.key -name 'ed25519' -out keystore.p12 \
|
||||
// -passin env:PASSWORD -passout env:PASSWORD
|
||||
//
|
||||
// openssl pkcs12 -export -in test-rsa.crt -inkey test-rsa.key -name 'rsa' -out keystore-rsa.p12 \
|
||||
// -passin env:PASSWORD -passout env:PASSWORD
|
||||
//
|
||||
// keytool -importkeystore -noprompt \
|
||||
// -srckeystore keystore-rsa.p12 \
|
||||
// -srcstoretype PKCS12 \
|
||||
// -srcstorepass $PASSWORD \
|
||||
// -destkeystore keystore.p12 \
|
||||
// -deststoretype PKCS12 \
|
||||
// -deststorepass $PASSWORD
|
||||
//
|
||||
// base64 -b 80 -i keystore.p12
|
||||
// ```
|
||||
private static final String KEYSTORE_BASE64 = """
|
||||
MIIRLQIBAzCCENcGCSqGSIb3DQEHAaCCEMgEghDEMIIQwDCCBqcGCSqGSIb3DQEHAaCCBpgEggaUMIIG
|
||||
kDCB/AYLKoZIhvcNAQwKAQKggaYwgaMwXwYJKoZIhvcNAQUNMFIwMQYJKoZIhvcNAQUMMCQEEOqLCxfn
|
||||
oI9s+ZaUjxBYAvMCAggAMAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBBhbXGVtsxJtJvyJmkGjkHF
|
||||
BEAu6JKEuzF8GnRJ8M8War9gQQloZrsShZBC0FCqQ8+JTx4eY0G8EZp1yuwh8BzJx5mGvPPEuL1K4htC
|
||||
I/nm8yC5MUQwHQYJKoZIhvcNAQkUMRAeDgBlAGQAMgA1ADUAMQA5MCMGCSqGSIb3DQEJFTEWBBTnVegw
|
||||
3d6k2KrtH5o3O4OeO4chnDCCBY0GCyqGSIb3DQEMCgECoIIFQDCCBTwwZgYJKoZIhvcNAQUNMFkwOAYJ
|
||||
KoZIhvcNAQUMMCsEFOInbF9RzXA4Hv/2CNxLQHeJkZnaAgInEAIBIDAMBggqhkiG9w0CCQUAMB0GCWCG
|
||||
SAFlAwQBKgQQHvmbAQBd3U4y9DYJsfqPkASCBNC2dllFGSuQYkdNxpxC+xunpgYN9UPKCmmrmnmw7g5t
|
||||
sSUwp0fhPv1GeHqD8dCuKJPJnEHj4eJb+VNLfPddpMimeB8/RoD6pry0acjr9YEPdCyZhqYuto1XAw2H
|
||||
AZ9joanjs7Vcm1jUSopLbOmNfJmlzgXrNAE0piGnomSsIS/if27WEvd0ydx/R8p2p2MQYt/pNRMy6QD/
|
||||
DgvPqWBcxljry2j5e70EJiPONtCHBwqDLlksPSMV0K5xkjaekV7NJn8n4QlVGE4mMt08pCxkMGqLGQX7
|
||||
VYIIGMxX0xn8WJJxiOeLGucTy0xxO0h04bCVKZOFoD6ld4CPVySQ25pLL7SB13R87T+79rQpCrf0u7Wm
|
||||
CAJSFhVO9Lo30YclYr+t6LHaq7sJRdEGcJr57i/0DfDBiw/gNE2G3z+hwNzMBgxlxQrnZVRnTC7bDeL0
|
||||
LSnPgh0xQ+YPmWJK/frMs1auTNvTKpg6HmuN46CuF7/Js34A1//IT+x6YWelHm+nF7I6cYiIgcw5HFye
|
||||
u6HzRZ74QGJzfkbCYLRWGcaSrofINdcgEXsxAxHkqAYFJrOBR4fChpkHCTJjYVMi7WG0UpE8tnvDHFn+
|
||||
5GrpWuxU7rcCbYZppT8nOLOE4TORXUrOkw9C5Lfp6m9DWKW/hUb6HYzfYg8ps8wabNzs3seitqLg5uV9
|
||||
/aRflJQxr2ga/Suk/W/0nLvvypkSO2umJ0LG8Sk3akpaYwArmtKN8jEdijngS3wc3iJlcRslJJlU+YnD
|
||||
7W0/TQ38LYWM4mjEQo+6Rym8jXn8YxwE5Srt+1RlnoFw/UxMmf6lL+pJXKUl23wgNTM6fgkgf5TX3cO7
|
||||
I66TylFQE9AQa0OLG1z9X5ga2qeet6/jkDI1eBHmRObUjtvloS/sQeSgOorAjq8wzb8vfmIH1x3iKQ7I
|
||||
uE5Ckatrf926cSFY9DgSm/9oxPiGbRlzkrTLTatZ5QBhhB8GrWct36Q5gS0Bb632k2jQt+dmm4NOHfXj
|
||||
FAk/Et5pMsuXXbtLB3HgzthybkGWYkdyTpEXhuaHD7r5jfBV0bNL0V8pr/Wumi/+LN++/xmW1LZ8wZwM
|
||||
sGGVsge/Kt8VSCbodjm6p1hVKwZtY5nwctxTMANAjmr09gMIJRyQZKxWobhWim07mSu/3U8avtZm+Yeo
|
||||
wrCv/K3B9kpvydAi3HFfswemBS3S5KSOT6HK0kfeZmr8LNkGwrxkoJwI3sh5DcGPaEUT2ez238zXTGNM
|
||||
dreCDY5ESr5kNcfLxvI/AY/lR02hO31PZhSAU7wH8QLuresi6wnJhGK7qC7oaOPz01SsCnGKRmI2jucM
|
||||
hLoEFnWkuMO9lbtE327UtCsuz9vj/ISN2P9OfgrqpfN0dhGnOOg3I1iwO9T/49Z5P3XhRDfef7nD9RmM
|
||||
7Yc/ObWlptTb3BZBd8yQmQ7QKV1nTeTSCgrcmXzSDaP0fnfNuTLnzS8vrsVxkBnKrrPq7MnFYBg7nLlv
|
||||
FiA4VKSZSymxzYzECVoNTk3bUjkoqhyaK77x/KKI9Sgr5xiKVlOvKAqTCuO2ZlF2D5V2MuYq41JyQSKv
|
||||
F/Nx5a6lbN+OqV00Jm3GR2+QI7VckaFGLadj5FpvIzxr4X4jPBQxQGAqfhhBhRuVZ7MCp7Z2KmChiY39
|
||||
uTE6MBUGCSqGSIb3DQEJFDEIHgYAcgBzAGEwIQYJKoZIhvcNAQkVMRQEElRpbWUgMTc0MzYxNTE2Mzcx
|
||||
MDCCChEGCSqGSIb3DQEHBqCCCgIwggn+AgEAMIIJ9wYJKoZIhvcNAQcBMGYGCSqGSIb3DQEFDTBZMDgG
|
||||
CSqGSIb3DQEFDDArBBTvCpZW0rVd0RGgTXwKrzvDuZFtcAICCAACASAwDAYIKoZIhvcNAgkFADAdBglg
|
||||
hkgBZQMEASoEEJDkZ8lF+7ObiTcgnwtoO5GAggmA+NyAz99Ux+/UA8H9UpdoCb29R/xSOT7gQOD5STzR
|
||||
6HTPPlrAXFJGdUUshBFIgyRZKd9DzqgR6GR549iITqWpik+qLG9l/9ZPzm6KZ8E4J3a9BP3P4O03jrUf
|
||||
QIM68+G8o0ejdd6pz7R3higRo9wyMb08DNTN3Z+mc1HiGTrmK+5KRCPFhChrgxHb1S9b8IVjGwyCefPr
|
||||
WiiBJuDIePXnZVBpjnYhqVVGTiKyXfSdIClZLZfcnaveVa+sULowZCXXPThJBb3Y+CO9WS+YoC6GR6M0
|
||||
dvRxtXYrXkElgBYvkXTAwyBQbKO775nkmNJw3xzEQPUSEmKcCMUv2+A+DxY3ybdvXLVsYIYVZVWpcQhM
|
||||
gGNq2St66kFm+adBLNOBliAEsWET6ka9m2n4e0JMzl0/rzKfihKUQrJtnhbDqpa2KnG4dWcThPVMC722
|
||||
mDheehhvhf3Q+YVyl6uTxIM2V0ZfvLdcGWaZkfaS8EXjF31j4Xd/1eeXO3ukCjT8Jy2YqTSwiP5pxJ+/
|
||||
o6SF6ij8BdjdLptrSy00YVzFmK5o7fdZBBxZgeSy2xuhB5atZm2BZXNQqgxK6i6bmUI03iAgyM0MDUDR
|
||||
GYRE1IZib98QluMpHuHRWDLwUYMmM2cqtdPcNiDUUsd3022B9EXbbut8HrWHJxeDseHye9qvafIzoclw
|
||||
IR71hqbkarSAunIdQwBkJN99DP//q9ECTt8xI/5SQwsYInpCRaX7fEizYQGlzSHDb+uwOy2MaxWYsrEM
|
||||
kfmrGAgQ7iyUl4nwYuJWyPT0YbgpFREfLXEJnpqUAGtqWmK0l/nUHfksMqTCnAVTS+YxC50yVbWLi+Ki
|
||||
umk5b6EkmO9ySyTG/w1xkiSmumg2bNPF/5Mk+DwVXF0rwABMS4RaubM1RPm7GvfUKKhiTkJFxKSyAdr7
|
||||
GIZupUpJcMLkqJeav3m247jzTzFqIMazPKpKFq86vs6Faa1+zDJJyQ8JyG+YwItTcy0aVhszBb5b33Xy
|
||||
7FZk8/Zf39OQvFgLb92TFyZG+cX7jPNsRo+2lpvCLum8ntc4UB47a0POWqDm+L5OT1FujDzvw5aZxvnI
|
||||
IY/0PRBUlpURdQ3XEgeCKuRJGPt6MGJ/Kh9g8rD+KV7gz8mu/X4rilrHRBAjptQMW8xQg49n3LzCAu44
|
||||
TD1l5ptV864vY9KSZURfXHOWfBHvmUeU4f580ZwA7OzEdyoEJsZBPvum7VNjYAw4TU4tQo2naoqIf0cg
|
||||
KsLBCsYzzRclh1ar5sxKHOyhyU/RkRILO+i7FwoEgzII3M1rmuw4FaKl6GyNP+3w6MGijJUM7EXEZTPI
|
||||
2QKc3ri4gWRYH2mIytUgzrv9vTz+V/uRqMF4+AQrDdhAzagBAnfInssJ20h+kXdoHexUjmj8kV4m6zO7
|
||||
ebeC2CjOt0Ruy29EsG7u2hrcyZ6s8tcTEk7AMf3pZWZh7fFnMqUE+RvJjnkQrxklqWnCbh8TSQQaU9Jk
|
||||
x2DAw2WFIbA8uweguXAlCKm1DyJDdlmEdjBNP7xMQ6ieJJQg+dSIpw9BrPMLDNZVFC8LCnmDAusjG80S
|
||||
TgcuebNjk0xDOM46DDSmVdsTAFCNuN0OMqilC12V5wA15tLHVFV0T2TplrKI/VNCm0+z8dAX7yoFe43R
|
||||
/YqSfPjLX/MvLb7Ni6ASXebzp3xXJTTygxEFx1aJgD2XpBliJB3flsEY8dCD2dt30CCBUf/8Qpyfl5AN
|
||||
xmaJBBRigSBYddTs3mng6w+Xr/c5bcZC9xybTAKdQtl+5knF28rwVGKa21wo7aurqI4oIY8EqPdufCLZ
|
||||
TaMtB2CPvmhAlLHgTRUlkOXBlzZMJqv7TEZiReTGOkZoXGdXfqN1xO4cuwRcf2CyyqV8VojbZ8R0LBRN
|
||||
/CPZdzR8Yr8ICR1jKZHKMxqOgjMhYGFzImHVO2NiPYWgC+MwUhrh9uiQ8vRCk/KpREvfsf7Q4KWDtQfB
|
||||
pYvay8ptsrr9O/5yNU0BY5W43ciBcjzW0C8YQIKXy3a/kZ9ZCwr+nFLZPzJHMAIZNoNtnlZIA20g1q7E
|
||||
5IYQhBlSdwWU9ajm22PSG2udMyxG363uNXTtls70VJLyTqbEWgwuI1U1NjJLga8DQw8j7bTiTmBSEF7U
|
||||
kkiAxNe/bNm8upoqU3NEvqyti14WnGQQgycbUEEucTDzq8Pyfiu+qCoOruCsPEfESbcU4WqyXTd9gA40
|
||||
6rY9vyL46CkI1E3WRvbU5BdZVSXyT8Xort+z/Edpb7MoKyb2Y39PZ+IVzlJvZ9QsNEpR985V1UHaYZnu
|
||||
GHlMVHyY+nhlQBpyKj/4Eajow+saNYhQm1TMA9xKQckqOoFHvQvM2Cy60/XbknqFCJshAOg2nvqMspMg
|
||||
F/M+yANnTMSooU9HPF3RMUN2ZkZYsXvrfZO2C+8tpP3ZzsigCgfnvwVqT024C/8Q//OBvn/PriG6j5UA
|
||||
208nRwqwICdG0IQg2j9e7m0z1OxU0oKZXfxC6fXkj7R/B/yKf/aNByq6bRebsD8QRNPW7P1YE+jvfya9
|
||||
5SVOLuc8cyiqoMBqWm4rwT+/cxqp7zYVj9kLVvaAYqh1QtGgHvIVarCsSnwbEdEq9S7m9HwRmgogJ+80
|
||||
UnMhrhdFI0buVSCFIlEHA9Wn1ipxcv4hZjR6GRcw3NY8I8DTs8vdU+DPXktUVg2B9Q/hMZnr1MxPe5Nx
|
||||
+fQf8fIyQz+V9gPE9Z7PzcuMD2b1sgLxMnHnuXVSPdb8DZ+Knzl08rvk8ECKKqhk4OeSH5dEjRDbUgMM
|
||||
Tgkol04+4Wp6S+7hgxpzZqJdfsb4nHiSV/95jAOyN1ezh+AykdmjlXS6V0p4NrQuoujCbFn2KeqwhLj/
|
||||
byqoX4A6X4toTUZjg4+PgJr3TieJ2vSEPTL5j6jfqDI6frQaTZzzRKz8Mol5JI4zmcHckXLRLnoJf6Hx
|
||||
ebgLG1xSU37M+WOve1MRjwFiO3pUBHJbGEWGlBtRbOY/W5alNFS/206ac2C8YZK/bgcTjRf7WVCJ72+y
|
||||
utlSQzIiY43e+aWfR42dkNyDdIwrwnx3w3stOvEZCa7CCNwHSCHdV5WsVfFDqcPac6+rQFq+hMDB4C1D
|
||||
CEgn2VV7Y1Sn35Gl7h90GZHRr0dei4N0qN0jM5NevdyLVYVEyU8XeZAUuY7yP1ZhExBFZllVuwOhbu6v
|
||||
2CnOhTdyXY/NKRYl0eqNgZeIMg6VMgO8nE27nR5XJaPIUcTdyoFLSXPjIfdPCbeKSk16hGmq+N2xfF0t
|
||||
8tkwTTAxMA0GCWCGSAFlAwQCAQUABCClumOxCp5GRbcwwR9luMgQJ8ktlYmxQzrK8VHftiuoEAQUFqd9
|
||||
N6VjWLZbEYq1VlM8QpdcaaoCAggA
|
||||
""";
|
||||
private static final String KEYSTORE_PASSWORD = "test123";
|
||||
|
||||
private static final Instant EDDSA_EXPIRATION = Instant.ofEpochSecond(4897215163L);
|
||||
private static final Instant RSA_EXPIRATION = Instant.ofEpochSecond(4897215160L);
|
||||
|
||||
@Test
|
||||
void test() throws Exception {
|
||||
try (Resource keystore = TestResource.fromBase64Mime("keystore", KEYSTORE_BASE64)) {
|
||||
|
||||
final KeyStore keyStore = CertificateUtils.getKeyStore(keystore, "PKCS12", null, KEYSTORE_PASSWORD);
|
||||
|
||||
final Map<String, Instant> expected = Map.of(
|
||||
"localhost:EdDSA", EDDSA_EXPIRATION,
|
||||
"localhost:RSA", RSA_EXPIRATION);
|
||||
assertEquals(expected, TlsCertificateExpirationUtil.getIdentifiersAndExpirations(keyStore, KEYSTORE_PASSWORD));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+4
-1
@@ -16,6 +16,7 @@ import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
@@ -46,7 +47,9 @@ class UserAgentTagUtilTest {
|
||||
Arguments.of("Signal-Android/4.68.3.0-bobsbootlegclient", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "android")),
|
||||
Arguments.of("Signal-Desktop/1.22.45-foo-0", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal-Desktop/1.34.5-beta.1-fakeclientemporium", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of("Signal-Desktop/1.32.0-beta.3", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop"))
|
||||
Arguments.of("Signal-Desktop/1.32.0-beta.3", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "desktop")),
|
||||
Arguments.of(UserAgentTagUtil.SERVER_UA, Tag.of(UserAgentTagUtil.PLATFORM_TAG, "server")),
|
||||
Arguments.of("Signal-Server/1.2.3 (" + UUID.randomUUID() + ")", Tag.of(UserAgentTagUtil.PLATFORM_TAG, "unrecognized"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+196
-35
@@ -18,10 +18,12 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -30,12 +32,22 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.InvalidMessageException;
|
||||
import org.signal.libsignal.protocol.InvalidVersionException;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MultiRecipientMessageHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestRecipient;
|
||||
|
||||
class MessageSenderTest {
|
||||
|
||||
@@ -60,7 +72,9 @@ class MessageSenderTest {
|
||||
final boolean expectPushNotificationAttempt = !clientPresent && !ephemeral;
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 17;
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
@@ -71,7 +85,11 @@ class MessageSenderTest {
|
||||
|
||||
when(account.getUuid()).thenReturn(accountIdentifier);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true);
|
||||
when(account.getDevices()).thenReturn(List.of(device));
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getRegistrationId()).thenReturn(registrationId);
|
||||
|
||||
if (hasPushToken) {
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
@@ -82,7 +100,11 @@ class MessageSenderTest {
|
||||
|
||||
when(messagesManager.insert(any(), any())).thenReturn(Map.of(deviceId, clientPresent));
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMessages(account, Map.of(device.getId(), message)));
|
||||
assertDoesNotThrow(() -> messageSender.sendMessages(account,
|
||||
serviceIdentifier,
|
||||
Map.of(device.getId(), message),
|
||||
Map.of(device.getId(), registrationId),
|
||||
null));
|
||||
|
||||
final MessageProtos.Envelope expectedMessage = ephemeral
|
||||
? message.toBuilder().setEphemeral(true).build()
|
||||
@@ -97,23 +119,62 @@ class MessageSenderTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendMessageMismatchedDevices() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 17;
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final MessageProtos.Envelope message = MessageProtos.Envelope.newBuilder().build();
|
||||
|
||||
when(account.getUuid()).thenReturn(accountIdentifier);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true);
|
||||
when(account.getDevices()).thenReturn(List.of(device));
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getRegistrationId()).thenReturn(registrationId);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
final MismatchedDevicesException mismatchedDevicesException =
|
||||
assertThrows(MismatchedDevicesException.class, () -> messageSender.sendMessages(account,
|
||||
serviceIdentifier,
|
||||
Map.of(device.getId(), message),
|
||||
Map.of(device.getId(), registrationId + 1),
|
||||
null));
|
||||
|
||||
assertEquals(new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of(deviceId)),
|
||||
mismatchedDevicesException.getMismatchedDevices());
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void sendMultiRecipientMessage(@CartesianTest.Values(booleans = {true, false}) final boolean clientPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean hasPushToken) throws NotPushRegisteredException {
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean hasPushToken)
|
||||
throws NotPushRegisteredException, InvalidMessageException, InvalidVersionException {
|
||||
|
||||
final boolean expectPushNotificationAttempt = !clientPresent && !ephemeral;
|
||||
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 17;
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
when(account.getUuid()).thenReturn(accountIdentifier);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true);
|
||||
when(account.getDevices()).thenReturn(List.of(device));
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getRegistrationId()).thenReturn(registrationId);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
if (hasPushToken) {
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
@@ -125,12 +186,20 @@ class MessageSenderTest {
|
||||
when(messagesManager.insertMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Map.of(account, Map.of(deviceId, clientPresent))));
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMultiRecipientMessage(mock(SealedSenderMultiRecipientMessage.class),
|
||||
Collections.emptyMap(),
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
ephemeral,
|
||||
urgent)
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage =
|
||||
SealedSenderMultiRecipientMessage.parse(MultiRecipientMessageHelper.generateMultiRecipientMessage(
|
||||
List.of(new TestRecipient(serviceIdentifier, deviceId, registrationId, new byte[48]))));
|
||||
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient =
|
||||
multiRecipientMessage.getRecipients().values().iterator().next();
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMultiRecipientMessage(multiRecipientMessage,
|
||||
Map.of(recipient, account),
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
ephemeral,
|
||||
urgent,
|
||||
null)
|
||||
.join());
|
||||
|
||||
if (expectPushNotificationAttempt) {
|
||||
@@ -140,39 +209,48 @@ class MessageSenderTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getDeliveryChannelName(final Device device, final String expectedChannelName) {
|
||||
assertEquals(expectedChannelName, MessageSender.getDeliveryChannelName(device));
|
||||
}
|
||||
@Test
|
||||
void sendMultiRecipientMessageMismatchedDevices() throws InvalidMessageException, InvalidVersionException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 17;
|
||||
|
||||
private static List<Arguments> getDeliveryChannelName() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
{
|
||||
final Device apnDevice = mock(Device.class);
|
||||
when(apnDevice.getApnId()).thenReturn("apns-token");
|
||||
when(account.getUuid()).thenReturn(accountIdentifier);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.isIdentifiedBy(serviceIdentifier)).thenReturn(true);
|
||||
when(account.getDevices()).thenReturn(List.of(device));
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getRegistrationId()).thenReturn(registrationId);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(apnDevice, "apn"));
|
||||
}
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage =
|
||||
SealedSenderMultiRecipientMessage.parse(MultiRecipientMessageHelper.generateMultiRecipientMessage(
|
||||
List.of(new TestRecipient(serviceIdentifier, deviceId, registrationId + 1, new byte[48]))));
|
||||
|
||||
{
|
||||
final Device fcmDevice = mock(Device.class);
|
||||
when(fcmDevice.getGcmId()).thenReturn("fcm-token");
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient =
|
||||
multiRecipientMessage.getRecipients().values().iterator().next();
|
||||
|
||||
arguments.add(Arguments.of(fcmDevice, "gcm"));
|
||||
}
|
||||
when(messagesManager.insertMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Map.of(account, Map.of(deviceId, true))));
|
||||
|
||||
{
|
||||
final Device fetchesMessagesDevice = mock(Device.class);
|
||||
when(fetchesMessagesDevice.getFetchesMessages()).thenReturn(true);
|
||||
final MultiRecipientMismatchedDevicesException mismatchedDevicesException =
|
||||
assertThrows(MultiRecipientMismatchedDevicesException.class,
|
||||
() -> messageSender.sendMultiRecipientMessage(multiRecipientMessage,
|
||||
Map.of(recipient, account),
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
null)
|
||||
.join());
|
||||
|
||||
arguments.add(Arguments.of(fetchesMessagesDevice, "websocket"));
|
||||
}
|
||||
|
||||
arguments.add(Arguments.of(mock(Device.class), "none"));
|
||||
|
||||
return arguments;
|
||||
assertEquals(Map.of(serviceIdentifier, new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of(deviceId))),
|
||||
mismatchedDevicesException.getMismatchedDevicesByServiceIdentifier());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -183,4 +261,87 @@ class MessageSenderTest {
|
||||
assertDoesNotThrow(() ->
|
||||
MessageSender.validateContentLength(MessageSender.MAX_MESSAGE_SIZE, false, false, false, null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getMismatchedDevices(final Account account,
|
||||
final ServiceIdentifier serviceIdentifier,
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId,
|
||||
final byte excludedDeviceId,
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<MismatchedDevices> expectedMismatchedDevices) {
|
||||
|
||||
assertEquals(expectedMismatchedDevices,
|
||||
MessageSender.getMismatchedDevices(account, serviceIdentifier, registrationIdsByDeviceId, excludedDeviceId));
|
||||
}
|
||||
|
||||
private static List<Arguments> getMismatchedDevices() {
|
||||
final byte primaryDeviceId = Device.PRIMARY_ID;
|
||||
final byte linkedDeviceId = primaryDeviceId + 1;
|
||||
final byte extraDeviceId = linkedDeviceId + 1;
|
||||
|
||||
final int primaryDeviceAciRegistrationId = 2;
|
||||
final int primaryDevicePniRegistrationId = 3;
|
||||
final int linkedDeviceAciRegistrationId = 5;
|
||||
final int linkedDevicePniRegistrationId = 7;
|
||||
|
||||
final Device primaryDevice = mock(Device.class);
|
||||
when(primaryDevice.getId()).thenReturn(primaryDeviceId);
|
||||
when(primaryDevice.getRegistrationId()).thenReturn(primaryDeviceAciRegistrationId);
|
||||
when(primaryDevice.getPhoneNumberIdentityRegistrationId()).thenReturn(OptionalInt.of(primaryDevicePniRegistrationId));
|
||||
|
||||
final Device linkedDevice = mock(Device.class);
|
||||
when(linkedDevice.getId()).thenReturn(linkedDeviceId);
|
||||
when(linkedDevice.getRegistrationId()).thenReturn(linkedDeviceAciRegistrationId);
|
||||
when(linkedDevice.getPhoneNumberIdentityRegistrationId()).thenReturn(OptionalInt.of(linkedDevicePniRegistrationId));
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice));
|
||||
when(account.getDevice(anyByte())).thenReturn(Optional.empty());
|
||||
when(account.getDevice(primaryDeviceId)).thenReturn(Optional.of(primaryDevice));
|
||||
when(account.getDevice(linkedDeviceId)).thenReturn(Optional.of(linkedDevice));
|
||||
|
||||
final AciServiceIdentifier aciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final PniServiceIdentifier pniServiceIdentifier = new PniServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("Complete device list for ACI, no devices excluded",
|
||||
account,
|
||||
aciServiceIdentifier,
|
||||
Map.of(
|
||||
primaryDeviceId, primaryDeviceAciRegistrationId,
|
||||
linkedDeviceId, linkedDeviceAciRegistrationId
|
||||
),
|
||||
MessageSender.NO_EXCLUDED_DEVICE_ID,
|
||||
Optional.empty()),
|
||||
|
||||
Arguments.argumentSet("Complete device list for PNI, no devices excluded",
|
||||
account,
|
||||
pniServiceIdentifier,
|
||||
Map.of(
|
||||
primaryDeviceId, primaryDevicePniRegistrationId,
|
||||
linkedDeviceId, linkedDevicePniRegistrationId
|
||||
),
|
||||
MessageSender.NO_EXCLUDED_DEVICE_ID,
|
||||
Optional.empty()),
|
||||
|
||||
Arguments.argumentSet("Complete device list, device excluded",
|
||||
account,
|
||||
aciServiceIdentifier,
|
||||
Map.of(
|
||||
linkedDeviceId, linkedDeviceAciRegistrationId
|
||||
),
|
||||
primaryDeviceId,
|
||||
Optional.empty()),
|
||||
|
||||
Arguments.argumentSet("Mismatched devices",
|
||||
account,
|
||||
aciServiceIdentifier,
|
||||
Map.of(
|
||||
linkedDeviceId, linkedDeviceAciRegistrationId + 1,
|
||||
extraDeviceId, 17
|
||||
),
|
||||
MessageSender.NO_EXCLUDED_DEVICE_ID,
|
||||
Optional.of(new MismatchedDevices(Set.of(primaryDeviceId), Set.of(extraDeviceId), Set.of(linkedDeviceId))))
|
||||
);
|
||||
}
|
||||
}
|
||||
+46
@@ -60,10 +60,12 @@ import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
@@ -76,6 +78,7 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
@@ -1705,4 +1708,47 @@ class AccountsManagerTest {
|
||||
Arguments.of("e552603a-1492-4de6-872d-bac19a2825b4.1691096565171:This is not valid base64", tokenTimestamp)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void validateCompleteDeviceList(final Account account, final Set<Byte> deviceIds, @Nullable final MismatchedDevicesException expectedException) {
|
||||
final Executable validateCompleteDeviceListExecutable =
|
||||
() -> AccountsManager.validateCompleteDeviceList(account, deviceIds);
|
||||
|
||||
if (expectedException != null) {
|
||||
final MismatchedDevicesException caughtException =
|
||||
assertThrows(MismatchedDevicesException.class, validateCompleteDeviceListExecutable);
|
||||
|
||||
assertEquals(expectedException.getMismatchedDevices(), caughtException.getMismatchedDevices());
|
||||
} else {
|
||||
assertDoesNotThrow(validateCompleteDeviceListExecutable);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Arguments> validateCompleteDeviceList() {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final byte extraDeviceId = deviceId + 1;
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getDevices()).thenReturn(List.of(device));
|
||||
|
||||
return List.of(
|
||||
Arguments.of(account, Set.of(deviceId), null),
|
||||
|
||||
Arguments.of(account, Set.of(deviceId, extraDeviceId),
|
||||
new MismatchedDevicesException(
|
||||
new MismatchedDevices(Collections.emptySet(), Set.of(extraDeviceId), Collections.emptySet()))),
|
||||
|
||||
Arguments.of(account, Collections.emptySet(),
|
||||
new MismatchedDevicesException(
|
||||
new MismatchedDevices(Set.of(deviceId), Collections.emptySet(), Collections.emptySet()))),
|
||||
|
||||
Arguments.of(account, Set.of(extraDeviceId),
|
||||
new MismatchedDevicesException(
|
||||
new MismatchedDevices(Set.of(deviceId), Set.of((byte) (extraDeviceId)), Collections.emptySet())))
|
||||
);
|
||||
}
|
||||
}
|
||||
+7
-85
@@ -31,8 +31,6 @@ import org.mockito.stubbing.Answer;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
@@ -105,7 +103,7 @@ public class ChangeNumberManagerTest {
|
||||
changeNumberManager.changeNumber(account, "+18025551234", null, null, null, null, null, null);
|
||||
verify(accountsManager).changeNumber(account, "+18025551234", null, null, null, null);
|
||||
verify(accountsManager, never()).updateDevice(any(), anyByte(), any());
|
||||
verify(messageSender, never()).sendMessages(eq(account), any());
|
||||
verify(messageSender, never()).sendMessages(eq(account), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -119,7 +117,7 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
changeNumberManager.changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyList(), Collections.emptyMap(), null);
|
||||
verify(accountsManager).changeNumber(account, "+18025551234", pniIdentityKey, prekeys, null, Collections.emptyMap());
|
||||
verify(messageSender, never()).sendMessages(eq(account), any());
|
||||
verify(messageSender, never()).sendMessages(eq(account), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -159,7 +157,7 @@ public class ChangeNumberManagerTest {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), envelopeCaptor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
@@ -212,7 +210,7 @@ public class ChangeNumberManagerTest {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), envelopeCaptor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
@@ -263,7 +261,7 @@ public class ChangeNumberManagerTest {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), envelopeCaptor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
@@ -310,7 +308,7 @@ public class ChangeNumberManagerTest {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), envelopeCaptor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
@@ -359,7 +357,7 @@ public class ChangeNumberManagerTest {
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Map<Byte, MessageProtos.Envelope>> envelopeCaptor =
|
||||
ArgumentCaptor.forClass(Map.class);
|
||||
|
||||
verify(messageSender).sendMessages(any(), envelopeCaptor.capture());
|
||||
verify(messageSender).sendMessages(any(), any(), envelopeCaptor.capture(), any(), any());
|
||||
|
||||
assertEquals(1, envelopeCaptor.getValue().size());
|
||||
assertEquals(Set.of(deviceId2), envelopeCaptor.getValue().keySet());
|
||||
@@ -372,82 +370,6 @@ public class ChangeNumberManagerTest {
|
||||
assertFalse(updatedPhoneNumberIdentifiersByAccount.containsKey(account));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberMismatchedRegistrationId() {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
|
||||
final List<Device> devices = new ArrayList<>();
|
||||
|
||||
for (byte i = 1; i <= 3; i++) {
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(i);
|
||||
when(device.getRegistrationId()).thenReturn((int) i);
|
||||
|
||||
devices.add(device);
|
||||
when(account.getDevice(i)).thenReturn(Optional.of(device));
|
||||
}
|
||||
|
||||
when(account.getDevices()).thenReturn(devices);
|
||||
|
||||
final byte destinationDeviceId2 = 2;
|
||||
final byte destinationDeviceId3 = 3;
|
||||
final List<IncomingMessage> messages = List.of(
|
||||
new IncomingMessage(1, destinationDeviceId2, 1, "foo".getBytes(StandardCharsets.UTF_8)),
|
||||
new IncomingMessage(1, destinationDeviceId3, 1, "foo".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
final ECPublicKey pniIdentityKey = pniIdentityKeyPair.getPublicKey();
|
||||
|
||||
final Map<Byte, ECSignedPreKey> preKeys = Map.of(Device.PRIMARY_ID,
|
||||
KeysHelper.signedECPreKey(1, pniIdentityKeyPair),
|
||||
destinationDeviceId2, KeysHelper.signedECPreKey(2, pniIdentityKeyPair),
|
||||
destinationDeviceId3, KeysHelper.signedECPreKey(3, pniIdentityKeyPair));
|
||||
final Map<Byte, Integer> registrationIds = Map.of(Device.PRIMARY_ID, 17, destinationDeviceId2, 47,
|
||||
destinationDeviceId3, 89);
|
||||
|
||||
assertThrows(StaleDevicesException.class,
|
||||
() -> changeNumberManager.changeNumber(account, "+18005559876", new IdentityKey(Curve.generateKeyPair().getPublicKey()), preKeys, null, messages, registrationIds, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePniKeysMismatchedRegistrationId() {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
|
||||
final List<Device> devices = new ArrayList<>();
|
||||
|
||||
for (byte i = 1; i <= 3; i++) {
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(i);
|
||||
when(device.getRegistrationId()).thenReturn((int) i);
|
||||
|
||||
devices.add(device);
|
||||
when(account.getDevice(i)).thenReturn(Optional.of(device));
|
||||
}
|
||||
|
||||
when(account.getDevices()).thenReturn(devices);
|
||||
|
||||
final byte destinationDeviceId2 = 2;
|
||||
final byte destinationDeviceId3 = 3;
|
||||
final List<IncomingMessage> messages = List.of(
|
||||
new IncomingMessage(1, destinationDeviceId2, 1, "foo".getBytes(StandardCharsets.UTF_8)),
|
||||
new IncomingMessage(1, destinationDeviceId3, 1, "foo".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
final ECPublicKey pniIdentityKey = pniIdentityKeyPair.getPublicKey();
|
||||
|
||||
final Map<Byte, ECSignedPreKey> preKeys = Map.of(Device.PRIMARY_ID,
|
||||
KeysHelper.signedECPreKey(1, pniIdentityKeyPair),
|
||||
destinationDeviceId2, KeysHelper.signedECPreKey(2, pniIdentityKeyPair),
|
||||
destinationDeviceId3, KeysHelper.signedECPreKey(3, pniIdentityKeyPair));
|
||||
final Map<Byte, Integer> registrationIds = Map.of(Device.PRIMARY_ID, 17, destinationDeviceId2, 47,
|
||||
destinationDeviceId3, 89);
|
||||
|
||||
assertThrows(StaleDevicesException.class,
|
||||
() -> changeNumberManager.updatePniKeys(account, new IdentityKey(Curve.generateKeyPair().getPublicKey()), preKeys, null, messages, registrationIds, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberMissingData() {
|
||||
final Account account = mock(Account.class);
|
||||
|
||||
-273
@@ -1,273 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.params.provider.Arguments.arguments;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.StaleDevicesException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class DestinationDeviceValidatorTest {
|
||||
|
||||
static Account mockAccountWithDeviceAndRegId(final Map<Byte, Integer> registrationIdsByDeviceId) {
|
||||
final Account account = mock(Account.class);
|
||||
|
||||
registrationIdsByDeviceId.forEach((deviceId, registrationId) -> {
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getRegistrationId()).thenReturn(registrationId);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
});
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
static Stream<Arguments> validateRegistrationIdsSource() {
|
||||
final byte id1 = 1;
|
||||
final byte id2 = 2;
|
||||
final byte id3 = 3;
|
||||
return Stream.of(
|
||||
arguments(
|
||||
mockAccountWithDeviceAndRegId(Map.of(id1, 0xFFFF, id2, 0xDEAD, id3, 0xBEEF)),
|
||||
Map.of(id1, 0xFFFF, id2, 0xDEAD, id3, 0xBEEF),
|
||||
null),
|
||||
arguments(
|
||||
mockAccountWithDeviceAndRegId(Map.of(id1, 42)),
|
||||
Map.of(id1, 1492),
|
||||
Set.of(id1)),
|
||||
arguments(
|
||||
mockAccountWithDeviceAndRegId(Map.of(id1, 42)),
|
||||
Map.of(id1, 42),
|
||||
null),
|
||||
arguments(
|
||||
mockAccountWithDeviceAndRegId(Map.of(id1, 42)),
|
||||
Map.of(id1, 0),
|
||||
null),
|
||||
arguments(
|
||||
mockAccountWithDeviceAndRegId(Map.of(id1, 42, id2, 255)),
|
||||
Map.of(id1, 0, id2, 42),
|
||||
Set.of(id2)),
|
||||
arguments(
|
||||
mockAccountWithDeviceAndRegId(Map.of(id1, 42, id2, 256)),
|
||||
Map.of(id1, 41, id2, 257),
|
||||
Set.of(id1, id2))
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("validateRegistrationIdsSource")
|
||||
void testValidateRegistrationIds(
|
||||
Account account,
|
||||
Map<Byte, Integer> registrationIdsByDeviceId,
|
||||
Set<Byte> expectedStaleDeviceIds) throws Exception {
|
||||
if (expectedStaleDeviceIds != null) {
|
||||
Assertions.assertThat(assertThrows(StaleDevicesException.class,
|
||||
() -> DestinationDeviceValidator.validateRegistrationIds(
|
||||
account,
|
||||
registrationIdsByDeviceId.entrySet(),
|
||||
Map.Entry::getKey,
|
||||
Map.Entry::getValue,
|
||||
false))
|
||||
.getStaleDevices())
|
||||
.hasSameElementsAs(expectedStaleDeviceIds);
|
||||
} else {
|
||||
DestinationDeviceValidator.validateRegistrationIds(account, registrationIdsByDeviceId.entrySet(),
|
||||
Map.Entry::getKey, Map.Entry::getValue, false);
|
||||
}
|
||||
}
|
||||
|
||||
static Account mockAccountWithDeviceAndEnabled(final Map<Byte, Boolean> enabledStateByDeviceId) {
|
||||
final Account account = mock(Account.class);
|
||||
final List<Device> devices = new ArrayList<>();
|
||||
|
||||
enabledStateByDeviceId.forEach((deviceId, enabled) -> {
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
|
||||
devices.add(device);
|
||||
});
|
||||
|
||||
when(account.getDevices()).thenReturn(devices);
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
static Stream<Arguments> validateCompleteDeviceList() {
|
||||
final byte id1 = 1;
|
||||
final byte id2 = 2;
|
||||
final byte id3 = 3;
|
||||
|
||||
final Account account = mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true));
|
||||
|
||||
return Stream.of(
|
||||
// Device IDs provided for all enabled devices
|
||||
arguments(
|
||||
account,
|
||||
Set.of(id1, id3),
|
||||
Set.of(id2),
|
||||
null,
|
||||
Collections.emptySet()),
|
||||
|
||||
// Device ID provided for disabled device
|
||||
arguments(
|
||||
account,
|
||||
Set.of(id1, id2, id3),
|
||||
null,
|
||||
null,
|
||||
Collections.emptySet()),
|
||||
|
||||
// Device ID omitted for enabled device
|
||||
arguments(
|
||||
account,
|
||||
Set.of(id1),
|
||||
Set.of(id2, id3),
|
||||
null,
|
||||
Collections.emptySet()),
|
||||
|
||||
// Device ID included for disabled device, omitted for enabled device
|
||||
arguments(
|
||||
account,
|
||||
Set.of(id1, id2),
|
||||
Set.of(id3),
|
||||
null,
|
||||
Collections.emptySet()),
|
||||
|
||||
// Device ID omitted for enabled device, included for device in excluded list
|
||||
arguments(
|
||||
account,
|
||||
Set.of(id1),
|
||||
Set.of(id2, id3),
|
||||
Set.of(id1),
|
||||
Set.of(id1)
|
||||
),
|
||||
|
||||
// Device ID omitted for enabled device, included for disabled device, omitted for excluded device
|
||||
arguments(
|
||||
account,
|
||||
Set.of(id2),
|
||||
Set.of(id3),
|
||||
null,
|
||||
Set.of(id1)
|
||||
),
|
||||
|
||||
// Device ID included for enabled device, omitted for excluded device
|
||||
arguments(
|
||||
account,
|
||||
Set.of(id3),
|
||||
Set.of(id2),
|
||||
null,
|
||||
Set.of(id1)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void validateCompleteDeviceList(
|
||||
Account account,
|
||||
Set<Byte> deviceIds,
|
||||
Collection<Byte> expectedMissingDeviceIds,
|
||||
Collection<Byte> expectedExtraDeviceIds,
|
||||
Set<Byte> excludedDeviceIds) throws Exception {
|
||||
|
||||
if (expectedMissingDeviceIds != null || expectedExtraDeviceIds != null) {
|
||||
final MismatchedDevicesException mismatchedDevicesException = assertThrows(MismatchedDevicesException.class,
|
||||
() -> DestinationDeviceValidator.validateCompleteDeviceList(account, deviceIds, excludedDeviceIds));
|
||||
if (expectedMissingDeviceIds != null) {
|
||||
Assertions.assertThat(mismatchedDevicesException.getMissingDevices())
|
||||
.hasSameElementsAs(expectedMissingDeviceIds);
|
||||
}
|
||||
if (expectedExtraDeviceIds != null) {
|
||||
Assertions.assertThat(mismatchedDevicesException.getExtraDevices()).hasSameElementsAs(expectedExtraDeviceIds);
|
||||
}
|
||||
} else {
|
||||
DestinationDeviceValidator.validateCompleteDeviceList(account, deviceIds, excludedDeviceIds);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDuplicateDeviceIds() {
|
||||
final Account account = mockAccountWithDeviceAndRegId(Map.of(Device.PRIMARY_ID, 17));
|
||||
try {
|
||||
DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, 16), new Pair<>(Device.PRIMARY_ID, 17)), false);
|
||||
Assertions.fail("duplicate devices should throw StaleDevicesException");
|
||||
} catch (StaleDevicesException e) {
|
||||
Assertions.assertThat(e.getStaleDevices()).hasSameElementsAs(Collections.singletonList(Device.PRIMARY_ID));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidatePniRegistrationIds() {
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getDevices()).thenReturn(List.of(device));
|
||||
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
final int aciRegistrationId = 17;
|
||||
final int pniRegistrationId = 89;
|
||||
final int incorrectRegistrationId = aciRegistrationId + pniRegistrationId;
|
||||
|
||||
when(device.getRegistrationId()).thenReturn(aciRegistrationId);
|
||||
when(device.getPhoneNumberIdentityRegistrationId()).thenReturn(OptionalInt.of(pniRegistrationId));
|
||||
|
||||
assertDoesNotThrow(
|
||||
() -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, aciRegistrationId)), false));
|
||||
assertDoesNotThrow(
|
||||
() -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, pniRegistrationId)),
|
||||
true));
|
||||
assertThrows(StaleDevicesException.class,
|
||||
() -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, aciRegistrationId)),
|
||||
true));
|
||||
assertThrows(StaleDevicesException.class,
|
||||
() -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, pniRegistrationId)),
|
||||
false));
|
||||
|
||||
when(device.getPhoneNumberIdentityRegistrationId()).thenReturn(OptionalInt.empty());
|
||||
|
||||
assertDoesNotThrow(
|
||||
() -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, aciRegistrationId)),
|
||||
false));
|
||||
assertDoesNotThrow(
|
||||
() -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, aciRegistrationId)),
|
||||
true));
|
||||
assertThrows(StaleDevicesException.class, () -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, incorrectRegistrationId)), true));
|
||||
assertThrows(StaleDevicesException.class, () -> DestinationDeviceValidator.validateRegistrationIds(account,
|
||||
Stream.of(new Pair<>(Device.PRIMARY_ID, incorrectRegistrationId)), false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util.jetty;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.util.Base64;
|
||||
import org.eclipse.jetty.util.resource.Resource;
|
||||
|
||||
public class TestResource extends Resource {
|
||||
|
||||
private final String name;
|
||||
private final byte[] data;
|
||||
|
||||
private TestResource(String name, byte[] data) {
|
||||
this.name = name;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static Resource fromBase64Mime(String name, String base64) {
|
||||
return new TestResource(name, Base64.getMimeDecoder().decode(base64));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isContainedIn(final Resource r) throws MalformedURLException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirectory() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long lastModified() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long length() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public URI getURI() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() throws IOException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReadableByteChannel getReadableByteChannel() throws IOException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete() throws SecurityException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean renameTo(final Resource dest) throws SecurityException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] list() {
|
||||
return new String[]{name};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Resource addPath(final String path) throws IOException, MalformedURLException {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule spam-filter updated: 4f2af0f059...8f566196d7.
Reference in new issue
Block a user