Add avatars to profiles gRPC

This commit is contained in:
Chris Eager authored and Chris Eager committed 2026-06-29 13:15:07 -05:00
1 parent f588390bdb
commit 8f24d28da3
27 files changed
+1173 -84

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)
@@ -740,7 +743,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);
@@ -911,6 +914,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 +1068,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 +1094,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 +1375,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,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;
}
});
}
}
@@ -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;
@@ -266,6 +267,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()
@@ -314,7 +317,7 @@ public record CommandDependencies(
new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
configuration.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
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);
@@ -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);
}
@@ -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: |