mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 12:06:53 +00:00
Retire string-based service identifiers/UUIDs in Envelope entities
This commit is contained in:
1 parent
4a9302033a
commit
f524d9fb25
56 files changed
+328
-580
No files matched your search
@@ -509,7 +509,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getMessages().getTableName(),
|
||||
config.getDynamoDbTables().getMessages().getExpiration(),
|
||||
messageDeletionAsyncExecutor, experimentEnrollmentManager);
|
||||
messageDeletionAsyncExecutor);
|
||||
RemoteConfigs remoteConfigs = new RemoteConfigs(dynamoDbClient,
|
||||
config.getDynamoDbTables().getRemoteConfig().getTableName());
|
||||
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
|
||||
@@ -700,7 +700,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock, experimentEnrollmentManager);
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock);
|
||||
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
|
||||
recurringJobExecutor,
|
||||
config.getClientReleaseConfiguration().refreshInterval(),
|
||||
|
||||
+2
-2
@@ -50,7 +50,7 @@ public record IncomingMessage(int type,
|
||||
.setType(MessageProtos.Envelope.Type.forNumber(type))
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(clock.millis())
|
||||
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
|
||||
.setDestinationServiceId(destinationIdentifier.toCompactByteString())
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent);
|
||||
|
||||
@@ -61,7 +61,7 @@ public record IncomingMessage(int type,
|
||||
|
||||
if (sourceServiceIdentifier != null && sourceDeviceId != null) {
|
||||
envelopeBuilder
|
||||
.setSourceServiceId(sourceServiceIdentifier.toServiceIdentifierString())
|
||||
.setSourceServiceId(sourceServiceIdentifier.toCompactByteString())
|
||||
.setSourceDevice(sourceDeviceId.intValue());
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final ServiceIdentifier serviceIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
|
||||
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getCheckAccountExistenceLimiter());
|
||||
|
||||
@@ -55,7 +55,7 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
|
||||
|
||||
return accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray()).join()
|
||||
.map(account -> LookupUsernameHashResponse.newBuilder()
|
||||
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.build())
|
||||
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
+2
-3
@@ -13,7 +13,6 @@ import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import org.signal.chat.account.ClearRegistrationLockRequest;
|
||||
import org.signal.chat.account.ClearRegistrationLockResponse;
|
||||
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
|
||||
@@ -88,8 +87,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
|
||||
+2
-12
@@ -5,17 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ServiceIdentifierUtil {
|
||||
public class GrpcServiceIdentifierUtil {
|
||||
|
||||
private ServiceIdentifierUtil() {
|
||||
private GrpcServiceIdentifierUtil() {
|
||||
}
|
||||
|
||||
public static ServiceIdentifier fromGrpcServiceIdentifier(final org.signal.chat.common.ServiceIdentifier serviceIdentifier) {
|
||||
@@ -42,12 +40,4 @@ public class ServiceIdentifierUtil {
|
||||
.setUuid(UUIDUtil.toByteString(serviceIdentifier.uuid()))
|
||||
.build();
|
||||
}
|
||||
|
||||
public static ByteString toCompactByteString(final ServiceIdentifier serviceIdentifier) {
|
||||
return ByteString.copyFrom(serviceIdentifier.toCompactByteArray());
|
||||
}
|
||||
|
||||
public static ServiceIdentifier fromByteString(final ByteString byteString) {
|
||||
return ServiceIdentifier.fromBytes(byteString.toByteArray());
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -13,7 +13,6 @@ import java.util.Arrays;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.keys.AccountPreKeyBundles;
|
||||
import org.signal.chat.keys.CheckIdentityKeyRequest;
|
||||
import org.signal.chat.keys.CheckIdentityKeyResponse;
|
||||
import org.signal.chat.keys.GetPreKeysAnonymousRequest;
|
||||
@@ -46,7 +45,7 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
@Override
|
||||
public GetPreKeysAnonymousResponse getPreKeys(final GetPreKeysAnonymousRequest request) {
|
||||
final ServiceIdentifier serviceIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
|
||||
|
||||
final byte deviceId = request.getRequest().hasDeviceId()
|
||||
? DeviceIdUtil.validate(request.getRequest().getDeviceId())
|
||||
@@ -91,7 +90,7 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
@Override
|
||||
public Flow.Publisher<CheckIdentityKeyResponse> checkIdentityKeys(final Flow.Publisher<CheckIdentityKeyRequest> requests) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(requests)
|
||||
.map(request -> Tuples.of(ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
|
||||
.map(request -> Tuples.of(GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
|
||||
request.getFingerprint().toByteArray()))
|
||||
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
|
||||
@@ -100,7 +99,7 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
.identityType()), serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(account -> CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetIdentifier(
|
||||
ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
|
||||
.identityType()).serialize()))
|
||||
.build())));
|
||||
|
||||
@@ -96,7 +96,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
|
||||
|
||||
|
||||
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
+6
-7
@@ -6,19 +6,18 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.Status;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.messages.IndividualRecipientMessageBundle;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.chat.messages.MultiRecipientMismatchedDevices;
|
||||
import org.signal.chat.messages.MultiRecipientSuccess;
|
||||
import org.signal.chat.messages.SendMessageResponse;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.chat.messages.SendMultiRecipientMessageRequest;
|
||||
import org.signal.chat.messages.SendMultiRecipientMessageResponse;
|
||||
import org.signal.chat.messages.SendMultiRecipientStoryRequest;
|
||||
@@ -85,7 +84,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final ServiceIdentifier destinationServiceIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
|
||||
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
|
||||
|
||||
@@ -133,7 +132,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final ServiceIdentifier destinationServiceIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
|
||||
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
|
||||
|
||||
@@ -194,7 +193,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
.setType(MessageProtos.Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(messages.getTimestamp())
|
||||
.setServerTimestamp(clock.millis())
|
||||
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
|
||||
.setDestinationServiceId(destinationServiceIdentifier.toCompactByteString())
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent)
|
||||
.setContent(entry.getValue().getPayload());
|
||||
@@ -313,7 +312,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
final MultiRecipientSuccess.Builder responseBuilder = MultiRecipientSuccess.newBuilder();
|
||||
|
||||
MessageUtil.getUnresolvedRecipients(multiRecipientMessage, resolvedRecipients).stream()
|
||||
.map(ServiceIdentifierUtil::toGrpcServiceIdentifier)
|
||||
.map(GrpcServiceIdentifierUtil::toGrpcServiceIdentifier)
|
||||
.forEach(responseBuilder::addUnresolvedRecipients);
|
||||
|
||||
return SendMultiRecipientMessageResponse.newBuilder().setSuccess(responseBuilder).build();
|
||||
|
||||
@@ -23,7 +23,7 @@ public class MessagesGrpcHelper {
|
||||
final org.whispersystems.textsecuregcm.controllers.MismatchedDevices mismatchedDevices) {
|
||||
|
||||
final MismatchedDevices.Builder mismatchedDevicesBuilder = MismatchedDevices.newBuilder()
|
||||
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier));
|
||||
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier));
|
||||
|
||||
mismatchedDevices.missingDeviceIds().forEach(mismatchedDevicesBuilder::addMissingDevices);
|
||||
mismatchedDevices.extraDeviceIds().forEach(mismatchedDevicesBuilder::addExtraDevices);
|
||||
|
||||
+3
-3
@@ -76,7 +76,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
final ServiceIdentifier destinationServiceIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
|
||||
if (sender.isIdentifiedBy(destinationServiceIdentifier)) {
|
||||
throw GrpcExceptions.invalidArguments("use `sendSyncMessage` to send messages to own account");
|
||||
@@ -159,8 +159,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
|
||||
.setType(getEnvelopeType(entry.getValue().getType()))
|
||||
.setClientTimestamp(messages.getTimestamp())
|
||||
.setServerTimestamp(clock.millis())
|
||||
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
|
||||
.setSourceServiceId(new AciServiceIdentifier(sender.accountIdentifier()).toServiceIdentifierString())
|
||||
.setDestinationServiceId(destinationServiceIdentifier.toCompactByteString())
|
||||
.setSourceServiceId(new AciServiceIdentifier(sender.accountIdentifier()).toCompactByteString())
|
||||
.setSourceDevice(sender.deviceId())
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent)
|
||||
|
||||
+3
-3
@@ -63,7 +63,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
@Override
|
||||
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
|
||||
|
||||
// Callers must be authenticated to request unversioned profiles by PNI
|
||||
if (targetIdentifier.identityType() == IdentityType.PNI) {
|
||||
@@ -100,7 +100,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
|
||||
@Override
|
||||
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
|
||||
@@ -123,7 +123,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
@Override
|
||||
public GetExpiringProfileKeyCredentialAnonymousResponse getExpiringProfileKeyCredential(
|
||||
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
|
||||
throw GrpcExceptions.constraintViolation("invalid credential type");
|
||||
|
||||
@@ -211,7 +211,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
|
||||
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
|
||||
@@ -228,7 +228,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
|
||||
|
||||
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
|
||||
+5
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.identity;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -62,6 +63,10 @@ public record AciServiceIdentifier(UUID uuid) implements ServiceIdentifier {
|
||||
return new AciServiceIdentifier(UUID.fromString(string));
|
||||
}
|
||||
|
||||
public static AciServiceIdentifier fromByteString(final ByteString byteString) {
|
||||
return fromBytes(byteString.toByteArray());
|
||||
}
|
||||
|
||||
public static AciServiceIdentifier fromBytes(final byte[] bytes) {
|
||||
final UUID uuid;
|
||||
|
||||
|
||||
+37
-2
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.identity;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.UUID;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
@@ -49,6 +50,15 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
|
||||
*/
|
||||
byte[] toCompactByteArray();
|
||||
|
||||
/**
|
||||
* Returns a compact binary representation of this account identifier as a {@link ByteString}.
|
||||
*
|
||||
* @return a binary representation of this account identifier
|
||||
*/
|
||||
default ByteString toCompactByteString() {
|
||||
return ByteString.copyFrom(toCompactByteArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a fixed-width binary representation of this account identifier.
|
||||
*
|
||||
@@ -56,11 +66,20 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
|
||||
*/
|
||||
byte[] toFixedWidthByteArray();
|
||||
|
||||
/**
|
||||
* Returns a fixed-width binary representation of this account identifier as a {@link ByteString}.
|
||||
*
|
||||
* @return a binary representation of this account identifier
|
||||
*/
|
||||
default ByteString toFixedWidthByteString() {
|
||||
return ByteString.copyFrom(toFixedWidthByteArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a service identifier string, which should be a plain UUID string for ACIs and a prefixed UUID string for PNIs
|
||||
*
|
||||
* @param string A service identifier string
|
||||
* @return The parsed {@link ServiceIdentifier}
|
||||
* @param string a service identifier string
|
||||
* @return the parsed service identifier
|
||||
*/
|
||||
static ServiceIdentifier valueOf(final String string) {
|
||||
try {
|
||||
@@ -70,6 +89,12 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a service identifier from a byte array.
|
||||
*
|
||||
* @param bytes the byte array from which to parse a service identifier
|
||||
* @return the parsed service identifier
|
||||
*/
|
||||
static ServiceIdentifier fromBytes(final byte[] bytes) {
|
||||
try {
|
||||
return AciServiceIdentifier.fromBytes(bytes);
|
||||
@@ -78,6 +103,16 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a service identifier from a byte string.
|
||||
*
|
||||
* @param byteString the byte string from which to parse a service identifier
|
||||
* @return the parsed service identifier
|
||||
*/
|
||||
static ServiceIdentifier fromByteString(final ByteString byteString) {
|
||||
return fromBytes(byteString.toByteArray());
|
||||
}
|
||||
|
||||
static ServiceIdentifier fromLibsignal(final ServiceId libsignalServiceId) {
|
||||
if (libsignalServiceId instanceof ServiceId.Aci) {
|
||||
return new AciServiceIdentifier(libsignalServiceId.getRawUUID());
|
||||
|
||||
@@ -15,6 +15,7 @@ import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -46,9 +47,10 @@ public final class MessageMetrics {
|
||||
final MessageProtos.Envelope envelope) {
|
||||
if (envelope.hasDestinationServiceId()) {
|
||||
try {
|
||||
measureAccountDestinationUuidMismatches(account, ServiceIdentifier.valueOf(envelope.getDestinationServiceId()));
|
||||
measureAccountDestinationUuidMismatches(account, ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()));
|
||||
} catch (final IllegalArgumentException ignored) {
|
||||
logger.warn("Envelope had invalid destination UUID: {}", envelope.getDestinationServiceId());
|
||||
logger.warn("Envelope had invalid destination service ID: {}",
|
||||
HexFormat.of().formatHex(envelope.getDestinationServiceId().toByteArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.util.DataSize;
|
||||
@@ -24,7 +24,6 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import kotlin.Pair;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
@@ -327,15 +326,15 @@ public class MessageSender {
|
||||
|
||||
final byte excludedDeviceId;
|
||||
if (syncMessageSenderDeviceId.isPresent()) {
|
||||
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isBlank(message.getSourceServiceId()) ||
|
||||
!destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
|
||||
if (messagesByDeviceId.values().stream().anyMatch(message -> !message.hasSourceServiceId() ||
|
||||
!destination.isIdentifiedBy(ServiceIdentifier.fromByteString(message.getSourceServiceId())))) {
|
||||
|
||||
throw new IllegalArgumentException("Sync message sender device ID specified, but one or more messages are not addressed to sender");
|
||||
}
|
||||
excludedDeviceId = syncMessageSenderDeviceId.get();
|
||||
} else {
|
||||
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isNotBlank(message.getSourceServiceId()) &&
|
||||
destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
|
||||
if (messagesByDeviceId.values().stream().anyMatch(message -> message.hasSourceServiceId() &&
|
||||
destination.isIdentifiedBy(ServiceIdentifier.fromByteString(message.getSourceServiceId())))) {
|
||||
|
||||
throw new IllegalArgumentException("Sync message sender device ID not specified, but one or more messages are addressed to sender");
|
||||
}
|
||||
|
||||
@@ -44,9 +44,9 @@ public class ReceiptSender {
|
||||
destinationAccount -> {
|
||||
final Envelope message = Envelope.newBuilder()
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setSourceServiceId(sourceIdentifier.toServiceIdentifierString())
|
||||
.setSourceServiceId(sourceIdentifier.toCompactByteString())
|
||||
.setSourceDevice(sourceDeviceId)
|
||||
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
|
||||
.setDestinationServiceId(destinationIdentifier.toCompactByteString())
|
||||
.setClientTimestamp(messageId)
|
||||
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT)
|
||||
.setUrgent(false)
|
||||
|
||||
+3
-3
@@ -40,6 +40,7 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ChangeNumberManager {
|
||||
|
||||
@@ -159,10 +160,9 @@ public class ChangeNumberManager {
|
||||
|
||||
try {
|
||||
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
|
||||
final String updatedPniString = updatedAccount.getIdentifier(IdentityType.PNI).toString();
|
||||
|
||||
messagesByDeviceId.replaceAll((_, envelope) ->
|
||||
envelope.toBuilder().setUpdatedPni(updatedPniString).build());
|
||||
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
|
||||
.build());
|
||||
|
||||
messageSender.sendMessages(updatedAccount,
|
||||
serviceIdentifier,
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.grpc.ServiceIdentifierUtil;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
/**
|
||||
* Provides utility methods for "compressing" and "expanding" envelopes. Historically UUID-like fields in envelopes have
|
||||
* been represented as strings (e.g. "c15f1dfb-ae2c-43a8-9bb9-baba97ac416c"), but <em>could</em> be represented as more
|
||||
* compact byte arrays instead. Existing clients generally expect string representations (though that should change in
|
||||
* the near future), but we can use the more compressed forms at rest for more efficient storage and transfer.
|
||||
*/
|
||||
public class EnvelopeUtil {
|
||||
|
||||
@VisibleForTesting
|
||||
static final String INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME = "envelopeIncludeBinaryServiceIdentifier";
|
||||
|
||||
/**
|
||||
* Converts all "compressible" UUID-like fields in the given envelope to more compact binary representations.
|
||||
*
|
||||
* @param envelope the envelope to compress
|
||||
*
|
||||
* @return an envelope with string-based UUID-like fields compressed to binary representations
|
||||
*/
|
||||
public static MessageProtos.Envelope compress(final MessageProtos.Envelope envelope) {
|
||||
final MessageProtos.Envelope.Builder builder = envelope.toBuilder();
|
||||
|
||||
if (builder.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceId = ServiceIdentifier.valueOf(builder.getSourceServiceId());
|
||||
|
||||
builder.setSourceServiceIdBinary(ServiceIdentifierUtil.toCompactByteString(sourceServiceId));
|
||||
builder.clearSourceServiceId();
|
||||
}
|
||||
|
||||
if (builder.hasDestinationServiceId()) {
|
||||
final ServiceIdentifier destinationServiceId = ServiceIdentifier.valueOf(builder.getDestinationServiceId());
|
||||
|
||||
builder.setDestinationServiceIdBinary(ServiceIdentifierUtil.toCompactByteString(destinationServiceId));
|
||||
builder.clearDestinationServiceId();
|
||||
}
|
||||
|
||||
if (builder.hasServerGuid()) {
|
||||
final UUID serverGuid = UUID.fromString(builder.getServerGuid());
|
||||
|
||||
builder.setServerGuidBinary(UUIDUtil.toByteString(serverGuid));
|
||||
builder.clearServerGuid();
|
||||
}
|
||||
|
||||
if (builder.hasUpdatedPni()) {
|
||||
final UUID updatedPni = UUID.fromString(builder.getUpdatedPni());
|
||||
|
||||
builder.setUpdatedPniBinary(UUIDUtil.toByteString(updatedPni));
|
||||
builder.clearUpdatedPni();
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* "Expands" all binary representations of UUID-like fields to string representations to meet current client
|
||||
* expectations.
|
||||
*
|
||||
* @param envelope the envelope to expand
|
||||
*
|
||||
* @return an envelope with binary representations of UUID-like fields expanded to string representations
|
||||
*/
|
||||
public static MessageProtos.Envelope expand(final MessageProtos.Envelope envelope,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
final boolean includeBinaryServiceIdentifiers;
|
||||
|
||||
if (envelope.hasDestinationServiceIdBinary() || envelope.hasDestinationServiceId()) {
|
||||
final ServiceIdentifier destinationIdentifier = envelope.hasDestinationServiceIdBinary()
|
||||
? ServiceIdentifier.fromBytes(envelope.getDestinationServiceIdBinary().toByteArray())
|
||||
: ServiceIdentifier.valueOf(envelope.getDestinationServiceId());
|
||||
|
||||
includeBinaryServiceIdentifiers =
|
||||
experimentEnrollmentManager.isEnrolled(destinationIdentifier.uuid(), INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME);
|
||||
} else {
|
||||
includeBinaryServiceIdentifiers = false;
|
||||
}
|
||||
|
||||
final MessageProtos.Envelope.Builder builder = envelope.toBuilder();
|
||||
|
||||
if (builder.hasSourceServiceIdBinary()) {
|
||||
final ServiceIdentifier sourceServiceId =
|
||||
ServiceIdentifierUtil.fromByteString(builder.getSourceServiceIdBinary());
|
||||
|
||||
builder.setSourceServiceId(sourceServiceId.toServiceIdentifierString());
|
||||
|
||||
if (!includeBinaryServiceIdentifiers) {
|
||||
builder.clearSourceServiceIdBinary();
|
||||
}
|
||||
}
|
||||
|
||||
if (builder.hasDestinationServiceIdBinary()) {
|
||||
final ServiceIdentifier destinationServiceId =
|
||||
ServiceIdentifierUtil.fromByteString(builder.getDestinationServiceIdBinary());
|
||||
|
||||
builder.setDestinationServiceId(destinationServiceId.toServiceIdentifierString());
|
||||
|
||||
if (!includeBinaryServiceIdentifiers) {
|
||||
builder.clearDestinationServiceIdBinary();
|
||||
}
|
||||
}
|
||||
|
||||
if (builder.hasServerGuidBinary()) {
|
||||
final UUID serverGuid = UUIDUtil.fromByteString(builder.getServerGuidBinary());
|
||||
|
||||
builder.setServerGuid(serverGuid.toString());
|
||||
|
||||
if (!includeBinaryServiceIdentifiers) {
|
||||
builder.clearServerGuidBinary();
|
||||
}
|
||||
}
|
||||
|
||||
if (builder.hasUpdatedPniBinary()) {
|
||||
final UUID updatedPni = UUIDUtil.fromByteString(builder.getUpdatedPniBinary());
|
||||
|
||||
// Note that expanded envelopes include BOTH forms of the `updatedPni` field
|
||||
builder.setUpdatedPni(updatedPni.toString());
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -32,6 +32,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -366,7 +367,7 @@ public class MessagePersister implements Managed {
|
||||
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
|
||||
return Mono
|
||||
.fromCompletionStage(() -> messagesManager
|
||||
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.delete(aci, device, UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.map(Optional::isPresent);
|
||||
})
|
||||
|
||||
@@ -48,12 +48,12 @@ import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -121,7 +121,6 @@ public class MessagesCache {
|
||||
private final ExecutorService messageDeletionExecutorService;
|
||||
// messageDeletionExecutorService wrapped into a reactor Scheduler
|
||||
private final Scheduler messageDeletionScheduler;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final MessagesCacheInsertScript insertScript;
|
||||
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
|
||||
@@ -175,16 +174,13 @@ public class MessagesCache {
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final Clock clock,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager)
|
||||
throws IOException {
|
||||
final Clock clock) throws IOException {
|
||||
|
||||
this(
|
||||
redisCluster,
|
||||
messageDeliveryScheduler,
|
||||
messageDeletionExecutorService,
|
||||
clock,
|
||||
experimentEnrollmentManager,
|
||||
new MessagesCacheInsertScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheGetItemsScript(redisCluster),
|
||||
@@ -200,7 +196,6 @@ public class MessagesCache {
|
||||
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript,
|
||||
@@ -216,7 +211,6 @@ public class MessagesCache {
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.messageDeletionExecutorService = messageDeletionExecutorService;
|
||||
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.insertScript = insertScript;
|
||||
this.insertMrmScript = insertMrmScript;
|
||||
@@ -233,7 +227,7 @@ public class MessagesCache {
|
||||
final byte destinationDeviceId,
|
||||
final MessageProtos.Envelope message) {
|
||||
|
||||
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(messageGuid.toString()).build();
|
||||
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(UUIDUtil.toByteString(messageGuid)).build();
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return insertScript.executeAsync(destinationAccountIdentifier, destinationDeviceId, messageWithGuid)
|
||||
@@ -278,7 +272,7 @@ public class MessagesCache {
|
||||
removedMessages.add(RemovedMessage.fromEnvelope(envelope));
|
||||
if (envelope.hasSharedMrmKey()) {
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(
|
||||
ServiceIdentifier.valueOf(envelope.getDestinationServiceId()), _ -> new ArrayList<>())
|
||||
ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()), _ -> new ArrayList<>())
|
||||
.add(envelope.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
@@ -398,7 +392,7 @@ public class MessagesCache {
|
||||
private void discardStaleMessages(final UUID destinationUuid, final byte destinationDevice,
|
||||
Flux<MessageProtos.Envelope> staleMessages, final Counter counter, final String context) {
|
||||
staleMessages
|
||||
.map(e -> UUID.fromString(e.getServerGuid()))
|
||||
.map(e -> UUIDUtil.fromByteString(e.getServerGuid()))
|
||||
.buffer(PAGE_SIZE)
|
||||
.subscribeOn(messageDeletionScheduler)
|
||||
.subscribe(messageGuids ->
|
||||
@@ -479,7 +473,7 @@ public class MessagesCache {
|
||||
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
|
||||
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
|
||||
// the message might be addressed to the account's PNI, so use the service ID from the envelope
|
||||
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
|
||||
ServiceIdentifier.fromByteString(mrmMessage.getDestinationServiceId()), destinationDevice);
|
||||
|
||||
return Mono.from(redisCluster.withBinaryCluster(
|
||||
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
|
||||
@@ -670,10 +664,10 @@ public class MessagesCache {
|
||||
try {
|
||||
final MessageProtos.Envelope message = parseEnvelope(serialized);
|
||||
|
||||
processedMessages.add(message.getServerGuid());
|
||||
processedMessages.add(UUIDUtil.fromByteString(message.getServerGuid()).toString());
|
||||
|
||||
if (message.hasSharedMrmKey()) {
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.fromByteString(message.getDestinationServiceId()),
|
||||
_ -> new ArrayList<>())
|
||||
.add(message.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
@@ -782,6 +776,6 @@ public class MessagesCache {
|
||||
private MessageProtos.Envelope parseEnvelope(final byte[] envelopeBytes)
|
||||
throws InvalidProtocolBufferException {
|
||||
|
||||
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(envelopeBytes), experimentEnrollmentManager);
|
||||
return MessageProtos.Envelope.parseFrom(envelopeBytes);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -21,6 +21,7 @@ import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
/**
|
||||
* Inserts an envelope into the message queue for a destination device and publishes a "new message available" event.
|
||||
@@ -62,8 +63,8 @@ class MessagesCacheInsertScript {
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>(Arrays.asList(
|
||||
EnvelopeUtil.compress(envelope).toByteArray(), // message
|
||||
envelope.getServerGuid().getBytes(StandardCharsets.UTF_8), // guid
|
||||
envelope.toByteArray(), // message
|
||||
UUIDUtil.fromByteString(envelope.getServerGuid()).toString().getBytes(StandardCharsets.UTF_8), // guid
|
||||
NEW_MESSAGE_EVENT_BYTES // eventPayload
|
||||
));
|
||||
|
||||
|
||||
+9
-13
@@ -27,8 +27,8 @@ import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
@@ -63,13 +63,11 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
private final String tableName;
|
||||
private final Duration timeToLive;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
|
||||
|
||||
public MessagesDynamoDb(DynamoDbClient dynamoDb, DynamoDbAsyncClient dynamoDbAsyncClient, String tableName,
|
||||
Duration timeToLive, ExecutorService messageDeletionExecutor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
Duration timeToLive, ExecutorService messageDeletionExecutor) {
|
||||
super(dynamoDb);
|
||||
|
||||
this.dbAsyncClient = dynamoDbAsyncClient;
|
||||
@@ -77,7 +75,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
this.timeToLive = timeToLive;
|
||||
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid,
|
||||
@@ -94,14 +91,14 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid, destinationDevice);
|
||||
List<WriteRequest> writeItems = new ArrayList<>();
|
||||
for (MessageProtos.Envelope message : messages) {
|
||||
final UUID messageUuid = UUID.fromString(message.getServerGuid());
|
||||
final UUID messageUuid = UUIDUtil.fromByteString(message.getServerGuid());
|
||||
|
||||
final ImmutableMap.Builder<String, AttributeValue> item = ImmutableMap.<String, AttributeValue>builder()
|
||||
.put(KEY_PARTITION, partitionKey)
|
||||
.put(KEY_SORT, convertSortKey(message.getServerTimestamp(), messageUuid))
|
||||
.put(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
|
||||
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)))
|
||||
.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(EnvelopeUtil.compress(message).toByteArray())).build());
|
||||
.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(message.toByteArray())).build());
|
||||
|
||||
writeItems.add(WriteRequest.builder().putRequest(PutRequest.builder()
|
||||
.item(item.build())
|
||||
@@ -147,7 +144,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
return dbAsyncClient.queryPaginator(queryRequest).items()
|
||||
.map(message -> {
|
||||
try {
|
||||
return convertItemToEnvelope(message, experimentEnrollmentManager);
|
||||
return convertItemToEnvelope(message);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.error("Failed to parse envelope", e);
|
||||
return null;
|
||||
@@ -167,7 +164,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
.thenApplyAsync(deleteItemResponse -> {
|
||||
if (deleteItemResponse.attributes() != null && deleteItemResponse.attributes().containsKey(KEY_PARTITION)) {
|
||||
try {
|
||||
return Optional.of(convertItemToEnvelope(deleteItemResponse.attributes(), experimentEnrollmentManager));
|
||||
return Optional.of(convertItemToEnvelope(deleteItemResponse.attributes()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.error("Failed to parse envelope", e);
|
||||
}
|
||||
@@ -178,11 +175,10 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) throws InvalidProtocolBufferException {
|
||||
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item)
|
||||
throws InvalidProtocolBufferException {
|
||||
|
||||
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray()),
|
||||
experimentEnrollmentManager);
|
||||
return MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray());
|
||||
}
|
||||
|
||||
private long getTtlForMessage(MessageProtos.Envelope message) {
|
||||
|
||||
+12
-7
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -102,10 +103,14 @@ public class MessagesManager {
|
||||
|
||||
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
|
||||
.thenAccept(present -> {
|
||||
if (message.hasSourceServiceId() && !accountIdentifier.toString()
|
||||
.equals(message.getSourceServiceId())) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(message.getSourceServiceId(), messageGuid);
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
}
|
||||
}
|
||||
|
||||
devicePresenceById.put(deviceId, present);
|
||||
@@ -170,8 +175,8 @@ public class MessagesManager {
|
||||
|
||||
return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI),
|
||||
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
|
||||
.collect(Collectors.toMap(deviceId -> deviceId, deviceId -> prototypeMessage.toBuilder()
|
||||
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
|
||||
.collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder()
|
||||
.setDestinationServiceId(serviceIdentifier.toCompactByteString())
|
||||
.build())))
|
||||
.thenAccept(clientPresenceByDeviceId ->
|
||||
clientPresenceByAccountAndDevice.put(resolvedRecipients.get(recipient),
|
||||
@@ -275,7 +280,7 @@ public class MessagesManager {
|
||||
|
||||
messagesDynamoDb.store(messages, destinationUuid, destinationDevice);
|
||||
|
||||
final List<UUID> messageGuids = messages.stream().map(message -> UUID.fromString(message.getServerGuid()))
|
||||
final List<UUID> messageGuids = messages.stream().map(message -> UUIDUtil.fromByteString(message.getServerGuid()))
|
||||
.collect(Collectors.toList());
|
||||
int messagesRemovedFromCache = 0;
|
||||
try {
|
||||
|
||||
+2
-1
@@ -11,6 +11,7 @@ import java.util.concurrent.Flow;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
|
||||
@@ -58,7 +59,7 @@ public class RedisDynamoDbMessageStream implements MessageStream {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
|
||||
final UUID guid = UUID.fromString(message.getServerGuid());
|
||||
final UUID guid = UUIDUtil.fromByteString(message.getServerGuid());
|
||||
|
||||
return messagesCache.remove(accountIdentifier, device.getId(), guid)
|
||||
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public record RemovedMessage(Optional<ServiceIdentifier> sourceServiceId, ServiceIdentifier destinationServiceId,
|
||||
@VisibleForTesting UUID serverGuid, long serverTimestamp, long clientTimestamp,
|
||||
@@ -18,10 +19,10 @@ public record RemovedMessage(Optional<ServiceIdentifier> sourceServiceId, Servic
|
||||
public static RemovedMessage fromEnvelope(MessageProtos.Envelope envelope) {
|
||||
return new RemovedMessage(
|
||||
envelope.hasSourceServiceId()
|
||||
? Optional.of(ServiceIdentifier.valueOf(envelope.getSourceServiceId()))
|
||||
? Optional.of(ServiceIdentifier.fromByteString(envelope.getSourceServiceId()))
|
||||
: Optional.empty(),
|
||||
ServiceIdentifier.valueOf(envelope.getDestinationServiceId()),
|
||||
UUID.fromString(envelope.getServerGuid()),
|
||||
ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()),
|
||||
UUIDUtil.fromByteString(envelope.getServerGuid()),
|
||||
envelope.getServerTimestamp(),
|
||||
envelope.getClientTimestamp(),
|
||||
envelope.getType()
|
||||
|
||||
+1
-1
@@ -160,7 +160,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
|
||||
acknowledgedMessageBuffer.acknowledgeMessage(
|
||||
messageGuidCodec.decodeMessageGuid(UUIDUtil.fromByteString(message.getServerGuidBinary())));
|
||||
messageGuidCodec.decodeMessageGuid(UUIDUtil.fromByteString(message.getServerGuid())));
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ sealed interface FoundationDbMessageStreamEntry permits FoundationDbMessageStrea
|
||||
return switch (this) {
|
||||
case Message(final Versionstamp versionstamp, final MessageProtos.Envelope partialEnvelope): {
|
||||
yield new MessageStreamEntry.Envelope(partialEnvelope.toBuilder()
|
||||
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp)))
|
||||
.setServerGuid(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp)))
|
||||
.build());
|
||||
}
|
||||
case QueueEmpty():
|
||||
|
||||
+7
-13
@@ -15,9 +15,9 @@ import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -44,11 +44,11 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.EnvelopeUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.WebSocketResourceProvider;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
@@ -93,8 +93,6 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
|
||||
private static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
|
||||
|
||||
private static final String RECOMPRESS_ENVELOPE_EXPERIMENT_NAME = "recompressEnvelopes";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class);
|
||||
|
||||
private final ReceiptSender receiptSender;
|
||||
@@ -173,7 +171,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
if (hasSentFirstMessage.compareAndSet(false, true)) {
|
||||
messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getIdentifier(IdentityType.ACI),
|
||||
authenticatedDevice.getId(),
|
||||
UUID.fromString(message.getServerGuid()),
|
||||
UUIDUtil.fromByteString(message.getServerGuid()),
|
||||
client.getUserAgent(),
|
||||
"websocket");
|
||||
}
|
||||
@@ -241,11 +239,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
return messageStream.acknowledgeMessage(message);
|
||||
}
|
||||
|
||||
final boolean recompressEnvelope =
|
||||
experimentEnrollmentManager.isEnrolled(authenticatedAccount.getIdentifier(IdentityType.ACI), RECOMPRESS_ENVELOPE_EXPERIMENT_NAME);
|
||||
|
||||
final Optional<byte[]> body =
|
||||
Optional.of(serializeMessage(recompressEnvelope ? EnvelopeUtil.compress(message) : message));
|
||||
final Optional<byte[]> body = Optional.of(serializeMessage(message));
|
||||
|
||||
sendMessageCounter.increment();
|
||||
sentMessageCounter.increment();
|
||||
@@ -308,11 +302,11 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
}
|
||||
|
||||
try {
|
||||
receiptSender.sendReceipt(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
authenticatedDevice.getId(), AciServiceIdentifier.valueOf(message.getSourceServiceId()),
|
||||
receiptSender.sendReceipt(ServiceIdentifier.fromByteString(message.getDestinationServiceId()),
|
||||
authenticatedDevice.getId(), AciServiceIdentifier.fromByteString(message.getSourceServiceId()),
|
||||
message.getClientTimestamp());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.error("Could not parse UUID: {}", message.getSourceServiceId());
|
||||
logger.error("Could not parse UUID: {}", HexFormat.of().formatHex(message.getSourceServiceId().toByteArray()));
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to send receipt", e);
|
||||
}
|
||||
|
||||
+2
-2
@@ -245,7 +245,7 @@ public record CommandDependencies(
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
messageDeletionExecutor, experimentEnrollmentManager);
|
||||
messageDeletionExecutor);
|
||||
FaultTolerantRedisClusterClient messagesCluster = configuration.getMessageCacheConfiguration()
|
||||
.getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
|
||||
@@ -267,7 +267,7 @@ public record CommandDependencies(
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster,
|
||||
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC(), experimentEnrollmentManager);
|
||||
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
configuration.getCdnConfiguration().bucket());
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
|
||||
Reference in new issue
Block a user