Compare commits

...
41 changed files with 2099 additions and 467 deletions

No files matched your search

+1
View File
@@ -82,6 +82,7 @@ zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcd
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
profileAvatarsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
paymentsService.fixerApiKey: unset
+5
View File
@@ -128,6 +128,8 @@ dynamoDbTables:
expiration: P90D
phoneNumberIdentifiers:
tableName: Example_PhoneNumberIdentifiers
profileAvatars:
tableName: Example_ProfileAvatars
profiles:
tableName: Example_Profiles
profilesV2:
@@ -326,6 +328,9 @@ callingZkConfig:
backupsZkConfig:
serverSecret: secret://backupsZkConfig.serverSecret
profileAvatarsZkConfig:
serverSecret: secret://profileAvatarsZkConfig.serverSecret
dynamicConfig:
s3Region: a-region
s3Bucket: a-bucket
@@ -235,6 +235,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GenericZkConfig backupsZkConfig;
@Valid
@NotNull
@JsonProperty
private GenericZkConfig profileAvatarsZkConfig;
@Valid
@NotNull
@JsonProperty
@@ -499,6 +504,10 @@ public class WhisperServerConfiguration extends Configuration {
return backupsZkConfig;
}
public GenericZkConfig getProfileAvatarsZkConfig() {
return profileAvatarsZkConfig;
}
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
return remoteConfig;
}
@@ -265,6 +265,7 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
@@ -538,6 +539,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
config.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
@@ -618,6 +621,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.threads(16).build();
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
final ScheduledExecutorService presenceRenewalExecutor =
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
ExecutorServiceBuilder.of(environment, "messageDelivery")
@@ -740,7 +745,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
disconnectionRequestListenerExecutor, retryExecutor);
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock);
@@ -748,6 +753,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getFoundationDbMessagesConfiguration().activeEpoch(),
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
presenceRenewalExecutor,
Clock.systemUTC());
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
@@ -911,6 +917,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().value());
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
GenericServerSecretParams backupsGenericZkSecretParams = new GenericServerSecretParams(config.getBackupsZkConfig().serverSecret().value());
GenericServerSecretParams profileAvatarsGenericZkSecretParams = new GenericServerSecretParams(config.getProfileAvatarsZkConfig().serverSecret().value());
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(zkSecretParams);
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(zkSecretParams);
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
@@ -1064,7 +1071,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileBadgeConverter, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
@@ -1090,7 +1097,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, zkSecretParams, rateLimiters, clock),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
@@ -1371,7 +1378,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
}
}
public static void main(String[] args) throws Exception {
static void main(String[] args) throws Exception {
new WhisperServerService().run(args);
}
}
@@ -64,6 +64,7 @@ public class DynamoDbTables {
private final TableWithExpiration messages;
private final TableWithExpiration onetimeDonations;
private final Table phoneNumberIdentifiers;
private final Table profileAvatars;
private final Table profiles;
private final Table profilesV2;
private final Table pushChallenge;
@@ -94,6 +95,7 @@ public class DynamoDbTables {
@JsonProperty("messages") final TableWithExpiration messages,
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@JsonProperty("profileAvatars") final Table profileAvatars,
@JsonProperty("profiles") final Table profiles,
@JsonProperty("profilesV2") final Table profilesV2,
@JsonProperty("pushChallenge") final Table pushChallenge,
@@ -123,6 +125,7 @@ public class DynamoDbTables {
this.messages = messages;
this.onetimeDonations = onetimeDonations;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profileAvatars = profileAvatars;
this.profiles = profiles;
this.profilesV2 = profilesV2;
this.pushChallenge = pushChallenge;
@@ -238,6 +241,12 @@ public class DynamoDbTables {
return phoneNumberIdentifiers;
}
@NotNull
@Valid
public Table getProfileAvatars() {
return profileAvatars;
}
@NotNull
@Valid
public Table getProfilesV1() {
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
@@ -44,6 +43,8 @@ import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
@@ -271,9 +272,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account authenticatedAccount = getAuthenticatedAccount();
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
final ZkCredentialPublicKey zkCredentialKey;
try {
zkCredentialKey = new ZkCredentialPublicKey(request.getPublicKey().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid public key bytes");
}
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
if (authenticatedAccount.getZkCredentialKey().map(zkCredentialKey::equals).orElse(false)) {
return SetZkCredentialKeyResponse.newBuilder()
.setRotationId(Objects.requireNonNull(authenticatedAccount.getZkCredentialKeyRotationId()))
.build();
@@ -5,12 +5,21 @@
package org.whispersystems.textsecuregcm.grpc;
import java.time.Clock;
import java.util.Optional;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Base64;
import java.util.Optional;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.DeleteAvatarRequest;
import org.signal.chat.profile.DeleteAvatarResponse;
import org.signal.chat.profile.ExtendAvatarTTLRequest;
import org.signal.chat.profile.ExtendAvatarTTLResponse;
import org.signal.chat.profile.GetAvatarUploadFormRequest;
import org.signal.chat.profile.GetAvatarUploadFormResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
@@ -18,44 +27,75 @@ import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.ProfileAnonymousImplBase {
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final ProfileBadgeConverter profileBadgeConverter;
private final ServerZkProfileOperations zkProfileOperations;
private final GenericServerSecretParams genericServerSecretParams;
private final GroupSendTokenUtil groupSendTokenUtil;
private final PostPolicyGenerator policyGenerator;
private final RateLimiters rateLimiters;
private final Clock clock;
public ProfileAnonymousGrpcService(
final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerSecretParams serverSecretParams) {
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final ServerSecretParams serverSecretParams,
final RateLimiters rateLimiters,
final Clock clock) {
this(accountsManager,
profilesManager,
profileBadgeConverter,
policyGenerator,
genericServerSecretParams,
rateLimiters,
clock,
new ServerZkProfileOperations(serverSecretParams),
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
new GroupSendTokenUtil(serverSecretParams, clock));
}
@VisibleForTesting
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final RateLimiters rateLimiters,
final Clock clock,
final ServerZkProfileOperations zkProfileOperations,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.profileBadgeConverter = profileBadgeConverter;
this.policyGenerator = policyGenerator;
this.genericServerSecretParams = genericServerSecretParams;
this.rateLimiters = rateLimiters;
this.clock = clock;
this.zkProfileOperations = zkProfileOperations;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@@ -152,4 +192,92 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
}
@Override
public GetAvatarUploadFormResponse getAvatarUploadForm(final GetAvatarUploadFormRequest request) throws RateLimitExceededException {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
} catch (VerificationFailedException _) {
return GetAvatarUploadFormResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
rateLimiters.getProfileAvatarBytesLimiter().validate(Base64.getEncoder().encodeToString(identity), request.getUploadLength());
final String avatar = ProfileHelper.generateAvatarObjectName();
profilesManager.setAvatarForIdentity(identity, avatar);
return GetAvatarUploadFormResponse.newBuilder()
.setAvatarUploadForm(ProfileGrpcHelper.generateAvatarUploadForm(avatar, request.getUploadLength(), policyGenerator, clock))
.build();
}
@Override
public ExtendAvatarTTLResponse extendAvatarTTL(final ExtendAvatarTTLRequest request) {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
try {
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (VerificationFailedException _) {
return ExtendAvatarTTLResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
return profilesManager.extendAvatarTtlForIdentity(identity)
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
.setPath(extendedPath)
.build())
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public DeleteAvatarResponse deleteAvatar(final DeleteAvatarRequest request) {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
try {
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (VerificationFailedException _) {
return DeleteAvatarResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
profilesManager.deleteAvatarForIdentity(identity);
return DeleteAvatarResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
}
@@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
@@ -17,6 +18,7 @@ import java.util.Optional;
import java.util.UUID;
import org.signal.chat.common.Badge;
import org.signal.chat.common.BadgeSvg;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
@@ -32,6 +34,7 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
@@ -40,6 +43,12 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcHelper {
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
final ProfilesManager profilesManager,
final byte[] requestVersion,
@@ -217,6 +226,20 @@ public class ProfileGrpcHelper {
});
}
public static S3UploadForm generateAvatarUploadForm(final String objectName, final int uploadLength,
final PostPolicyGenerator policyGenerator, final Clock clock) {
final PostPolicyGenerator.SignedPostPolicy policy =
policyGenerator.createFor(objectName, uploadLength, clock.instant());
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
.setKey(objectName)
.setCredential(policy.credential())
.setDate(policy.formattedTimestamp())
.setPolicy(policy.encodedPolicy())
.setSignature(policy.signature())
.build();
}
/**
* Computes the SHA-256 hash of the given data.
* <p>
@@ -5,11 +5,14 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
@@ -17,6 +20,8 @@ import java.util.stream.Collectors;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.GetAvatarCredentialsRequest;
import org.signal.chat.profile.GetAvatarCredentialsResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
@@ -28,6 +33,14 @@ import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
import org.signal.chat.profile.SimpleProfileGrpc;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -52,20 +65,18 @@ import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private static final Logger logger = LoggerFactory.getLogger(ProfileGrpcService.class);
private final Clock clock;
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
private final PostPolicyGenerator policyGenerator;
private final GenericServerSecretParams genericServerSecretParams;
private final ProfileBadgeConverter profileBadgeConverter;
private final RateLimiters rateLimiters;
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
private record AvatarData(Optional<String> currentAvatar,
Optional<String> finalAvatar,
Optional<S3UploadForm> uploadAttributes) {}
@@ -77,6 +88,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters) {
this.clock = clock;
@@ -86,6 +98,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
BadgeConfiguration::getId, Function.identity()));
this.policyGenerator = policyGenerator;
this.genericServerSecretParams = genericServerSecretParams;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
}
@@ -136,7 +149,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
case AVATAR_CHANGE_UPDATE -> {
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
Optional.of(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, policyGenerator, clock)));
}
};
@@ -205,6 +218,39 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
.build());
}
@Override
public GetAvatarCredentialsResponse getAvatarCredentials(final GetAvatarCredentialsRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
if (account.getZkCredentialKey().isEmpty()) {
return GetAvatarCredentialsResponse.newBuilder()
.setMissingZkCredentialKey(FailedPrecondition.newBuilder().setDescription("account requires ZK credential key"))
.build();
}
try {
final AvatarUploadCredentialRequest credentialRequest = new AvatarUploadCredentialRequest(
request.getAvatarCredentialsRequest().toByteArray());
final AvatarUploadCredentialResponse credentialResponse = credentialRequest.issueCredential(
new ServiceId.Aci(account.getIdentifier(IdentityType.ACI)),
account.getZkCredentialKey().get(),
Objects.requireNonNull(account.getZkCredentialKeyRotationId()),
clock.instant().truncatedTo(ChronoUnit.DAYS),
this.genericServerSecretParams);
return GetAvatarCredentialsResponse.newBuilder()
.setAvatarCredentials(ByteString.copyFrom(credentialResponse.serialize()))
.build();
} catch (InvalidInputException | VerificationFailedException _) {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@@ -263,17 +309,4 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
throw GrpcExceptions.invalidArguments("Request must include commitment during migration");
}
}
private S3UploadForm generateAvatarUploadForm(final String objectName) {
final PostPolicyGenerator.SignedPostPolicy policy =
policyGenerator.createFor(objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, clock.instant());
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
.setKey(objectName)
.setCredential(policy.credential())
.setDate(policy.formattedTimestamp())
.setPolicy(policy.encodedPolicy())
.setSignature(policy.signature())
.build();
}
}
@@ -28,6 +28,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
ALLOCATE_DEVICE("allocateDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
VERIFY_DEVICE("verifyDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
PROFILE("profile", new RateLimiterConfig(4320, Duration.ofSeconds(20), true)),
PROFILE_AVATAR_BYTES("profileAvatarBytes", new RateLimiterConfig(DataSize.mebibytes(100).toBytes(), Duration.ofNanos(10000), true)),
STICKER_PACK("stickerPack", new RateLimiterConfig(50, Duration.ofMinutes(72), false)),
USERNAME_LOOKUP("usernameLookup", new RateLimiterConfig(100, Duration.ofMinutes(15), true)),
USERNAME_SET("usernameSet", new RateLimiterConfig(100, Duration.ofMinutes(15), false)),
@@ -134,6 +135,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.PROFILE);
}
public RateLimiter getProfileAvatarBytesLimiter() {
return forDescriptor(For.PROFILE_AVATAR_BYTES);
}
public RateLimiter getStickerPackLimiter() {
return forDescriptor(For.STICKER_PACK);
}
@@ -9,12 +9,9 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.micrometer.core.instrument.Metrics;
@@ -33,6 +30,7 @@ import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,6 +41,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
@JsonFilter("Account")
public class Account {
@@ -128,7 +127,9 @@ public class Account {
@JsonProperty("zck")
@Nullable
private byte[] zkCredentialKey;
@JsonSerialize(using = ZkCredentialPublicKeyAdapter.Serializer.class)
@JsonDeserialize(using = ZkCredentialPublicKeyAdapter.Deserializer.class)
private ZkCredentialPublicKey zkCredentialKey;
@JsonProperty("zckr")
@Nullable
@@ -560,12 +561,11 @@ public class Account {
this.usernameHolds = usernameHolds;
}
@Nullable
public byte[] getZkCredentialKey() {
return zkCredentialKey;
public Optional<ZkCredentialPublicKey> getZkCredentialKey() {
return Optional.ofNullable(zkCredentialKey);
}
public void setZkCredentialKey(@Nullable final byte[] zkCredentialKey) {
public void setZkCredentialKey(@Nullable final ZkCredentialPublicKey zkCredentialKey) {
this.zkCredentialKey = zkCredentialKey;
}
@@ -327,7 +327,8 @@ public class Accounts {
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
// Carry over the existing ZK credential key to the new account
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey());
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
final List<TransactWriteItem> writeItems = new ArrayList<>();
@@ -0,0 +1,162 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.BiConsumer;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.reactivestreams.Subscription;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.BaseSubscriber;
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
public class AcknowledgementMirroringMessageStream implements MessageStream {
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private final FoundationDbMessageStream foundationDbMessageStream;
private final Set<UUID> messagesPendingAcknowledgement = new HashSet<>();
private static final int HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD = 1024;
@VisibleForTesting
static final int MAX_PENDING_ACKNOWLEDGEMENTS = 8192;
@VisibleForTesting
static final int FOUNDATIONDB_REQUEST_SIZE = 100;
private static final Counter HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER =
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "highPendingAcknowledgementCount"));
private static final Counter MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER =
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "maxPendingAcknowledgementLimitBreached"));
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry.Envelope> {
private final BiConsumer<UUID, Long> mirroredMessageHandler;
private long mirroredEntriesDelivered = 0;
private long requested = 0;
private FoundationDbSubscriber(final BiConsumer<UUID, Long> mirroredMessageHandler) {
this.mirroredMessageHandler = mirroredMessageHandler;
}
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
final boolean isMirroredMessage = switch (messageStreamEntry) {
case MessageStreamEntry.Envelope envelopeEntry ->
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
case MessageStreamEntry.QueueEmpty _ -> false;
};
if (!isMirroredMessage) {
return;
}
final boolean requestMore;
synchronized (this) {
requestMore = ++mirroredEntriesDelivered > requested;
if (requestMore) {
requested += FOUNDATIONDB_REQUEST_SIZE;
}
}
if (requestMore) {
request(FOUNDATIONDB_REQUEST_SIZE);
}
}
@Override
protected void hookOnSubscribe(final Subscription subscription) {
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
// to avoid with this subscriber
}
@Override
protected void hookOnNext(final MessageStreamEntry.Envelope envelope) {
mirroredMessageHandler.accept(
UUIDUtil.fromByteString(envelope.message().getServerGuid()), envelope.message().getServerTimestamp());
}
}
public AcknowledgementMirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
final FoundationDbMessageStream foundationDbMessageStream) {
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
this.foundationDbMessageStream = foundationDbMessageStream;
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber(this::handleMirroredMessageAcknowledged);
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
.cast(MessageStreamEntry.Envelope.class)
.subscribe(subscriber);
return JdkFlowAdapter.publisherToFlowPublisher(
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
// Mirror demand and termination signals to the FoundationDB message stream
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
.doOnComplete(subscriber::dispose));
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
// in Redis/DynamoDB
if (messageGuid.version() == 8) {
handleMirroredMessageAcknowledged(messageGuid, serverTimestamp);
}
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
}
private void handleMirroredMessageAcknowledged(final UUID messageGuid, final long serverTimestamp) {
// Before we can acknowledge and delete the message in FoundationDB, two things need to happen:
//
// 1. The client needs to acknowledge the message on the Redis/DDB stream.
// 2. The message needs to pass through the FoundationDB message stream pipeline because it needs to be registered
// in the acknowledged message buffer machinery before it can be deleted.
//
// We can't guarantee the order in which these two things happen, so we use a synchronized set to coordinate and
// determine when both have happened.
synchronized (messagesPendingAcknowledgement) {
if (messagesPendingAcknowledgement.remove(messageGuid)) {
// One of the two streams had already acknowledged this message, and this is the second acknowledgement. Now we
// can pass the acknowledgement along to FoundationDB.
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
} else {
// Either this message came from FoundationDB and got auto-acknowledged before getting explicitly acknowledged
// on the Redis/DynamoDB stream or the message got explicitly acknowledged on the Redis/DynamoDB stream before
// passing through the FoundationDB stream. Either way, wait for both streams to have done their part.
if (messagesPendingAcknowledgement.add(messageGuid)) {
if (messagesPendingAcknowledgement.size() == HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD) {
HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER.increment();
}
if (messagesPendingAcknowledgement.size() > MAX_PENDING_ACKNOWLEDGEMENTS) {
MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER.increment();
throw new IllegalStateException("Too many pending acknowledgements");
}
}
}
}
}
}
@@ -158,21 +158,24 @@ public class ChangeNumberManager {
final Account updatedAccount = accountsManager.changeNumber(
account.getIdentifier(IdentityType.ACI), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
.build());
if (!messagesByDeviceId.isEmpty()) {
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
.build());
messageSender.sendMessages(updatedAccount,
serviceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
senderUserAgent);
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages for {}", account.getIdentifier(IdentityType.ACI), e);
throw e;
messageSender.sendMessages(updatedAccount,
serviceIdentifier,
messagesByDeviceId,
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
senderUserAgent);
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages for {}",
account.getIdentifier(IdentityType.ACI), e);
throw e;
}
}
return updatedAccount;
@@ -1,66 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
public class DeletionMirroringRedisDynamoDbMessageStream implements MessageStream {
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private final FoundationDbMessageStore foundationDbMessageStore;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final AciServiceIdentifier accountIdentifier;
private final byte deviceId;
private static final Logger logger = LoggerFactory.getLogger(DeletionMirroringRedisDynamoDbMessageStream.class);
public DeletionMirroringRedisDynamoDbMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
final FoundationDbMessageStore foundationDbMessageStore,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final UUID accountIdentifier,
final byte deviceId) {
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
this.foundationDbMessageStore = foundationDbMessageStore;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
this.deviceId = deviceId;
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
return redisDynamoDbMessageStream.getMessages();
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
// in Redis/DynamoDB
if (messageGuid.version() == 8 &&
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
foundationDbMessageStore.delete(accountIdentifier, deviceId, messageGuid)
.whenComplete((_, throwable) -> {
if (throwable != null) {
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
messageGuid, throwable);
}
});
}
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
}
}
@@ -38,6 +38,7 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
@@ -279,12 +280,15 @@ public class MessagesManager {
}
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
return new DeletionMirroringRedisDynamoDbMessageStream(
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice),
foundationDbMessageStore,
experimentEnrollmentManager,
destinationUuid,
destinationDevice.getId());
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
destinationUuid, destinationDevice);
return experimentEnrollmentManager.isEnrolled(destinationUuid, MIRROR_DELETIONS_EXPERIMENT_NAME)
? new AcknowledgementMirroringMessageStream(
redisDynamoDbMessageStream,
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
: redisDynamoDbMessageStream;
}
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
@@ -0,0 +1,106 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
public class ProfileAvatars {
private final DynamoDbClient dynamoDbClient;
private final String tableName;
private final Duration expiration;
private final Clock clock;
// Identity that owns this profile; hash key; byte array
@VisibleForTesting
static final String KEY_IDENTITY = "I";
// URL of the avatar; string
@VisibleForTesting
static final String ATTR_URL = "U";
// Expiration timestamp, in seconds since the epoch, of the avatar; number
@VisibleForTesting
static final String ATTR_TTL = "E";
public ProfileAvatars(final DynamoDbClient dynamoDbClient, final String tableName, final Duration expiration, final
Clock clock) {
this.dynamoDbClient = dynamoDbClient;
this.tableName = tableName;
this.expiration = expiration;
this.clock = clock;
}
/// Sets the avatar URL for an identity
///
/// @return the previous URL, if any
public Optional<String> setAvatarUrl(final byte[] identity, final String url) {
final PutItemResponse response = dynamoDbClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity),
ATTR_URL, AttributeValues.fromString(url),
ATTR_TTL, AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
.returnValues(ReturnValue.ALL_OLD)
.build());
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
}
/// @return the avatar URL, if present
public Optional<String> updateAvatarTtl(final byte[] identity) {
final UpdateItemResponse response;
try {
response = dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.conditionExpression("attribute_exists(#url)")
.updateExpression("SET #ttl = :ttl")
.expressionAttributeNames(Map.of(
"#ttl", ATTR_TTL,
"#url", ATTR_URL))
.expressionAttributeValues(
Map.of(":ttl", AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
.returnValues(ReturnValue.ALL_OLD)
.build());
} catch (ConditionalCheckFailedException _) {
return Optional.empty();
}
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
}
/// @return the deleted avatar URL, if present
public Optional<String> deleteAvatarUrl(final byte[] identity) {
final DeleteItemResponse response = dynamoDbClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.returnValues(ReturnValue.ALL_OLD)
.build());
if (!response.hasAttributes()) {
return Optional.empty();
}
return Optional.ofNullable(response.attributes().get(ATTR_URL))
.map(AttributeValue::s);
}
}
@@ -14,7 +14,9 @@ import io.lettuce.core.RedisException;
import io.lettuce.core.ScriptOutputType;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -29,9 +31,13 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.MetadataDirective;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
public class ProfilesManager {
@@ -44,6 +50,7 @@ public class ProfilesManager {
private final Profiles profilesV1;
private final ProfilesV2 profilesV2;
private final ProfileAvatars profileAvatars;
private final FaultTolerantRedisClusterClient cacheCluster;
private final ScheduledExecutorService retryExecutor;
private final S3AsyncClient s3Client;
@@ -57,17 +64,19 @@ public class ProfilesManager {
public ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final ProfileAvatars profileAvatars,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket) throws IOException {
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
this(profilesV1, profilesV2, profileAvatars, cacheCluster, retryExecutor, s3Client, bucket,
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
}
@VisibleForTesting
ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final ProfileAvatars profileAvatars,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
@@ -75,6 +84,7 @@ public class ProfilesManager {
final ClusterLuaScript setLuaScript) {
this.profilesV1 = profilesV1;
this.profilesV2 = profilesV2;
this.profileAvatars = profileAvatars;
this.cacheCluster = cacheCluster;
this.retryExecutor = retryExecutor;
this.s3Client = s3Client;
@@ -124,12 +134,10 @@ public class ProfilesManager {
redisSet(uuid, versionedProfile, versionedProfileV1);
}
/**
* Delete all profiles for the given uuid.
* <p>
* Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
* deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
*/
/// Delete all profiles for the given uuid.
///
/// Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
/// deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
@@ -149,7 +157,7 @@ public class ProfilesManager {
.bucket(bucket)
.key(avatar)
.build())
.handle((ignored, throwable) -> {
.whenComplete((_, throwable) -> {
final String outcome;
if (throwable != null) {
logger.warn("Error deleting avatar", throwable);
@@ -159,7 +167,6 @@ public class ProfilesManager {
}
Metrics.counter(DELETE_AVATAR_COUNTER_NAME, "outcome", outcome).increment();
return null;
})
.thenRun(Util.NOOP);
}
@@ -284,4 +291,51 @@ public class ProfilesManager {
static byte[] getCacheKeyV1(UUID uuid) {
return (CACHE_PREFIX_V1 + '{' + uuid.toString() + '}').getBytes();
}
public void deleteAvatarForIdentity(final byte[] identity) {
profileAvatars.deleteAvatarUrl(identity).ifPresent(avatar -> Mono.fromFuture(() ->
deleteAvatar(avatar))
.retry(3)
.onErrorComplete()
.block());
}
/// Sets an avatar for the identity. If there was already an avatar, it will be deleted from storage.
public void setAvatarForIdentity(byte[] identity, String avatar) {
profileAvatars.setAvatarUrl(identity, avatar).map(previousAvatar -> Mono.fromFuture(() ->
deleteAvatar(previousAvatar))
.retry(3)
.onErrorComplete()
.block());
}
public Optional<String> extendAvatarTtlForIdentity(final byte[] identity) {
final Optional<String> maybePath = profileAvatars.updateAvatarTtl(identity);
return maybePath.map(key -> {
try {
// copying the object to itself extends the expiration...
Mono.fromFuture(() -> s3Client.copyObject(CopyObjectRequest.builder()
.sourceBucket(bucket)
.sourceKey(key)
.destinationBucket(bucket)
.destinationKey(key)
.metadataDirective(MetadataDirective.REPLACE)
// ...but there needs to be a trivial change, otherwise it is rejected
.metadata(Map.of("t", String.valueOf(Instant.now().getEpochSecond())))
.build()))
.retryWhen(Retry.max(3).filter(e -> !(e instanceof NoSuchKeyException)))
.block();
return key;
} catch (NoSuchKeyException _) {
logger.warn("avatar expected to be present is gone");
profileAvatars.deleteAvatarUrl(identity);
return null;
}
});
}
}
@@ -5,7 +5,23 @@ import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -13,28 +29,60 @@ import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import javax.annotation.Nullable;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
/// catching up to end-of-queue,and an infinite stream for live updates.
class FoundationDbMessagePublisher {
private final Database database;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
private final Clock clock;
/// Keeps track of the key from which to start reading on the next iteration
private volatile KeySelector beginKeyCursor;
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
private final KeySelector endKeyExclusive;
/// Keeps track of the key from which to start reading on the next iteration
private volatile KeySelector beginKeyCursor;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
@Nullable private final byte[] presenceKey;
// An ID for this specific stream for use when checking "ownership" of a presence value.
private final int streamId = NEXT_STREAM_ID.getAndIncrement();
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
@Nullable private final byte[] messagesAvailableWatchKey;
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
/// is started for the page fetch operations.
private final Supplier<Consumer<Transaction>> beforePageFetch;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
private State state = State.MESSAGES_AVAILABLE;
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
/// Reference to the sink we publish messages to.
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
/// A future for refreshing the connected client's presence value at regular intervals.
@Nullable private ScheduledFuture<?> renewPresenceFuture;
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
enum State {
/// Messages are likely available in the queue. Initial state.
@@ -70,49 +118,52 @@ class FoundationDbMessagePublisher {
FETCH_OR_PUBLISH_ERROR_OCCURRED
}
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
@Nullable private final byte[] messagesAvailableWatchKey;
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
/// is started for the page fetch operations.
private final Supplier<Consumer<Transaction>> beforePageFetch;
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
private State state = State.MESSAGES_AVAILABLE;
/// Reference to the sink we publish messages to.
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
FoundationDbMessagePublisher(
final Database database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
@Nullable final byte[] presenceKey,
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
@Nullable final byte[] messagesAvailableWatchKey,
@Nullable final BiConsumer<State, State> stateChangeListener,
final Supplier<Consumer<Transaction>> beforePageFetch) {
this.database = database;
this.clock = clock;
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.database = database;
this.maxMessagesPerScan = maxMessagesPerScan;
this.presenceKey = presenceKey;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
this.beforePageFetch = beforePageFetch;
this.messagePublisher = Flux.create(emitter -> {
if (!terminateOnQueueEmpty) {
Objects.requireNonNull(presenceKey);
Objects.requireNonNull(presenceRenewalExecutorService);
}
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
this.emitter = emitter;
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
emitter.onDispose(this::onDispose);
}).doOnSubscribe(_ -> {
if (!terminateOnQueueEmpty) {
// Establish presence immediately and block until we do. We must establish presence for watches to work as
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
// exception.
database.run(transaction -> {
setPresence(transaction);
return null;
});
// Refresh presence at regular intervals
startPresenceRenewal(presenceRenewalExecutorService);
}
});
}
@@ -121,18 +172,22 @@ class FoundationDbMessagePublisher {
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
public static FoundationDbMessagePublisher createFinitePublisher(
final Database database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
final Supplier<Consumer<Transaction>> beforePageFetch) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
return new FoundationDbMessagePublisher(database,
clock,
beginKeyInclusive,
endKeyExclusive,
database,
maxMessagesPerScan,
null,
null,
null,
null,
beforePageFetch);
}
@@ -140,17 +195,23 @@ class FoundationDbMessagePublisher {
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
/// messages and is now waiting for a live stream of new messages.
public static FoundationDbMessagePublisher createInfinitePublisher(
final Database database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
final byte[] presenceKey,
final ScheduledExecutorService presenceRenewalExecutorService,
final byte[] messagesAvailableWatchKey,
final Supplier<Consumer<Transaction>> beforePageFetch) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
return new FoundationDbMessagePublisher(database,
clock,
beginKeyInclusive,
endKeyExclusive,
database,
maxMessagesPerScan,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
null,
beforePageFetch);
@@ -345,15 +406,6 @@ class FoundationDbMessagePublisher {
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
}
private synchronized void onDispose() {
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
// in evaluating the state machine when there's no live subscription.
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
}
cancelWatch();
}
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
private synchronized void cancelWatch() {
@@ -362,4 +414,76 @@ class FoundationDbMessagePublisher {
}
}
private synchronized void startPresenceRenewal(final ScheduledExecutorService presenceRenewalExecutorService) {
final long renewalIntervalMillis =
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
renewPresenceFuture = presenceRenewalExecutorService.scheduleWithFixedDelay(this::renewPresence,
renewalIntervalMillis,
renewalIntervalMillis,
TimeUnit.MILLISECONDS);
}
private synchronized void renewPresence() {
if (state == State.TERMINATED || state == State.ERROR) {
return;
}
database.runAsync(transaction -> {
setPresence(transaction);
return CompletableFuture.completedFuture(null);
})
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to renew presence; will terminate publisher", throwable);
terminateWithError(throwable);
}
});
}
private void setPresence(final Transaction transaction) {
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
}
@VisibleForTesting
synchronized void clearPresence() {
if (renewPresenceFuture != null) {
renewPresenceFuture.cancel(true);
}
if (!terminateOnQueueEmpty) {
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
transaction.clear(presenceKey);
}
}))
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear presence on disposal", throwable);
}
});
}
}
@VisibleForTesting
synchronized void terminateWithError(final Throwable throwable) {
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.ERROR, Event.INTERNAL_TRIGGER);
}
emitter.error(throwable);
}
private synchronized void onDispose() {
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
// in evaluating the state machine when there's no live subscription.
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
}
cancelWatch();
clearPresence();
}
}
@@ -13,10 +13,12 @@ import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
@@ -24,16 +26,16 @@ import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
/// An implementation of a message store backed by FoundationDB.
@@ -54,10 +56,16 @@ public class FoundationDbMessageStore {
private final int[] liveEpochs;
private final int activeEpoch;
private final VersionstampUUIDCipher versionstampUUIDCipher;
private final ScheduledExecutorService presenceRenewalExecutorService;
private final Clock clock;
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
private static final int PRESENCE_VALUE_LENGTH = 28;
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
private static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
@VisibleForTesting
static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
/// The (approximate) transaction size beyond which we do not add more messages in a transaction. The estimated size
/// includes only message payloads (and not key reads/writes) which we assume will dominate the total
@@ -76,12 +84,6 @@ public class FoundationDbMessageStore {
private static final Timer INSERT_MESSAGE_BATCH_TIMER =
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessageBatchTimer"));
private static final Counter DELETE_MESSAGE_COUNTER =
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessage"));
private static final Timer DELETE_MESSAGE_TIMER =
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessageTimer"));
/// Result of inserting a message for a particular device
///
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
@@ -96,6 +98,7 @@ public class FoundationDbMessageStore {
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
final int activeEpoch,
final VersionstampUUIDCipher versionstampUUIDCipher,
final ScheduledExecutorService presenceRenewalExecutorService,
final Clock clock) {
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
@@ -107,6 +110,7 @@ public class FoundationDbMessageStore {
this.liveEpochs = IntStream.range(0, MAX_EPOCHS).filter(e -> databasesByEpochArray[e] != null).toArray();
this.activeEpoch = activeEpoch;
this.versionstampUUIDCipher = versionstampUUIDCipher;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.versionstampClocks = databasesByEpochMap.values().stream()
.flatMap(List::stream)
.distinct()
@@ -339,27 +343,6 @@ public class FoundationDbMessageStore {
});
}
// Note that this method is intended only for initial migration support; in general, callers should clear messages
// by acknowledging messages via a `FoundationDbMessageStream`.
public CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
}
private CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
final Timer.Sample sample = Timer.start();
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
transaction.clear(messageKey);
return CompletableFuture.completedFuture(null);
})
.thenRun(() -> {
sample.stop(DELETE_MESSAGE_TIMER);
DELETE_MESSAGE_COUNTER.increment();
});
}
public void clearAll(final AciServiceIdentifier aci) {
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
transaction.clear(getAccountSubspace(aci).range());
@@ -382,14 +365,14 @@ public class FoundationDbMessageStore {
.forEach(action);
}
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
}
@VisibleForTesting
MessageStream getMessages(final AciServiceIdentifier aci,
final Device destinationDevice,
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
final byte deviceId,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
@@ -401,13 +384,16 @@ public class FoundationDbMessageStore {
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
}
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
getPresenceKey(aci, deviceId),
getMessagesAvailableWatchKey(aci),
databasesForQueueByEpoch,
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
maxMessagesPerScan,
maxUnacknowledgedMessages,
doAfterCleanup);
doAfterCleanup,
presenceRenewalExecutorService,
clock);
}
/// Record the versionstamp for the current time in each database's versionstamp clock.
@@ -530,19 +516,56 @@ public class FoundationDbMessageStore {
}
@VisibleForTesting
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).pack("p");
static byte[] getServerId() {
return SERVER_ID;
}
@VisibleForTesting
boolean isClientPresent(final byte[] presenceValueBytes) {
if (presenceValueBytes == null) {
static byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).pack("p");
}
static byte[] getPresenceValue(final Instant timestamp, final int streamId) {
return ByteBuffer.allocate(PRESENCE_VALUE_LENGTH)
.put(SERVER_ID)
.putInt(streamId)
.putLong(timestamp.toEpochMilli())
.array();
}
@VisibleForTesting
static byte[] getPresenceServerId(final byte[] presenceValue) {
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
}
return Arrays.copyOfRange(presenceValue, 0, 16);
}
@VisibleForTesting
static int getPresenceStreamId(final byte[] presenceValue) {
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
}
return ByteBuffer.wrap(presenceValue).getInt(16);
}
@VisibleForTesting
static Instant getPresenceTimestamp(final byte[] presenceValue) {
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
}
return Instant.ofEpochMilli(ByteBuffer.wrap(presenceValue).getLong(20));
}
@VisibleForTesting
boolean isClientPresent(@Nullable final byte[] presenceValue) {
if (presenceValue == null) {
return false;
}
final long presenceValue = Conversions.byteArrayToLong(presenceValueBytes);
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
// containing the timestamp (seconds since epoch) that the client updates periodically.
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= PRESENCE_STALE_THRESHOLD.toSeconds();
return Duration.between(getPresenceTimestamp(presenceValue), clock.instant()).compareTo(PRESENCE_STALE_THRESHOLD) <= 0;
}
}
@@ -13,6 +13,7 @@ import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IdentityHashMap;
@@ -23,6 +24,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;
@@ -41,6 +43,7 @@ import reactor.util.function.Tuples;
public class FoundationDbMessageStream implements MessageStream {
private final Subspace deviceQueueSubspace;
private final byte[] presenceKey;
private final byte[] messagesAvailableWatchKey;
private final Database[] databasesByEpoch;
private final MessageGuidCodec messageGuidCodec;
@@ -48,12 +51,21 @@ public class FoundationDbMessageStream implements MessageStream {
private final int maxMessagesPerScan;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
private final ScheduledExecutorService presenceRenewalExecutorService;
private final Clock clock;
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
private final Counter messageReadCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
private final Counter messageAcknowledgedCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "messagesAcknowledged"));
private final Counter staleEphemeralMessagesCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 100;
@VisibleForTesting
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
@@ -63,19 +75,25 @@ public class FoundationDbMessageStream implements MessageStream {
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
final byte[] presenceKey,
final byte[] messagesAvailableWatchKey,
final Database[] databasesByEpoch,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
final Runnable doAfterCleanup,
final ScheduledExecutorService presenceRenewalExecutorService,
final Clock clock) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.presenceKey = presenceKey;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.databasesByEpoch = databasesByEpoch;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.clock = clock;
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
@@ -116,6 +134,11 @@ public class FoundationDbMessageStream implements MessageStream {
sink.next(messageStreamEntry);
})
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
.doOnNext(messageStreamEntry -> {
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
messageReadCounter.increment();
}
})
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
}
@@ -149,9 +172,10 @@ public class FoundationDbMessageStream implements MessageStream {
return maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
database,
clock,
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive,
database,
maxMessagesPerScan,
() -> this.clearAcknowledgedMessages(database))
.getMessages())
@@ -178,10 +202,13 @@ public class FoundationDbMessageStream implements MessageStream {
.orElseGet(() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
return FoundationDbMessagePublisher.createInfinitePublisher(
database,
clock,
infinitePublisherBeginKey,
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
database,
maxMessagesPerScan,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
() -> clearAcknowledgedMessages(database)).getMessages();
})
@@ -225,6 +252,8 @@ public class FoundationDbMessageStream implements MessageStream {
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
messageAcknowledgedCounter.increment();
return CompletableFuture.completedFuture(null);
}
@@ -133,7 +133,7 @@ public class AppleAppStoreClient {
final APIError apiError = e.getApiError();
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", apiError != null ? apiError.name() : "http_" + e.getHttpStatusCode())).increment();
throw switch (e.getApiError()) {
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> new SubscriptionNotFoundException();
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
case null, default -> throw e;
@@ -183,7 +183,7 @@ public class AppleAppStoreClient {
private static boolean shouldRetry(Throwable e) {
return e instanceof APIException apiException && switch (apiException.getApiError()) {
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE, ACCOUNT_NOT_FOUND_RETRYABLE -> true;
case null, default -> false;
};
}
@@ -0,0 +1,56 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Base64;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
public class ZkCredentialPublicKeyAdapter {
public static class Serializer extends JsonSerializer<ZkCredentialPublicKey> {
@Override
public void serialize(final ZkCredentialPublicKey zkCredentialPublicKey,
final JsonGenerator jsonGenerator,
final SerializerProvider serializers) throws IOException {
jsonGenerator.writeString(Base64.getEncoder().encodeToString(zkCredentialPublicKey.serialize()));
}
}
public static class Deserializer extends JsonDeserializer<ZkCredentialPublicKey> {
@Override
public ZkCredentialPublicKey deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
final byte[] zkCredentialPublicKeyBytes;
try {
zkCredentialPublicKeyBytes = Base64.getDecoder().decode(parser.getValueAsString());
} catch (final IllegalArgumentException e) {
throw new JsonParseException(parser, "Could not parse key as a base64-encoded value", e);
}
if (zkCredentialPublicKeyBytes.length == 0) {
return null;
}
try {
return new ZkCredentialPublicKey(zkCredentialPublicKeyBytes);
} catch (final InvalidInputException e) {
// this should really never happen, as ZkCredentialPublicKey simply extends ByteArray
throw new JsonParseException(parser, "Could not interpret bytes as a ZK credential public key", e);
}
}
}
}
@@ -69,6 +69,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
@@ -220,6 +221,8 @@ public record CommandDependencies(
.threads(1).build();
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
.threads(1).build();
final ScheduledExecutorService presenceRenewalExecutor =
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(1).build();
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
configuration.getSecureStorageServiceConfiguration());
@@ -266,6 +269,8 @@ public record CommandDependencies(
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV1().getTableName());
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
configuration.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getProfilesV2().getTableName());
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
@@ -313,8 +318,9 @@ public record CommandDependencies(
configuration.getFoundationDbMessagesConfiguration().activeEpoch(),
new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
configuration.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
presenceRenewalExecutor,
Clock.systemUTC());
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getReportMessage().getTableName(),
@@ -269,7 +269,7 @@ message LookupUsernameLinkResponse {
}
message SetZkCredentialKeyRequest {
// A serialized Ristretto key with a one-byte type prefix
// A serialized libsignal ZkCredentialPublicKey
bytes public_key = 1 [(require.exactlySize) = 33];
}
@@ -9,6 +9,8 @@ option java_multiple_files = true;
package org.signal.chat.profile;
import "google/protobuf/empty.proto";
import "org/signal/chat/common.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/require.proto";
@@ -26,6 +28,11 @@ service Profile {
// Retrieves unversioned profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
// Returns anonymous credentials that may be presented with avatar operations in ProfilesAnonymous
//
// Note: `Accounts.SetZkCredentialKey` is a pre-requisite for this RPC
rpc GetAvatarCredentials(GetAvatarCredentialsRequest) returns (GetAvatarCredentialsResponse) {}
}
// Provides methods for working with profiles and profile-related data using "unidentified access"
@@ -41,6 +48,24 @@ service ProfileAnonymous {
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {}
// Retrieves a profile key credential.
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {}
// Returns credentials to upload a v2 avatar. After uploading the avatar, the client
// must call SetProfile with the new avatar URL in the encrypted `data`.
//
// Because avatars are uploaded anonymously, they have an expiration equal to the
// idle account expiration. Clients must periodically (recommended: every 90 days)
// call ExtendAvatarTTL to extend the TTl.
//
// Note: any existing avatar associated with these credentials will be deleted immediately
rpc GetAvatarUploadForm(GetAvatarUploadFormRequest) returns (GetAvatarUploadFormResponse) {}
// Extends the TTL of the avatar currently associated with the request’s avatar auth credential
rpc ExtendAvatarTTL(ExtendAvatarTTLRequest) returns (ExtendAvatarTTLResponse) {}
// Deletes the avatar currently associated with the request’s avatar auth credential.
//
// Clients must also call SetProfile to remove the avatar from the encrypted `data`.
rpc DeleteAvatar(DeleteAvatarRequest) returns (DeleteAvatarResponse) {}
}
message SetProfileV1Request {
@@ -325,3 +350,59 @@ enum CredentialType {
CREDENTIAL_TYPE_UNSPECIFIED = 0;
CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY = 1;
}
// avatar auth
message GetAvatarCredentialsRequest {
bytes avatar_credentials_request = 1;
}
message GetAvatarCredentialsResponse {
oneof response {
bytes avatar_credentials = 1;
// the client must call Accounts.SetZkCredentialKey to call this method
errors.FailedPrecondition missing_zk_credential_key = 2 [(tag.reason) = "missing_zk_credential_key"];
}
}
message GetAvatarUploadFormRequest {
bytes avatar_credentials_presentation = 1;
// The length of the attachment for the requested upload form. Uploads
// performed with this form will be limited to the provided length.
uint32 upload_length = 2 [(require.range) = {min: 1, max: 10485760 /* 10 MiB */}];
}
message GetAvatarUploadFormResponse {
oneof response {
common.S3UploadForm avatar_upload_form = 1;
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
}
}
message ExtendAvatarTTLRequest {
bytes avatar_credentials_presentation = 1;
}
message ExtendAvatarTTLResponse {
oneof response {
// The avatar that was extended. May be used as a check against state de-synchronization.
string path = 1;
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
// the identity does not have an active avatar
errors.NotFound not_found = 3 [(tag.reason) = "no_active_avatar"];
}
}
message DeleteAvatarRequest {
bytes avatar_credentials_presentation = 1;
}
message DeleteAvatarResponse {
oneof response {
google.protobuf.Empty success = 1;
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -61,6 +60,8 @@ import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.AccountController;
@@ -707,15 +708,15 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@ParameterizedTest
@ValueSource(booleans = {true, false})
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) throws Exception {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final ZkCredentialPublicKey publicKey = ZkCredentialKeyPair.generate().getPublicKey();
final long rotationId = ThreadLocalRandom.current().nextLong(1, Long.MAX_VALUE);
final Account account = mock(Account.class);
if (matchesCurrentZkCredentialKey) {
when(account.getZkCredentialKey()).thenReturn(publicKey);
when(account.getZkCredentialKey()).thenReturn(Optional.of(publicKey));
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
}
@@ -724,7 +725,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final SetZkCredentialKeyResponse response = assertDoesNotThrow(() ->
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey))
.setPublicKey(ByteString.copyFrom(publicKey.serialize()))
.build()));
if (matchesCurrentZkCredentialKey) {
@@ -736,13 +737,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final int updateMethodCalls = matchesCurrentZkCredentialKey ? 0 : 1;
verify(accountsManager, times(updateMethodCalls)).update(eq(AUTHENTICATED_ACI), any());
verify(account, times(updateMethodCalls)).setZkCredentialKey(aryEq(publicKey));
verify(account, times(updateMethodCalls)).setZkCredentialKey(publicKey);
}
@Test
void setZkCredentialKeyRateLimited() throws Exception {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final byte[] publicKey = ZkCredentialKeyPair.generate().getPublicKey().serialize();
final Duration retryDuration = Duration.ofDays(1);
final Account account = mock(Account.class);
@@ -13,6 +13,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -20,12 +22,15 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusInvalidArgument;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import io.grpc.ServerInterceptor;
import com.google.rpc.BadRequest;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
@@ -38,6 +43,7 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
@@ -50,6 +56,12 @@ import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.DeleteAvatarRequest;
import org.signal.chat.profile.DeleteAvatarResponse;
import org.signal.chat.profile.ExtendAvatarTTLRequest;
import org.signal.chat.profile.ExtendAvatarTTLResponse;
import org.signal.chat.profile.GetAvatarUploadFormRequest;
import org.signal.chat.profile.GetAvatarUploadFormResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
@@ -66,8 +78,13 @@ import org.signal.chat.profile.ProfileAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
@@ -78,9 +95,13 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
@@ -89,6 +110,8 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.MutableClock;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -108,8 +131,15 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@Mock
private ProfileBadgeConverter profileBadgeConverter;
@Mock
private RateLimiter profileAvatarBytesRateLimiter;
private ServerZkProfileOperations zkProfileOperations;
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
private MutableClock clock;
@Override
protected ProfileAnonymousGrpcService createServiceBeforeEachTest() {
getMockRequestAttributesInterceptor().setRequestAttributes(new RequestAttributes(InetAddresses.forString("127.0.0.1"),
@@ -118,12 +148,21 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
zkProfileOperations = spy(new ServerZkProfileOperations(SERVER_SECRET_PARAMS));
final RateLimiters rateLimiters = mock(RateLimiters.class);
when(rateLimiters.getProfileAvatarBytesLimiter()).thenReturn(profileAvatarBytesRateLimiter);
clock = new MutableClock();
return new ProfileAnonymousGrpcService(
accountsManager,
profilesManager,
profileBadgeConverter,
new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey", "accessSecret"),
genericServerSecretParams,
rateLimiters,
clock,
zkProfileOperations,
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, Clock.systemUTC())
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, clock)
);
}
@@ -788,12 +827,182 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
);
}
@Override
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
return serverInterceptors.stream()
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
// updated error model
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
.toList();
@Test
void getAvatarUploadForm() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(100)
.build();
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
assertTrue(response.hasAvatarUploadForm());
final String avatarPath = response.getAvatarUploadForm().getKey();
assertFalse(avatarPath.isEmpty());
verify(profilesManager).setAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()), eq(avatarPath));
}
@Test
void getAvatarUploadFormInvalidUploadLength() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(Math.toIntExact(ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES + 1))
.build();
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
() -> authenticatedServiceStub().getAvatarUploadForm(request));
final List<BadRequest.FieldViolation> fieldViolations = GrpcTestUtils.extractDetail(BadRequest.class, statusRuntimeException)
.getFieldViolationsList();
assertEquals(1, fieldViolations.size());
assertEquals("upload_length", fieldViolations.getFirst().getField());
}
@Test
void getAvatarUploadFormInvalidCredentialsPresentation() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(100)
.build();
// trigger a verification failure by advancing the clock beyond validity
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
assertTrue(response.hasInvalidCredentialsPresentation());
}
@Test
void getAvatarUploadFormRateLimited() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final Duration retryDuration = Duration.ofMinutes(20);
doThrow(new RateLimitExceededException(retryDuration))
.when(profileAvatarBytesRateLimiter).validate(anyString(), anyLong());
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.setUploadLength(100)
.build();
assertRateLimitExceeded(retryDuration,
() -> authenticatedServiceStub().getAvatarUploadForm(request),
profilesManager);
}
@Test
void extendAvatarTtl() throws Exception {
final String path = "somePath";
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.of(path));
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
assertTrue(response.hasPath());
assertEquals(path, response.getPath());
}
@Test
void extendAvatarTtlNoActiveAvatar() throws Exception {
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.empty());
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
assertTrue(response.hasNotFound());
}
@Test
void extendAvatarTtlInvalidCredentialsPresentation() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
// trigger a verification failure by advancing the clock beyond validity
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
assertTrue(response.hasInvalidCredentialsPresentation());
}
@Test
void deleteAvatar() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
assertTrue(response.hasSuccess());
verify(profilesManager).deleteAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()));
}
@Test
void deleteAvatarInvalidCredentialsPresentation() throws Exception {
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
genericServerSecretParams, clock);
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
.build();
// trigger a verification failure by advancing the clock beyond validity
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
assertTrue(response.hasInvalidCredentialsPresentation());
}
static AvatarUploadCredentialPresentation getAvatarUploadCredentialPresentation(final GenericServerSecretParams serverSecretParams, final Clock clock) throws VerificationFailedException {
final ServiceId.Aci aci = new ServiceId.Aci(UUID.randomUUID());
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
final long rotationId = ThreadLocalRandom.current().nextLong();
final AvatarUploadCredentialRequestContext context = AvatarUploadCredentialRequestContext.create(
aci,
zkCredentialKeyPair, rotationId);
final AvatarUploadCredentialResponse avatarUploadCredentialResponse = context.getRequest()
.issueCredential(aci, zkCredentialKeyPair.getPublicKey(), rotationId, clock.instant().truncatedTo(ChronoUnit.DAYS), serverSecretParams);
return context.receiveResponse(avatarUploadCredentialResponse, clock.instant(),
serverSecretParams.getPublicParams()).present(serverSecretParams.getPublicParams());
}
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -31,7 +32,6 @@ import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.protobuf.ByteString;
import com.google.rpc.BadRequest;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.time.Clock;
@@ -60,6 +60,8 @@ import org.mockito.Mock;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetAvatarCredentialsRequest;
import org.signal.chat.profile.GetAvatarCredentialsResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileResult;
@@ -77,7 +79,12 @@ import org.signal.chat.profile.test.PlaintextProfileData;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
@@ -106,6 +113,7 @@ import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.MutableClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -122,6 +130,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setPhoneNumberSharing(ByteString.copyFrom(TestRandomUtil.nextBytes(29)))
.build();
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
@Mock
private AccountsManager accountsManager;
@@ -143,11 +153,11 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
@Mock
private ProfileBadgeConverter profileBadgeConverter;
private Clock clock;
private MutableClock clock;
@Override
protected ProfileGrpcService createServiceBeforeEachTest() {
clock = Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC"));
clock = new MutableClock(Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC")));
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
@@ -208,6 +218,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
dynamicConfigurationManager,
badgesConfiguration,
policyGenerator,
genericServerSecretParams,
profileBadgeConverter,
rateLimiters
);
@@ -893,13 +904,77 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
}
@Override
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
return serverInterceptors.stream()
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
// updated error model
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
.toList();
@Test
void getAvatarCredential() {
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
final long rotationId = 617L;
// this test needs a valid clock
clock.setTimeMillis(Instant.now().toEpochMilli());
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, rotationId);
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
GetAvatarCredentialsRequest.newBuilder()
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
.build());
assertTrue(response.hasAvatarCredentials());
assertDoesNotThrow(() -> avatarUploadCredentialRequestContext.receiveResponse(
new AvatarUploadCredentialResponse(response.getAvatarCredentials().toByteArray()),
genericServerSecretParams.getPublicParams()));
}
@Test
void getAvatarCredentialAccountNotFound() {
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.empty());
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
() -> authenticatedServiceStub().getAvatarCredentials(GetAvatarCredentialsRequest.getDefaultInstance()));
assertEquals("account not found", statusRuntimeException.getStatus().getDescription());
}
@Test
void getAvatarCredentialMissingZkCredentialKey() {
when(account.getZkCredentialKey()).thenReturn(Optional.empty());
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
GetAvatarCredentialsRequest.getDefaultInstance());
assertTrue(response.hasMissingZkCredentialKey());
assertEquals("account requires ZK credential key", response.getMissingZkCredentialKey().getDescription());
}
@Test
void getAvatarCredentialInvalidCredentialRequest() {
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
final long rotationId = 617L;
final long incorrectRotationId = rotationId + 1;
// this test needs a valid clock
clock.setTimeMillis(Instant.now().toEpochMilli());
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, incorrectRotationId);
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
() -> authenticatedServiceStub().getAvatarCredentials(
GetAvatarCredentialsRequest.newBuilder()
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
.build()));
assertEquals("invalid credential request", statusRuntimeException.getStatus().getDescription());
}
@ParameterizedTest
@@ -23,6 +23,7 @@ import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil.assertFailsWithCause;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -49,7 +50,6 @@ import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
@@ -59,6 +59,7 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -471,7 +472,7 @@ class AccountsTest {
}
@Test
void testReclaimAccountPreservesFields() {
void testReclaimAccountPreservesFields() throws Exception {
final String e164 = "+14151112222";
final UUID existingUuid = UUID.randomUUID();
final Account existingAccount =
@@ -479,7 +480,7 @@ class AccountsTest {
// the backup credential request and share-set are always preserved across account reclaims
existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
createAccount(existingAccount);
final Account secondAccount =
generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
@@ -491,11 +492,11 @@ class AccountsTest {
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElseThrow());
assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow())
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow());
assertThat(reclaimed.getZkCredentialKey()).isEqualTo(existingAccount.getZkCredentialKey());
assertThat(reclaimed.getZkCredentialKey()).hasValue(existingAccount.getZkCredentialKey().orElseThrow());
}
@Test
void testReclaimAccount() throws UsernameHashNotAvailableException {
void testReclaimAccount() throws Exception {
final String e164 = "+14151112222";
final Device device = generateDevice(DEVICE_ID_1);
final UUID existingUuid = UUID.randomUUID();
@@ -506,7 +507,7 @@ class AccountsTest {
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
existingAccount.setBackupVoucher(bv);
// ZK credential keys should be carried over across re-registration
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
createAccount(existingAccount);
@@ -0,0 +1,146 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
class AcknowledgementMirroringMessageStreamTest {
private RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private FoundationDbMessageStream foundationDbMessageStream;
private AcknowledgementMirroringMessageStream mirroringMessageStream;
private static long serialMessageTimestamp = 0;
private enum UUIDVersion {
V4,
V8
}
@BeforeEach
void setUp() {
redisDynamoDbMessageStream = mock(RedisDynamoDbMessageStream.class);
when(redisDynamoDbMessageStream.acknowledgeMessage(any(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(null));
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
when(foundationDbMessageStream.acknowledgeMessage(any(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(null));
mirroringMessageStream = new AcknowledgementMirroringMessageStream(
redisDynamoDbMessageStream,
foundationDbMessageStream);
}
@ParameterizedTest
@EnumSource(UUIDVersion.class)
void acknowledgeMessages(final UUIDVersion uuidVersion) {
final List<MessageStreamEntry> entries = new ArrayList<>();
{
for (int i = 0; i < AcknowledgementMirroringMessageStream.FOUNDATIONDB_REQUEST_SIZE + 1; i++) {
entries.add(generateEnvelopeEntry(uuidVersion));
}
entries.add(new MessageStreamEntry.QueueEmpty());
}
when(redisDynamoDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
when(foundationDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(
uuidVersion == UUIDVersion.V8 ? entries : Collections.emptyList())));
JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
message.getServerTimestamp());
}
})
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
.then()
.block();
if (uuidVersion == UUIDVersion.V8) {
entries.stream()
.filter(streamEntry -> streamEntry instanceof MessageStreamEntry.Envelope)
.map(streamEntry -> ((MessageStreamEntry.Envelope) streamEntry).message())
.forEach(envelope -> verify(foundationDbMessageStream).acknowledgeMessage(
UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp()));
} else {
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
}
}
@Test
void acknowledgeMessagesOverflow() {
final List<MessageStreamEntry> entries = new ArrayList<>();
{
for (int i = 0; i < AcknowledgementMirroringMessageStream.MAX_PENDING_ACKNOWLEDGEMENTS + 1; i++) {
entries.add(generateEnvelopeEntry(UUIDVersion.V8));
}
entries.add(new MessageStreamEntry.QueueEmpty());
}
when(redisDynamoDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
when(foundationDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.empty()));
assertThrows(IllegalStateException.class,
() -> JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
message.getServerTimestamp());
}
})
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
.then()
.block());
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
}
private static MessageStreamEntry.Envelope generateEnvelopeEntry(final UUIDVersion uuidVersion) {
final UUID messageGuid = switch (uuidVersion) {
case V4 -> UUID.randomUUID();
case V8 -> MessageGuidUtil.generateRandomV8UUID();
};
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder()
.setServerGuid(UUIDUtil.toByteString(messageGuid))
.setServerTimestamp(serialMessageTimestamp++)
.build());
}
}
@@ -166,7 +166,7 @@ public class ChangeNumberManagerTest {
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), mock(ContainerRequestContext.class));
verify(accountsManager).changeNumber(accountIdentifier, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
verify(messageSender, never()).sendMessages(eq(account), any(), any(), any(), any(), any());
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
}
@Test
@@ -1,68 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
class DeletionMirroringRedisDynamoDbMessageStreamTest {
private FoundationDbMessageStore foundationDbMessageStore;
private ExperimentEnrollmentManager experimentEnrollmentManager;
private DeletionMirroringRedisDynamoDbMessageStream deletionMirroringRedisDynamoDbMessageStream;
private static final AciServiceIdentifier ACCOUNT_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
private static final byte DEVICE_ID = Device.PRIMARY_ID;
@BeforeEach
void setUp() {
foundationDbMessageStore = mock(FoundationDbMessageStore.class);
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
deletionMirroringRedisDynamoDbMessageStream = new DeletionMirroringRedisDynamoDbMessageStream(
mock(RedisDynamoDbMessageStream.class),
foundationDbMessageStore,
experimentEnrollmentManager,
ACCOUNT_IDENTIFIER.uuid(),
DEVICE_ID);
}
@ParameterizedTest
@MethodSource
void acknowledgeMessage(final boolean enrolled, final UUID messageGuid, final boolean expectFoundationDbDeletion) {
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)))
.thenReturn(enrolled);
deletionMirroringRedisDynamoDbMessageStream.acknowledgeMessage(messageGuid, System.currentTimeMillis());
verify(foundationDbMessageStore, times(expectFoundationDbDeletion ? 1 : 0))
.delete(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid);
}
private static List<Arguments> acknowledgeMessage() {
return List.of(
Arguments.argumentSet("Not enrolled, v4 UUID", false, UUID.randomUUID(), false),
Arguments.argumentSet("Not enrolled, v8 UUID", false, MessageGuidUtil.generateRandomV8UUID(), false),
Arguments.argumentSet("Enrolled, v4 UUID", true, UUID.randomUUID(), false),
Arguments.argumentSet("Enrolled, v8 UUID", true, MessageGuidUtil.generateRandomV8UUID(), true)
);
}
}
@@ -275,6 +275,15 @@ public final class DynamoDbExtensionSchema {
.build()),
List.of(), List.of()),
PROFILE_AVATARS("profileAvatars_test",
ProfileAvatars.KEY_IDENTITY,
null,
List.of(AttributeDefinition.builder()
.attributeName(ProfileAvatars.KEY_IDENTITY)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(), List.of()),
PROFILES_V2("profilesV2_test",
ProfilesV2.KEY_ACCOUNT_UUID,
ProfilesV2.KEY_VERSION,
@@ -0,0 +1,156 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
class ProfileAvatarsTest {
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS);
private ProfileAvatars profileAvatars;
private static final Duration EXPIRATION = Duration.ofDays(1);
private static final TestClock CLOCK = TestClock.pinned(Instant.now().truncatedTo(ChronoUnit.SECONDS));
@BeforeEach
void setup() {
profileAvatars = new ProfileAvatars(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName(), EXPIRATION, CLOCK);
}
@Test
void testSet() {
final byte[] identity = TestRandomUtil.nextBytes(32);
final String avatarUrl1 = "avatar";
{
final Optional<String> previousAvatar = profileAvatars.setAvatarUrl(identity, avatarUrl1);
assertTrue(previousAvatar.isEmpty());
}
{
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
.getItem(GetItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.build());
assertTrue(response.hasItem());
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
assertEquals(avatarUrl1, response.item().get(ProfileAvatars.ATTR_URL).s());
assertEquals(CLOCK.instant().plus(EXPIRATION),
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
}
final String avatarUrl2 = "avatar2";
{
final Optional<String> previousAvatar = profileAvatars.setAvatarUrl(identity, avatarUrl2);
assertEquals(Optional.of(avatarUrl1), previousAvatar);
}
{
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
.getItem(GetItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.build());
assertTrue(response.hasItem());
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
assertEquals(avatarUrl2, response.item().get(ProfileAvatars.ATTR_URL).s());
}
}
@Test
void testUpdateTtl() {
final byte[] identity = TestRandomUtil.nextBytes(32);
final String avatarUrl = "avatar";
profileAvatars.setAvatarUrl(identity, avatarUrl);
{
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
.getItem(GetItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.build());
assertTrue(response.hasItem());
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
assertEquals(CLOCK.instant().plus(EXPIRATION),
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
}
final Instant later = CLOCK.instant().plus(Duration.ofDays(30));
CLOCK.pin(later);
profileAvatars.updateAvatarTtl(identity);
{
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
.getItem(GetItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.build());
assertTrue(response.hasItem());
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
assertEquals(later.plus(EXPIRATION),
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
}
}
@Test
void testUpdateTtlNotPresent() {
final byte[] identity = TestRandomUtil.nextBytes(32);
assertTrue(profileAvatars.updateAvatarTtl(identity).isEmpty());
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
.getItem(GetItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
.build());
assertFalse(response.hasItem(), "item should not be created as a side effect");
}
@Test
void testDelete() {
final byte[] identity = TestRandomUtil.nextBytes(32);
assertTrue(profileAvatars.deleteAvatarUrl(identity).isEmpty());
final String avatarUrl = "avatar";
profileAvatars.setAvatarUrl(identity, avatarUrl);
final Optional<String> deletedUrl = profileAvatars.deleteAvatarUrl(identity);
assertTrue(deletedUrl.isPresent());
assertEquals(avatarUrl, deletedUrl.get());
assertTrue(profileAvatars.deleteAvatarUrl(identity).isEmpty());
}
}
@@ -11,10 +11,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -42,6 +44,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
@@ -56,13 +59,18 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.S3Exception;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class ProfilesManagerTest {
private Profiles profilesV1;
private ProfilesV2 profilesV2;
private ProfileAvatars profileAvatars;
private RedisAdvancedClusterCommands<byte[], byte[]> commands;
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands;
private S3AsyncClient s3Client;
@@ -85,10 +93,11 @@ public class ProfilesManagerTest {
profilesV1 = mock(Profiles.class);
profilesV2 = mock(ProfilesV2.class);
profileAvatars = mock(ProfileAvatars.class);
s3Client = mock(S3AsyncClient.class);
setLuaScript = mock(ClusterLuaScript.class);
profilesManager = new ProfilesManager(profilesV1, profilesV2, cacheCluster, mock(ScheduledExecutorService.class),
profilesManager = new ProfilesManager(profilesV1, profilesV2, profileAvatars, cacheCluster, mock(ScheduledExecutorService.class),
s3Client, BUCKET, setLuaScript);
}
@@ -449,6 +458,104 @@ public class ProfilesManagerTest {
);
}
@Test
void setAvatarForIdentity() {
final byte[] identity = new byte[1];
final String url1 = "url1";
when(profileAvatars.setAvatarUrl(any(byte[].class), anyString()))
.thenReturn(Optional.empty());
profilesManager.setAvatarForIdentity(identity, url1);
verify(profileAvatars).setAvatarUrl(identity, url1);
verifyNoInteractions(s3Client);
when(profileAvatars.setAvatarUrl(any(byte[].class), anyString()))
.thenReturn(Optional.of(url1));
final String url2 = "url2";
profilesManager.setAvatarForIdentity(identity, url2);
verify(profileAvatars).setAvatarUrl(identity, url2);
verify(s3Client).deleteObject(argThat((DeleteObjectRequest r) -> url1.equals(r.key())));
}
@Test
void extendAvatarTtlForIdentity() {
final String avatarPath = "somePath";
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
assertEquals(Optional.of(avatarPath), profilesManager.extendAvatarTtlForIdentity(new byte[1]));
final ArgumentCaptor<CopyObjectRequest> copyObjectRequestArgumentCaptor = ArgumentCaptor.forClass(CopyObjectRequest.class);
verify(s3Client).copyObject(copyObjectRequestArgumentCaptor.capture());
assertEquals(avatarPath, copyObjectRequestArgumentCaptor.getValue().sourceKey());
assertEquals(avatarPath, copyObjectRequestArgumentCaptor.getValue().destinationKey());
}
@Test
void extendAvatarTtlForIdentityNotFound() {
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.empty());
assertTrue(profilesManager.extendAvatarTtlForIdentity(new byte[1]).isEmpty());
verifyNoInteractions(s3Client);
}
@Test
void extendAvatarTtlForIdentityS3NoSuchKey() {
final String avatarPath = "somePath";
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
when(s3Client.copyObject(any(CopyObjectRequest.class)))
.thenReturn(CompletableFuture.failedFuture(NoSuchKeyException.builder().build()));
assertTrue(profilesManager.extendAvatarTtlForIdentity(new byte[1]).isEmpty());
verify(s3Client).copyObject(any(CopyObjectRequest.class));
verify(profileAvatars).deleteAvatarUrl(any(byte[].class));
}
@Test
void extendAvatarTtlForIdentityS3Retry() {
final String avatarPath = "somePath";
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
when(s3Client.copyObject(any(CopyObjectRequest.class)))
.thenReturn(CompletableFuture.failedFuture(S3Exception.builder().build()))
.thenReturn(CompletableFuture.completedFuture(mock(CopyObjectResponse.class)));
assertEquals(Optional.of(avatarPath), profilesManager.extendAvatarTtlForIdentity(new byte[1]));
verify(s3Client, times(2)).copyObject(any(CopyObjectRequest.class));
verify(profileAvatars, never()).deleteAvatarUrl(any(byte[].class));
}
@Test
void deleteAvatarForIdentity() {
final String avatarPath = "somePath";
when(profileAvatars.deleteAvatarUrl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
profilesManager.deleteAvatarForIdentity(new byte[1]);
final ArgumentCaptor<DeleteObjectRequest> deleteObjectRequestArgumentCaptor = ArgumentCaptor.forClass(
DeleteObjectRequest.class);
verify(s3Client).deleteObject(deleteObjectRequestArgumentCaptor.capture());
assertEquals(avatarPath, deleteObjectRequestArgumentCaptor.getValue().key());
}
@Test
void deleteAvatarForIdentityNotFound() {
when(profileAvatars.deleteAvatarUrl(any(byte[].class))).thenReturn(Optional.empty());
profilesManager.deleteAvatarForIdentity(new byte[1]);
verifyNoInteractions(s3Client);
}
@Nested
class Redis {
@@ -457,7 +564,7 @@ public class ProfilesManagerTest {
@BeforeEach
void setUp() throws Exception {
profilesManager = new ProfilesManager(profilesV1, profilesV2, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
profilesManager = new ProfilesManager(profilesV1, profilesV2, profileAvatars, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
s3Client, BUCKET);
}
@@ -16,20 +16,27 @@ import com.apple.foundationdb.Range;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.async.AsyncIterable;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.protobuf.InvalidProtocolBufferException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
@@ -46,6 +53,8 @@ class FoundationDbMessagePublisherTest {
private Database database;
private List<FoundationDbMessagePublisher.State> stateTransitions;
private static ScheduledExecutorService presenceRenewalExecutorService;
private static final AciServiceIdentifier SERVICE_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
private static final Range SUBSPACE_RANGE =
@@ -56,6 +65,15 @@ class FoundationDbMessagePublisherTest {
private static final Supplier<Consumer<Transaction>> NOOP_ON_PAGE_FETCH = () -> _ -> {};
private static final Clock CLOCK = Clock.systemUTC();
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
@BeforeAll
static void setUpBeforeAll() {
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
}
@BeforeEach
void setUp() {
database = mock(Database.class);
@@ -65,8 +83,15 @@ class FoundationDbMessagePublisherTest {
new SecureRandom().nextBytes(messageGuidCodecKey);
}
@AfterAll
static void tearDownAfterAll() throws InterruptedException {
presenceRenewalExecutorService.shutdown();
//noinspection ResultOfMethodCallIgnored
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
void finitePublisherMultipleBatches() throws InvalidProtocolBufferException {
void finitePublisherMultipleBatches() {
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
@@ -95,11 +120,14 @@ class FoundationDbMessagePublisherTest {
});
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
database,
CLOCK,
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
database,
2, // With 3 messages and batch size set to 2, we'll need to grab 2 batches.
null,
null,
null,
(_, newState) -> stateTransitions.add(newState),
NOOP_ON_PAGE_FETCH
);
@@ -166,10 +194,13 @@ class FoundationDbMessagePublisherTest {
.thenReturn(watchFuture3);
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
database,
CLOCK,
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
database,
2,
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
(oldState, newState) -> {
stateTransitions.add(newState);
@@ -215,7 +246,7 @@ class FoundationDbMessagePublisherTest {
}
@Test
void messageAvailableWatchSignalBuffered() throws InvalidProtocolBufferException {
void messageAvailableWatchSignalBuffered() {
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
@@ -248,10 +279,13 @@ class FoundationDbMessagePublisherTest {
.thenReturn(watchFuture2);
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
database,
CLOCK,
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
database,
2,
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
(oldState, newState) -> {
stateTransitions.add(newState);
@@ -292,12 +326,15 @@ class FoundationDbMessagePublisherTest {
@Test
@SuppressWarnings({"unchecked", "resource"})
void watchCanceledOnSubscriptionCancel() throws InvalidProtocolBufferException {
void watchCanceledOnSubscriptionCancel() {
final FoundationDbMessagePublisher infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
database,
CLOCK,
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
database,
100,
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
() -> _ -> {});
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
@@ -325,6 +362,61 @@ class FoundationDbMessagePublisherTest {
verify(watchFuture).cancel(true);
}
@Test
@SuppressWarnings({"unchecked", "resource"})
void terminateWithError() {
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
final KeyValue keyValue = mockKeyValue((byte) 5, message);
final AsyncIterable<KeyValue> keyValues = mock(AsyncIterable.class);
when(keyValues.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue)));
final Transaction transaction = mock(Transaction.class);
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(StreamingMode.class)))
.thenReturn(keyValues);
when(transaction.get(FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID)))
.thenAnswer(_ -> CompletableFuture.completedFuture(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
when(transaction.watch(any()))
.thenReturn(new CompletableFuture<>());
when(database.runAsync(any(Function.class))).thenAnswer(
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
0);
return f.apply(transaction);
});
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
database,
CLOCK,
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
2,
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
(_, newState) -> stateTransitions.add(newState),
NOOP_ON_PAGE_FETCH
);
final RuntimeException streamTerminationException = new RuntimeException("Stream terminated");
StepVerifier.create(infinitePublisher.getMessages())
.expectNext(getExpectedMessageStreamEntry(keyValue))
.then(() -> infinitePublisher.terminateWithError(streamTerminationException))
.verifyErrorMatches(throwable -> throwable.equals(streamTerminationException));
assertEquals(List.of(
FoundationDbMessagePublisher.State.FETCHING_MESSAGES,
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES,
FoundationDbMessagePublisher.State.ERROR
),
stateTransitions
);
}
private FoundationDbMessageStreamEntry.Message getExpectedMessageStreamEntry(final KeyValue keyValue) {
try {
return new FoundationDbMessageStreamEntry.Message(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()),
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -18,9 +19,11 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dropwizard.util.DataSize;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -34,6 +37,9 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -43,6 +49,8 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@@ -50,6 +58,7 @@ import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
@@ -60,7 +69,6 @@ import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -77,11 +85,20 @@ class FoundationDbMessageStoreTest {
private VersionstampUUIDCipher versionstampUUIDCipher;
private FoundationDbMessageStore foundationDbMessageStore;
private static ScheduledExecutorService presenceRenewalExecutorService;
private static final TestClock CLOCK = TestClock.pinned(Instant.ofEpochSecond(500));
private static final int DEFAULT_EPOCH = 0;
private static final int FUTURE_EPOCH = 2;
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
@BeforeAll
static void setUpBeforeAll() {
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
}
@BeforeEach
void setup() {
final byte[] versionstampCipherKey = new byte[16];
@@ -101,9 +118,17 @@ class FoundationDbMessageStoreTest {
),
DEFAULT_EPOCH,
versionstampUUIDCipher,
presenceRenewalExecutorService,
CLOCK);
}
@AfterAll
static void tearDownAfterAll() throws InterruptedException {
presenceRenewalExecutorService.shutdown();
//noinspection ResultOfMethodCallIgnored
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.SECONDS);
}
@ParameterizedTest
@MethodSource
void insert(final long presenceUpdatedBeforeSeconds,
@@ -117,7 +142,7 @@ class FoundationDbMessageStoreTest {
.mapToObj(i -> (byte) i)
.toList();
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, 1, presenceUpdatedBeforeSeconds));
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, presenceUpdatedBeforeSeconds));
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
@@ -221,13 +246,12 @@ class FoundationDbMessageStoreTest {
@Test
void versionstampCorrectlyUpdatedOnMultipleInserts() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
writePresenceKey(aci, Device.PRIMARY_ID, 10L);
foundationDbMessageStore.insert(Map.of(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false)))).join();
final Map<Byte, FoundationDbMessageStore.InsertResult> secondMessageInsertResult = foundationDbMessageStore.insert(aci,
Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
final Optional<Versionstamp> messagesAvailableWatchVersionstamp = getMessagesAvailableWatch(aci);
assertTrue(messagesAvailableWatchVersionstamp.isPresent());
assertEquals(
secondMessageInsertResult.get(Device.PRIMARY_ID).versionstamp(),
messagesAvailableWatchVersionstamp);
@@ -241,7 +265,7 @@ class FoundationDbMessageStoreTest {
.mapToObj(i -> (byte) i)
.toList();
// Only 1 device has a recent presence, the others do not have presence keys present.
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
writePresenceKey(aci, Device.PRIMARY_ID, 10L);
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
final Map<Byte, FoundationDbMessageStore.InsertResult> result = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
@@ -271,7 +295,24 @@ class FoundationDbMessageStoreTest {
"Non-ephemeral messages must always be stored");
});
}
}
@Test
void getPresenceServerId() {
assertArrayEquals(FoundationDbMessageStore.getServerId(),
FoundationDbMessageStore.getPresenceServerId(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
}
@Test
void getPresenceStreamId() {
assertEquals(STREAM_ID,
FoundationDbMessageStore.getPresenceStreamId(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
}
@Test
void getPresenceTimestamp() {
assertEquals(CLOCK.instant().truncatedTo(ChronoUnit.MILLIS),
FoundationDbMessageStore.getPresenceTimestamp(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
}
@ParameterizedTest
@@ -285,14 +326,14 @@ class FoundationDbMessageStoreTest {
Arguments.argumentSet("Presence value doesn't exist",
null, false),
Arguments.argumentSet("Presence updated recently",
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(5))), true),
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minusSeconds(5), STREAM_ID), true),
Arguments.argumentSet("Presence updated same second as current time",
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(0))), true),
FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID), true),
Arguments.argumentSet(
"Presence updated exactly at the second before which it would have been considered offline",
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(300))), true),
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minus(FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD), STREAM_ID), true),
Arguments.argumentSet("Presence expired",
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(400))), false)
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minus(FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.plusSeconds(1)), STREAM_ID), false)
);
}
@@ -336,7 +377,7 @@ class FoundationDbMessageStoreTest {
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
final MultiRecipientTestConfig testConfig = testConfigs.get(i);
if (testConfig.devicePresent()) {
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L));
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 10L));
}
}
@@ -452,36 +493,6 @@ class FoundationDbMessageStoreTest {
Map.of(generateRandomAciForShard(0), Collections.emptyMap())));
}
@Test
void delete() {
final AciServiceIdentifier deletedMessageAci = new AciServiceIdentifier(UUID.randomUUID());
final byte deletedMessageDeviceId = Device.PRIMARY_ID;
final MessageProtos.Envelope deletedMessage = generateRandomMessage(false);
final AciServiceIdentifier retainedMessageAci = new AciServiceIdentifier(UUID.randomUUID());
final byte retainedMessageDeviceId = Device.PRIMARY_ID;
final MessageProtos.Envelope retainedMessage = generateRandomMessage(false);
final UUID deletedMessageGuid =
foundationDbMessageStore.insert(deletedMessageAci, Map.of(deletedMessageDeviceId, deletedMessage)).join()
.get(deletedMessageDeviceId).messageGuid().orElseThrow();
foundationDbMessageStore.insert(retainedMessageAci, Map.of(retainedMessageDeviceId, retainedMessage)).join();
assertArrayEquals(deletedMessage.toByteArray(),
getItemsInDeviceQueue(deletedMessageAci, deletedMessageDeviceId).getFirst().getValue());
assertArrayEquals(retainedMessage.toByteArray(),
getItemsInDeviceQueue(retainedMessageAci, retainedMessageDeviceId).getFirst().getValue());
foundationDbMessageStore.delete(deletedMessageAci, deletedMessageDeviceId, deletedMessageGuid).join();
assertTrue(getItemsInDeviceQueue(deletedMessageAci, deletedMessageDeviceId).isEmpty());
assertArrayEquals(retainedMessage.toByteArray(),
getItemsInDeviceQueue(retainedMessageAci, retainedMessageDeviceId).getFirst().getValue());
}
@Test
void clearAllForAccount() {
final AciServiceIdentifier deletedAccountIdentifier = new AciServiceIdentifier(UUID.randomUUID());
@@ -544,7 +555,6 @@ class FoundationDbMessageStoreTest {
@MethodSource
void getMessages(final int numMessages, final int batchSize) {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
final List<Versionstamp> expectedVersionstamps = IntStream.range(0, numMessages)
.mapToObj(_ -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join()
@@ -553,10 +563,9 @@ class FoundationDbMessageStoreTest {
.orElseThrow())
.toList();
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device, batchSize, numMessages,
Util.NOOP);
final MessageStream messageStream =
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, numMessages, Util.NOOP);
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
.recordWith(() -> retrievedEntries)
@@ -592,9 +601,6 @@ class FoundationDbMessageStoreTest {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = Device.PRIMARY_ID;
final Device device = new Device();
device.setId(deviceId);
final int messagesPerBatch = 8;
final AtomicLong serialTimestamp = new AtomicLong();
@@ -608,7 +614,7 @@ class FoundationDbMessageStoreTest {
final List<MessageProtos.Envelope> liveDefaultEpochMessages = new ArrayList<>();
final List<MessageProtos.Envelope> liveFutureEpochMessages = new ArrayList<>();
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
final CountDownLatch queueEmptyLatch = new CountDownLatch(1);
@@ -625,9 +631,6 @@ class FoundationDbMessageStoreTest {
}
});
writePresenceKey(aci, deviceId, 1, 5L, DEFAULT_EPOCH);
writePresenceKey(aci, deviceId, 1, 5L, FUTURE_EPOCH);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
.recordWith(() -> retrievedEntries)
.expectNextCount(existingDefaultEpochMessages.size() + existingFutureEpochMessages.size())
@@ -656,7 +659,6 @@ class FoundationDbMessageStoreTest {
final MessageGuidCodec messageGuidCodec =
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
final MessageProtos.Envelope message1 = generateRandomMessage(false);
final Versionstamp versionstamp1 = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message1)).join()
.get(Device.PRIMARY_ID)
@@ -689,9 +691,7 @@ class FoundationDbMessageStoreTest {
}
});
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
.expectNext(new MessageStreamEntry.Envelope(message1
.toBuilder()
@@ -714,7 +714,7 @@ class FoundationDbMessageStoreTest {
@Test
void getMessagesPublishMoreAfterSubscriptionStarts() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
for (int i = 0; i < 16; i++) {
final MessageProtos.Envelope message = generateRandomMessage(false);
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message)).join());
@@ -723,7 +723,7 @@ class FoundationDbMessageStoreTest {
final CountDownLatch latch = new CountDownLatch(1);
Thread.ofVirtual().start(() -> {
try {
// Wait until queue is empty
// Wait for a first message to get consumed
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
// Then publish more messages
for (int i = 0; i < 16; i++) {
@@ -735,9 +735,7 @@ class FoundationDbMessageStoreTest {
}
});
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
// Initially only request a single message, then give the go ahead to the publisher. This verifies that we get the
// queue empty signal when we consume the initial batch of messages even though the publisher keeps publishing in
// the meantime.
@@ -751,6 +749,116 @@ class FoundationDbMessageStoreTest {
.verifyTimeout(Duration.ofSeconds(3));
}
@Test
void getMessagesPresence() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
for (int i = 0; i < 16; i++) {
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
}
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
assertFalse(isPresent(aci, Device.PRIMARY_ID));
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), 16)
.expectNextCount(16)
.then(() -> assertFalse(isPresent(aci, Device.PRIMARY_ID),
"Client should not be present until infinite stream begins"))
.thenRequest(1)
.expectNext(new MessageStreamEntry.QueueEmpty())
.then(() -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join())
.thenRequest(1)
.expectNextCount(1)
.then(() -> assertTrue(isPresent(aci, Device.PRIMARY_ID),
"Client should be present after infinite stream begins"))
.verifyTimeout(Duration.ofSeconds(3));
final Instant deadline = Instant.now().plus(Duration.ofSeconds(1));
boolean presenceCleared = false;
while (!presenceCleared && Instant.now().isBefore(deadline)) {
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
.thenApply(Objects::isNull)
.join();
}
assertTrue(presenceCleared,
"Presence should be cleared after subscription disposal");
}
private enum PresenceConflictType {
SERVER_ID,
STREAM_ID
}
@ParameterizedTest
@EnumSource
void getMessagesPresenceConflictAtDisposal(final PresenceConflictType presenceConflictType) {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
for (int i = 0; i < 16; i++) {
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
}
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
assertFalse(isPresent(aci, Device.PRIMARY_ID));
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), 16)
.expectNextCount(16)
.then(() -> assertFalse(isPresent(aci, Device.PRIMARY_ID),
"Client should not be present until infinite stream begins"))
.thenRequest(1)
.expectNext(new MessageStreamEntry.QueueEmpty())
.then(() -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join())
.thenRequest(1)
.expectNextCount(1)
.then(() -> assertTrue(isPresent(aci, Device.PRIMARY_ID),
"Client should be present after infinite stream begins"))
.then(() -> {
// Overwrite some part of the presence value to simulate a conflict with another server or stream
final byte [] presenceValue = switch (presenceConflictType) {
case SERVER_ID -> ByteBuffer.wrap(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID))
.putLong(0, ThreadLocalRandom.current().nextLong())
.putLong(8, ThreadLocalRandom.current().nextLong())
.array();
case STREAM_ID -> ByteBuffer.wrap(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID))
.putInt(16, STREAM_ID + 1)
.array();
};
foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction -> {
transaction.set(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID), presenceValue);
return null;
});
})
.thenCancel()
.verify();
final Instant deadline = Instant.now().plus(Duration.ofSeconds(1));
boolean presenceCleared = false;
while (!presenceCleared && Instant.now().isBefore(deadline)) {
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
.thenApply(Objects::isNull)
.join();
}
assertFalse(presenceCleared,
"Presence should not be cleared if presence was established on another instance");
}
private boolean isPresent(final AciServiceIdentifier aci, final byte deviceId) {
return foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction ->
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, deviceId))
.thenApply(foundationDbMessageStore::isClientPresent))
.join();
}
@ParameterizedTest
@MethodSource
void acknowledgeMessages(final int numMessages, final Set<Integer> unacknowledgedMessages)
@@ -758,7 +866,6 @@ class FoundationDbMessageStoreTest {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final MessageGuidCodec messageGuidCodec =
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
final List<Versionstamp> versionstamps = IntStream.range(0, numMessages)
.mapToObj(
@@ -768,10 +875,8 @@ class FoundationDbMessageStoreTest {
.orElseThrow())
.toList();
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final CountDownLatch latch = new CountDownLatch(1);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
latch::countDown);
@@ -832,12 +937,7 @@ class FoundationDbMessageStoreTest {
void acknowledgeMessagesEpochChange() throws InterruptedException {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = Device.PRIMARY_ID;
final Device device = new Device();
device.setId(deviceId);
final int messagesPerBatch = 8;
final AtomicLong serialTimestamp = new AtomicLong();
generateAndInsertMessages(aci, deviceId, DEFAULT_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement);
@@ -847,7 +947,7 @@ class FoundationDbMessageStoreTest {
final CountDownLatch cleanupLatch = new CountDownLatch(1);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci,
device,
deviceId,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
cleanupLatch::countDown);
@@ -870,7 +970,7 @@ class FoundationDbMessageStoreTest {
}
{
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
@@ -896,15 +996,12 @@ class FoundationDbMessageStoreTest {
final int maxUnacknowledgedMessages = 3;
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
for (int i = 0; i < numMessages; i++) {
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
}
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
maxUnacknowledgedMessages,
Util.NOOP);
@@ -920,7 +1017,7 @@ class FoundationDbMessageStoreTest {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final MessageGuidCodec messageGuidCodec =
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
writePresenceKey(aci, Device.PRIMARY_ID, 5L);
// Insert an ephemeral message that will be read by the finite publisher and immediately acknowledged and discarded
final Versionstamp acknowledgedVersionstamp = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(true)))
@@ -949,10 +1046,7 @@ class FoundationDbMessageStoreTest {
}
});
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
cleanUpLatch::countDown);
@@ -991,15 +1085,14 @@ class FoundationDbMessageStoreTest {
final Instant testTime = oldTime.plus(Duration.ofDays(3));
final List<AciServiceIdentifier> acis = IntStream.range(0, 1024).mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID())).toList();
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final byte deviceId = Device.PRIMARY_ID;
// insert some old messages
CompletableFuture.allOf(
IntStream.range(0, 10)
.mapToObj(_ -> foundationDbMessageStore.insert(
acis.stream()
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(Device.PRIMARY_ID, generateRandomMessage(false))))))
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(deviceId, generateRandomMessage(false))))))
.toArray(CompletableFuture[]::new))
.join();
@@ -1013,19 +1106,19 @@ class FoundationDbMessageStoreTest {
IntStream.range(0, 10)
.mapToObj(_ -> foundationDbMessageStore.insert(
acis.stream()
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(Device.PRIMARY_ID, generateRandomMessage(false))))))
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(deviceId, generateRandomMessage(false))))))
.toArray(CompletableFuture[]::new))
.join();
// advance to a future date, and clear messages before the threshold
CLOCK.pin(testTime);
foundationDbMessageStore.deleteMessagesBefore(
acis.stream().collect(Collectors.toMap(Function.identity(), _ -> List.of(Device.PRIMARY_ID))),
acis.stream().collect(Collectors.toMap(Function.identity(), _ -> List.of(deviceId))),
threshold);
// make sure we have new but not old messages
for (AciServiceIdentifier aci : acis) {
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
final List<MessageProtos.Envelope> messages =
JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
@@ -1119,35 +1212,16 @@ class FoundationDbMessageStoreTest {
private void writePresenceKey(final AciServiceIdentifier aci,
final byte deviceId,
final int serverId,
final long secondsBeforeCurrentTime) {
writePresenceKey(aci, deviceId, serverId, secondsBeforeCurrentTime, DEFAULT_EPOCH);
}
private void writePresenceKey(final AciServiceIdentifier aci,
final byte deviceId,
final int serverId,
final long secondsBeforeCurrentTime,
final int epoch) {
foundationDbMessageStore.getShardForAci(aci, epoch).run(transaction -> {
final byte[] presenceKey = foundationDbMessageStore.getPresenceKey(aci, deviceId);
final long presenceUpdateEpochSeconds = getEpochSecondsBeforeClock(secondsBeforeCurrentTime);
final long presenceValue = constructPresenceValue(serverId, presenceUpdateEpochSeconds);
transaction.set(presenceKey, Conversions.longToByteArray(presenceValue));
foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction -> {
final byte[] presenceKey = FoundationDbMessageStore.getPresenceKey(aci, deviceId);
final byte[] presenceValue = FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minusSeconds(secondsBeforeCurrentTime), STREAM_ID);
transaction.set(presenceKey, presenceValue);
return null;
});
}
private static long getEpochSecondsBeforeClock(final long secondsBefore) {
return CLOCK.instant().minusSeconds(secondsBefore).getEpochSecond();
}
private static long constructPresenceValue(final int serverId, final long presenceUpdateEpochSeconds) {
return (long) (serverId & 0x0ffff) << 48 | (presenceUpdateEpochSeconds & 0x0000ffffffffffffL);
}
private AciServiceIdentifier generateRandomAciForShard(final int shardNumber) {
return generateRandomAciForShard(shardNumber, DEFAULT_EPOCH);
}
@@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.subscriptions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
@@ -63,6 +64,19 @@ class AppleAppStoreClientTest {
verifyNoInteractions(sandboxClient);
}
@ParameterizedTest
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"TRANSACTION_ID_NOT_FOUND", "ORIGINAL_TRANSACTION_ID_NOT_FOUND", "ACCOUNT_NOT_FOUND"})
public void notFound(APIError error) throws APIException, IOException {
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, error, "test"));
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, error, "test"));
assertThatExceptionOfType(SubscriptionNotFoundException.class)
.isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()));
}
@Test
public void fallbackOnNoTransactionFound()
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
@@ -158,6 +158,8 @@ zkConfig-libsignal-0.42.serverSecret: ALxy0qUiV9B3OgF1GzTgn6g4NSN22ww87p5xOlYkyp
genericZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
callingZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
backupsZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
profileAvatarsZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
paymentsService.fixerApiKey: unset
paymentsService.coinGeckoApiKey: unset
@@ -134,6 +134,8 @@ dynamoDbTables:
expiration: P90D
phoneNumberIdentifiers:
tableName: pni_test
profileAvatars:
tableName: profileAvatars_test
profiles:
tableName: profiles_test
profilesV2:
@@ -335,6 +337,9 @@ callingZkConfig:
backupsZkConfig:
serverSecret: secret://backupsZkConfig.serverSecret
profileAvatarsZkConfig:
serverSecret: secret://profileAvatarsZkConfig.serverSecret
dynamicConfig:
type: static
object: |