mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 12:06:53 +00:00
Profiles gRPC: initial v2 implementation
This commit is contained in:
1 parent
1b11c3efc2
commit
1e3b2c8ce8
38 files changed
+3163
-1063
No files matched your search
@@ -238,6 +238,7 @@ import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
@@ -469,8 +470,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getClientReleases().getTableName());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getProfiles().getTableName());
|
||||
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getProfilesV1().getTableName());
|
||||
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
|
||||
|
||||
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
|
||||
.credentialsProvider(awsCredentialsProvider)
|
||||
@@ -678,7 +680,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock, experimentEnrollmentManager);
|
||||
|
||||
+10
-1
@@ -64,6 +64,7 @@ public class DynamoDbTables {
|
||||
private final TableWithExpiration onetimeDonations;
|
||||
private final Table phoneNumberIdentifiers;
|
||||
private final Table profiles;
|
||||
private final Table profilesV2;
|
||||
private final Table pushChallenge;
|
||||
private final Table pushNotificationExperimentSamples;
|
||||
private final TableWithExpiration redeemedReceipts;
|
||||
@@ -92,6 +93,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
|
||||
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
|
||||
@JsonProperty("profiles") final Table profiles,
|
||||
@JsonProperty("profilesV2") final Table profilesV2,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
|
||||
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
|
||||
@@ -119,6 +121,7 @@ public class DynamoDbTables {
|
||||
this.onetimeDonations = onetimeDonations;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.profiles = profiles;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.pushChallenge = pushChallenge;
|
||||
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
|
||||
this.redeemedReceipts = redeemedReceipts;
|
||||
@@ -228,10 +231,16 @@ public class DynamoDbTables {
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getProfiles() {
|
||||
public Table getProfilesV1() {
|
||||
return profiles;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getProfilesV2() {
|
||||
return profilesV2;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getPushChallenge() {
|
||||
|
||||
+26
-28
@@ -62,6 +62,8 @@ import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
|
||||
import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -94,7 +96,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
@@ -172,33 +174,28 @@ public class ProfileController {
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
final Optional<VersionedProfile> currentProfile =
|
||||
profilesManager.get(auth.accountIdentifier(), request.version());
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return Response.status(Response.Status.PRECONDITION_FAILED).build();
|
||||
}
|
||||
|
||||
final Optional<VersionedProfileV1> currentProfile =
|
||||
profilesManager.getV1(auth.accountIdentifier(), request.version());
|
||||
|
||||
if (request.paymentAddress() != null && request.paymentAddress().length != 0) {
|
||||
final boolean hasDisallowedPrefix =
|
||||
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
|
||||
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
|
||||
|
||||
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
|
||||
if (hasDisallowedPrefix && currentProfile.map(VersionedProfileV1::paymentAddress).isEmpty()) {
|
||||
return Response.status(Response.Status.FORBIDDEN).build();
|
||||
}
|
||||
}
|
||||
|
||||
Optional<String> currentAvatar = Optional.empty();
|
||||
if (currentProfile.isPresent() && currentProfile.get().avatar() != null && currentProfile.get().avatar()
|
||||
.startsWith("profiles/")) {
|
||||
currentAvatar = Optional.of(currentProfile.get().avatar());
|
||||
}
|
||||
final Optional<String> currentAvatar = ProfileHelper.getCurrentAvatar(currentProfile);
|
||||
final String avatar = ProfileHelper.getAvatar(request.getAvatarChange(), currentAvatar);
|
||||
|
||||
final String avatar = switch (request.getAvatarChange()) {
|
||||
case UNCHANGED -> currentAvatar.orElse(null);
|
||||
case CLEAR -> null;
|
||||
case UPDATE -> ProfileHelper.generateAvatarObjectName();
|
||||
};
|
||||
|
||||
profilesManager.set(auth.accountIdentifier(),
|
||||
new VersionedProfile(
|
||||
profilesManager.setV1(auth.accountIdentifier(),
|
||||
new VersionedProfileV1(
|
||||
request.version(),
|
||||
request.name(),
|
||||
avatar,
|
||||
@@ -440,13 +437,14 @@ public class ProfileController {
|
||||
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
|
||||
|
||||
if (account.getCurrentProfileVersion().map(version::equals).orElse(false)) {
|
||||
expiringProfileKeyCredentialResponse = profilesManager.get(account.getUuid(), version)
|
||||
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
|
||||
.map(profile -> {
|
||||
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
|
||||
HexFormat.of().parseHex(encodedCredentialRequest),
|
||||
profile, new ServiceId.Aci(account.getUuid()), zkProfileOperations);
|
||||
new ProfileKeyCredentialRequest(HexFormat.of().parseHex(encodedCredentialRequest)),
|
||||
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getUuid()),
|
||||
zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw new BadRequestException(e);
|
||||
}
|
||||
@@ -468,7 +466,7 @@ public class ProfileController {
|
||||
final boolean hasCredentialRequest,
|
||||
final ContainerRequestContext containerRequestContext) {
|
||||
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
|
||||
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getUuid(), version);
|
||||
|
||||
if (maybeProfile.isEmpty()) {
|
||||
// this can happen if an account re-registers, which includes some device-transfer scenarios
|
||||
@@ -481,17 +479,17 @@ public class ProfileController {
|
||||
.increment();
|
||||
}
|
||||
|
||||
final byte[] name = maybeProfile.map(VersionedProfile::name).orElse(null);
|
||||
final byte[] about = maybeProfile.map(VersionedProfile::about).orElse(null);
|
||||
final byte[] aboutEmoji = maybeProfile.map(VersionedProfile::aboutEmoji).orElse(null);
|
||||
final String avatar = maybeProfile.map(VersionedProfile::avatar).orElse(null);
|
||||
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfile::phoneNumberSharing).orElse(null);
|
||||
final byte[] name = maybeProfile.map(VersionedProfileV1::name).orElse(null);
|
||||
final byte[] about = maybeProfile.map(VersionedProfileV1::about).orElse(null);
|
||||
final byte[] aboutEmoji = maybeProfile.map(VersionedProfileV1::aboutEmoji).orElse(null);
|
||||
final String avatar = maybeProfile.map(VersionedProfileV1::avatar).orElse(null);
|
||||
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfileV1::phoneNumberSharing).orElse(null);
|
||||
|
||||
// Allow requests where either the version matches the latest version on Account or the latest version on Account
|
||||
// is empty to read the payment address.
|
||||
final byte[] paymentAddress = maybeProfile
|
||||
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(version)).orElse(true))
|
||||
.map(VersionedProfile::paymentAddress)
|
||||
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(p.version())).orElse(true))
|
||||
.map(VersionedProfileV1::paymentAddress)
|
||||
.orElse(null);
|
||||
|
||||
return new VersionedProfileResponse(
|
||||
|
||||
@@ -9,7 +9,7 @@ import io.grpc.Status;
|
||||
import org.whispersystems.textsecuregcm.entities.AvatarChange;
|
||||
|
||||
public class AvatarChangeUtil {
|
||||
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileRequest.AvatarChange avatarChangeType) {
|
||||
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileV1Request.AvatarChange avatarChangeType) {
|
||||
return switch (avatarChangeType) {
|
||||
case AVATAR_CHANGE_UNCHANGED -> AvatarChange.AVATAR_CHANGE_UNCHANGED;
|
||||
case AVATAR_CHANGE_CLEAR -> AvatarChange.AVATAR_CHANGE_CLEAR;
|
||||
|
||||
@@ -18,6 +18,7 @@ public class DeviceCapabilityUtil {
|
||||
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
|
||||
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
|
||||
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
|
||||
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
|
||||
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
|
||||
throw GrpcExceptions.invalidArguments("unrecognized device capability");
|
||||
};
|
||||
@@ -29,6 +30,7 @@ public class DeviceCapabilityUtil {
|
||||
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
|
||||
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
|
||||
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
|
||||
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
|
||||
};
|
||||
}
|
||||
}
|
||||
+83
-42
@@ -5,16 +5,18 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusException;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
@@ -38,77 +40,116 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final ServerSecretParams serverSecretParams) {
|
||||
this(accountsManager,
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
new ServerZkProfileOperations(serverSecretParams),
|
||||
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final ServerZkProfileOperations zkProfileOperations,
|
||||
final GroupSendTokenUtil groupSendTokenUtil) {
|
||||
this.accountsManager = accountsManager;
|
||||
this.profilesManager = profilesManager;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.zkProfileOperations = new ServerZkProfileOperations(serverSecretParams);
|
||||
this.groupSendTokenUtil = new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC());
|
||||
this.zkProfileOperations = zkProfileOperations;
|
||||
this.groupSendTokenUtil = groupSendTokenUtil;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) throws StatusException {
|
||||
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
|
||||
|
||||
// Callers must be authenticated to request unversioned profiles by PNI
|
||||
if (targetIdentifier.identityType() == IdentityType.PNI) {
|
||||
throw Status.UNAUTHENTICATED.asException();
|
||||
throw GrpcExceptions.invalidArguments("aci service identifier type required");
|
||||
}
|
||||
|
||||
final Account account = switch (request.getAuthenticationCase()) {
|
||||
case GROUP_SEND_TOKEN -> {
|
||||
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier)) {
|
||||
throw Status.UNAUTHENTICATED.asException();
|
||||
}
|
||||
yield accountsManager.getByServiceIdentifier(targetIdentifier)
|
||||
.orElseThrow(Status.NOT_FOUND::asException);
|
||||
}
|
||||
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
final boolean authorized = switch (request.getAuthenticationCase()) {
|
||||
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
|
||||
case UNIDENTIFIED_ACCESS_KEY ->
|
||||
getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
default -> throw Status.INVALID_ARGUMENT.asException();
|
||||
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
|
||||
.orElse(false);
|
||||
default -> throw GrpcExceptions.constraintViolation("invalid authentication");
|
||||
};
|
||||
|
||||
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
|
||||
null,
|
||||
account,
|
||||
profileBadgeConverter);
|
||||
if (!authorized) {
|
||||
return GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
return targetAccount.map(account ->
|
||||
GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
null,
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build())
|
||||
.orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) throws StatusException {
|
||||
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
if (targetIdentifier.identityType() != IdentityType.ACI) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
|
||||
}
|
||||
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
|
||||
final Account targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
return ProfileGrpcHelper.getVersionedProfile(targetAccount, profilesManager, request.getRequest().getVersion());
|
||||
return targetAccount.flatMap(account ->
|
||||
ProfileGrpcHelper.getVersionedProfile(account,
|
||||
profilesManager,
|
||||
request.getRequest().getVersion().toByteArray(),
|
||||
request.getRequest().getDataEtag().toByteArray(),
|
||||
request.getRequest().getPaymentAddressEtag().toByteArray()))
|
||||
.map(result ->
|
||||
GetVersionedProfileAnonymousResponse.newBuilder()
|
||||
.setResult(result)
|
||||
.build())
|
||||
.orElseGet(() ->
|
||||
GetVersionedProfileAnonymousResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
|
||||
final GetExpiringProfileKeyCredentialAnonymousRequest request) throws StatusException {
|
||||
public GetExpiringProfileKeyCredentialAnonymousResponse getExpiringProfileKeyCredential(
|
||||
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
if (targetIdentifier.identityType() != IdentityType.ACI) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
|
||||
}
|
||||
|
||||
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
|
||||
throw GrpcExceptions.constraintViolation("invalid credential type");
|
||||
}
|
||||
|
||||
final Account account = getTargetAccountAndValidateUnidentifiedAccess(
|
||||
final Optional<Account> maybeAccount = getTargetAccountAndValidateUnidentifiedAccess(
|
||||
targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(account.getUuid(),
|
||||
request.getRequest().getVersion(), request.getRequest().getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
|
||||
|
||||
return maybeAccount.map(account ->
|
||||
ProfileGrpcHelper.getExpiringProfileKeyCredentialResult(account,
|
||||
request.getRequest().getVersion().toByteArray(), request.getRequest().getCredentialRequest().toByteArray(),
|
||||
profilesManager, zkProfileOperations)
|
||||
.map(result -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
|
||||
.setResult(result)
|
||||
.build())
|
||||
.orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build())).orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
|
||||
}
|
||||
|
||||
private Account getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) throws StatusException {
|
||||
private Optional<Account> getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) {
|
||||
|
||||
return accountsManager.getByServiceIdentifier(targetIdentifier)
|
||||
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey))
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asException);
|
||||
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
|
||||
}
|
||||
}
|
||||
+135
-48
@@ -7,21 +7,27 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import io.grpc.StatusException;
|
||||
import org.signal.chat.profile.Badge;
|
||||
import org.signal.chat.profile.BadgeSvg;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileResponse;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileV1Response;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
@@ -30,32 +36,88 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileGrpcHelper {
|
||||
static GetVersionedProfileResponse getVersionedProfile(final Account account,
|
||||
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
|
||||
final ProfilesManager profilesManager,
|
||||
final String requestVersion) throws StatusException {
|
||||
final byte[] requestVersion,
|
||||
final byte[] requestDataEtag,
|
||||
final byte[] requestPaymentAddressEtag) {
|
||||
|
||||
final VersionedProfile profile = profilesManager.get(account.getUuid(), requestVersion)
|
||||
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
|
||||
|
||||
final GetVersionedProfileResponse.Builder responseBuilder = GetVersionedProfileResponse.newBuilder();
|
||||
|
||||
responseBuilder
|
||||
.setName(ByteString.copyFrom(profile.name()))
|
||||
.setAbout(ByteString.copyFrom(profile.about()))
|
||||
.setAboutEmoji(ByteString.copyFrom(profile.aboutEmoji()))
|
||||
.setAvatar(profile.avatar())
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(profile.phoneNumberSharing()));
|
||||
|
||||
// Allow requests where either the version matches the latest version on Account or the latest version on Account
|
||||
// is empty to read the payment address.
|
||||
if (account.getCurrentProfileVersion().map(v -> v.equals(requestVersion)).orElse(true)) {
|
||||
responseBuilder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
|
||||
final Optional<VersionedProfile> profile;
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
profile = profilesManager.get(account.getUuid(), requestVersion);
|
||||
} else {
|
||||
profile = Optional.empty();
|
||||
}
|
||||
|
||||
return responseBuilder.build();
|
||||
final Optional<VersionedProfileV1> v1Profile;
|
||||
if (profile.isEmpty()) {
|
||||
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
|
||||
} else {
|
||||
v1Profile = Optional.empty();
|
||||
}
|
||||
|
||||
if (profile.isEmpty() && v1Profile.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder();
|
||||
|
||||
profile.ifPresent(p -> {
|
||||
if (requestDataEtag.length > 0 && Arrays.equals(requestDataEtag, p.dataHash())) {
|
||||
responseBuilder.setDataEtagMatched(true);
|
||||
} else {
|
||||
responseBuilder.setDataEtag(DataEtag.newBuilder()
|
||||
.setData(ByteString.copyFrom(p.data()))
|
||||
.setEtag(ByteString.copyFrom(p.dataHash()))
|
||||
.build());
|
||||
}
|
||||
});
|
||||
|
||||
v1Profile.ifPresent(p -> {
|
||||
final GetVersionedProfileV1Response.Builder v1ResponseBuilder = GetVersionedProfileV1Response.newBuilder();
|
||||
|
||||
v1ResponseBuilder
|
||||
.setName(ByteString.copyFrom(p.name()))
|
||||
.setAbout(ByteString.copyFrom(p.about()))
|
||||
.setAboutEmoji(ByteString.copyFrom(p.aboutEmoji()))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(p.phoneNumberSharing()));
|
||||
|
||||
if (p.avatar() != null) {
|
||||
v1ResponseBuilder.setAvatar(p.avatar());
|
||||
}
|
||||
|
||||
responseBuilder.setV1Response(v1ResponseBuilder);
|
||||
});
|
||||
|
||||
// Include payment address if the version matches the latest version on Account or the latest version on Account
|
||||
// is empty
|
||||
if (account.getCurrentProfileVersion().map(v -> v.equals(HexFormat.of().formatHex(requestVersion))).orElse(true)) {
|
||||
final Optional<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
|
||||
|
||||
if (paymentAddress.isPresent()) {
|
||||
|
||||
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
|
||||
profile.map(VersionedProfile::paymentAddressHash)
|
||||
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
|
||||
.orElse(false);
|
||||
|
||||
if (paymentAddressETagMatches) {
|
||||
responseBuilder.setPaymentAddressEtagMatched(true);
|
||||
} else {
|
||||
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
|
||||
.setData(ByteString.copyFrom(paymentAddress.get()))
|
||||
.setEtag(ByteString.copyFrom(
|
||||
profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get()))))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.of(responseBuilder.build());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -95,54 +157,79 @@ public class ProfileGrpcHelper {
|
||||
return grpcBadgeSvgs;
|
||||
}
|
||||
|
||||
static GetUnversionedProfileResponse buildUnversionedProfileResponse(
|
||||
static GetUnversionedProfileResult buildUnversionedProfileResult(
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final UUID requesterUuid,
|
||||
final Account targetAccount,
|
||||
final ProfileBadgeConverter profileBadgeConverter) {
|
||||
final GetUnversionedProfileResponse.Builder responseBuilder = GetUnversionedProfileResponse.newBuilder()
|
||||
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
|
||||
.addAllCapabilities(buildAccountCapabilities(targetAccount));
|
||||
|
||||
switch (targetIdentifier.identityType()) {
|
||||
case ACI -> {
|
||||
responseBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(buildBadges(profileBadgeConverter.convert(
|
||||
RequestAttributesUtil.getAvailableAcceptedLocales(),
|
||||
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(
|
||||
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
|
||||
targetAccount.getBadges(),
|
||||
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
|
||||
|
||||
targetAccount.getUnidentifiedAccessKey()
|
||||
.map(UnidentifiedAccessChecksum::generateFor)
|
||||
.map(ByteString::copyFrom)
|
||||
.ifPresent(responseBuilder::setUnidentifiedAccess);
|
||||
.ifPresent(resultBuilder::setUnidentifiedAccess);
|
||||
}
|
||||
case PNI -> responseBuilder.setUnrestrictedUnidentifiedAccess(false);
|
||||
case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false);
|
||||
}
|
||||
|
||||
return responseBuilder.build();
|
||||
return resultBuilder.build();
|
||||
}
|
||||
|
||||
static GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredentialResponse(
|
||||
final UUID targetUuid,
|
||||
final String version,
|
||||
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
|
||||
final Account account,
|
||||
final byte[] version,
|
||||
final byte[] encodedCredentialRequest,
|
||||
final ProfilesManager profilesManager,
|
||||
final ServerZkProfileOperations zkProfileOperations) throws StatusException {
|
||||
final ServerZkProfileOperations zkProfileOperations) {
|
||||
|
||||
final VersionedProfile profile = profilesManager.get(targetUuid, version)
|
||||
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(encodedCredentialRequest,
|
||||
profile, new ServiceId.Aci(targetUuid), zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw Status.INVALID_ARGUMENT.withCause(e).asException();
|
||||
final Optional<VersionedProfile> versionedProfile;
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
versionedProfile = profilesManager.get(account.getUuid(), version);
|
||||
} else {
|
||||
versionedProfile = Optional.empty();
|
||||
}
|
||||
|
||||
return GetExpiringProfileKeyCredentialResponse.newBuilder()
|
||||
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
|
||||
.build();
|
||||
return versionedProfile.map(VersionedProfile::commitment)
|
||||
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version)).map(VersionedProfileV1::commitment))
|
||||
.map(commitment -> {
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw GrpcExceptions.constraintViolation("invalid credential request");
|
||||
}
|
||||
|
||||
return GetExpiringProfileKeyCredentialResult.newBuilder()
|
||||
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
|
||||
.build();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the SHA-256 hash of the given data.
|
||||
* <p>
|
||||
* Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[])
|
||||
*/
|
||||
@VisibleForTesting
|
||||
public static byte[] hash(final byte[] data) {
|
||||
final MessageDigest sha256;
|
||||
try {
|
||||
sha256 = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
return sha256.digest(data);
|
||||
}
|
||||
}
|
||||
+134
-106
@@ -6,29 +6,29 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.time.Clock;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import io.grpc.StatusException;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileResponse;
|
||||
import org.signal.chat.profile.PaymentsForbiddenInRegion;
|
||||
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
|
||||
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
|
||||
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.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
@@ -44,9 +44,12 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
@@ -61,7 +64,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
private final PolicySigner policySigner;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final ServerZkProfileOperations zkProfileOperations;
|
||||
|
||||
private record AvatarData(Optional<String> currentAvatar,
|
||||
Optional<String> finalAvatar,
|
||||
@@ -76,8 +78,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final PolicySigner policySigner,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final RateLimiters rateLimiters,
|
||||
final ServerZkProfileOperations zkProfileOperations) {
|
||||
final RateLimiters rateLimiters) {
|
||||
this.clock = clock;
|
||||
this.accountsManager = accountsManager;
|
||||
this.profilesManager = profilesManager;
|
||||
@@ -88,33 +89,52 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
this.policySigner = policySigner;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.zkProfileOperations = zkProfileOperations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetProfileResponse setProfile(final SetProfileRequest request) throws StatusException {
|
||||
validateRequest(request);
|
||||
public SetProfileResponse setProfile(final SetProfileRequest request) {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(
|
||||
authenticatedDevice.accountIdentifier()).orElseThrow(Status.UNAUTHENTICATED::asException);
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(
|
||||
authenticatedDevice.accountIdentifier(), request.getVersion());
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found"));
|
||||
|
||||
if (!request.getPaymentAddress().isEmpty()) {
|
||||
final boolean hasDisallowedPrefix =
|
||||
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
|
||||
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
|
||||
if (hasDisallowedPrefix && maybeProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
|
||||
throw Status.PERMISSION_DENIED.asException();
|
||||
}
|
||||
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
.setProfilesV2CapabilityRequired(ProfilesV2CapabilityRequired.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final Optional<String> currentAvatar = maybeProfile.map(VersionedProfile::avatar)
|
||||
validateRequest(request);
|
||||
|
||||
final String expectedCurrentVersionHex = HexFormat.of().formatHex(request.getExpectedCurrentVersion().toByteArray());
|
||||
|
||||
final boolean currentVersionMatchesExpected = account.getCurrentProfileVersion().isEmpty()
|
||||
? request.getExpectedCurrentVersion().isEmpty()
|
||||
: account.getCurrentProfileVersion().get().equals(expectedCurrentVersionHex);
|
||||
|
||||
if (!currentVersionMatchesExpected) {
|
||||
return SetProfileResponse.newBuilder().setWriteConflict(FailedPrecondition.newBuilder()
|
||||
.setDescription("current and expected profile versions must match")
|
||||
.build()).build();
|
||||
}
|
||||
|
||||
final byte[] version = request.getVersion().toByteArray();
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(authenticatedDevice.accountIdentifier(),
|
||||
version);
|
||||
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(
|
||||
authenticatedDevice.accountIdentifier(), HexFormat.of().formatHex(version));
|
||||
|
||||
if (!request.getPaymentAddress().isEmpty() && ProfileHelper.isPaymentAddressUpdateForbidden(account, maybeProfile, maybeV1Profile, dynamicConfigurationManager)) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
.setPaymentsForbiddenInRegion(PaymentsForbiddenInRegion.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final Optional<String> currentAvatar = maybeV1Profile.map(VersionedProfileV1::avatar)
|
||||
.filter(avatar -> avatar.startsWith("profiles/"));
|
||||
|
||||
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
|
||||
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getV1Request().getAvatarChange())) {
|
||||
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
|
||||
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
|
||||
case AVATAR_CHANGE_UPDATE -> {
|
||||
@@ -124,120 +144,128 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
}
|
||||
};
|
||||
|
||||
profilesManager.set(account.getIdentifier(IdentityType.ACI),
|
||||
new VersionedProfile(
|
||||
request.getVersion(),
|
||||
request.getName().toByteArray(),
|
||||
avatarData.finalAvatar().orElse(null),
|
||||
request.getAboutEmoji().toByteArray(),
|
||||
request.getAbout().toByteArray(),
|
||||
request.getPaymentAddress().toByteArray(),
|
||||
request.getPhoneNumberSharing().toByteArray(),
|
||||
request.getCommitment().toByteArray()));
|
||||
final byte[] commitment = !request.getCommitment().isEmpty()
|
||||
? request.getCommitment().toByteArray()
|
||||
: maybeProfile.orElseThrow(IllegalStateException::new).commitment();
|
||||
|
||||
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
|
||||
final VersionedProfileV1 v1Profile = new VersionedProfileV1(
|
||||
HexFormat.of().formatHex(version),
|
||||
request.getV1Request().getName().toByteArray(),
|
||||
avatarData.finalAvatar().orElse(null),
|
||||
request.getV1Request().getAboutEmoji().toByteArray(),
|
||||
request.getV1Request().getAbout().toByteArray(),
|
||||
request.getPaymentAddress().toByteArray(),
|
||||
request.getV1Request().getPhoneNumberSharing().toByteArray(),
|
||||
commitment);
|
||||
|
||||
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
|
||||
a.getBadges()))
|
||||
.orElseGet(a::getBadges);
|
||||
final VersionedProfile profile = new VersionedProfile(version,
|
||||
request.getData().toByteArray(),
|
||||
request.getPaymentAddress().isEmpty() ? null : request.getPaymentAddress().toByteArray(),
|
||||
commitment
|
||||
);
|
||||
|
||||
a.setBadges(clock, updatedBadges);
|
||||
a.setCurrentProfileVersion(request.getVersion());
|
||||
});
|
||||
try {
|
||||
profilesManager.set(account.getIdentifier(IdentityType.ACI), v1Profile, profile,
|
||||
request.getExpectedCurrentDataHash().isEmpty() ? null : request.getExpectedCurrentDataHash().toByteArray());
|
||||
|
||||
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
|
||||
} catch (WriteConflictException _) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
.setWriteConflict(FailedPrecondition.newBuilder()
|
||||
.setDescription("current and expected data hash mismatch")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
try {
|
||||
accountsManager.updateCurrentProfileVersion(account.getIdentifier(IdentityType.ACI), version, expectedCurrentVersionHex, a -> {
|
||||
|
||||
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
|
||||
a.getBadges()))
|
||||
.orElseGet(a::getBadges);
|
||||
|
||||
a.setBadges(clock, updatedBadges);
|
||||
});
|
||||
|
||||
} catch (final WriteConflictException _) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
.setWriteConflict(FailedPrecondition.newBuilder()
|
||||
.setDescription("current and expected version mismatch")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
if (request.getV1Request().getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
|
||||
profilesManager.deleteAvatar(avatarData.currentAvatar().get());
|
||||
}
|
||||
|
||||
return avatarData.uploadAttributes()
|
||||
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
|
||||
.orElse(SetProfileResponse.newBuilder().build());
|
||||
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder()
|
||||
.setResult(SetProfileResult.newBuilder()
|
||||
.setV1AvatarUploadForm(avatarUploadAttributes).build())
|
||||
.build())
|
||||
.orElse(SetProfileResponse.newBuilder()
|
||||
.setResult(SetProfileResult.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws StatusException, RateLimitExceededException {
|
||||
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
|
||||
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
|
||||
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
targetAccount,
|
||||
profileBadgeConverter);
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws StatusException, RateLimitExceededException {
|
||||
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
|
||||
|
||||
if (targetIdentifier.identityType() != IdentityType.ACI) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
|
||||
}
|
||||
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
final Account account = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
return ProfileGrpcHelper.getVersionedProfile(account, profilesManager, request.getVersion());
|
||||
return maybeAccount.map(account ->
|
||||
ProfileGrpcHelper.getVersionedProfile(account, profilesManager,
|
||||
request.getVersion().toByteArray(),
|
||||
request.getDataEtag().toByteArray(),
|
||||
request.getPaymentAddressEtag().toByteArray())
|
||||
.map(result ->
|
||||
GetVersionedProfileResponse.newBuilder()
|
||||
.setResult(result)
|
||||
.build())
|
||||
.orElseGet(() -> GetVersionedProfileResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build())).orElseGet(() -> GetVersionedProfileResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
|
||||
final GetExpiringProfileKeyCredentialRequest request) throws StatusException, RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
|
||||
|
||||
if (targetIdentifier.identityType() != IdentityType.ACI) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
|
||||
}
|
||||
|
||||
if (request.getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
|
||||
}
|
||||
|
||||
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(targetAccount.getUuid(),
|
||||
request.getVersion(), request.getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
|
||||
}
|
||||
|
||||
|
||||
private Account validateRateLimitAndGetAccount(final UUID requesterUuid,
|
||||
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException, StatusException {
|
||||
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
|
||||
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException {
|
||||
rateLimiters.getProfileLimiter().validate(requesterUuid);
|
||||
|
||||
return accountsManager.getByServiceIdentifier(targetIdentifier).orElseThrow(Status.NOT_FOUND::asException);
|
||||
return accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
}
|
||||
|
||||
private void validateRequest(final SetProfileRequest request) throws StatusException {
|
||||
if (request.getVersion().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asException();
|
||||
private void validateRequest(final SetProfileRequest request) {
|
||||
if (request.getExpectedCurrentDataHash().isEmpty() && request.getCommitment().isEmpty()) {
|
||||
throw GrpcExceptions.constraintViolation("At least one of expected current data hash and commitment is required");
|
||||
}
|
||||
|
||||
// v1 -> v2 migration
|
||||
if (request.getCommitment().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asException();
|
||||
throw GrpcExceptions.constraintViolation("Request must include commitment during migration");
|
||||
}
|
||||
|
||||
checkByteStringLength(request.getName(), "Invalid name length", List.of(81, 285));
|
||||
checkByteStringLength(request.getAboutEmoji(), "Invalid about emoji length", List.of(0, 60));
|
||||
checkByteStringLength(request.getAbout(), "Invalid about length", List.of(0, 156, 282, 540));
|
||||
checkByteStringLength(request.getPaymentAddress(), "Invalid mobile coin address length", List.of(0, 582));
|
||||
}
|
||||
|
||||
private static void checkByteStringLength(final ByteString byteString, final String errorMessage,
|
||||
final List<Integer> allowedLengths) throws StatusException {
|
||||
|
||||
final int byteStringLength = byteString.toByteArray().length;
|
||||
|
||||
for (int allowedLength : allowedLengths) {
|
||||
if (byteStringLength == allowedLength) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asException();
|
||||
}
|
||||
|
||||
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
|
||||
|
||||
+3
-4
@@ -26,6 +26,7 @@ import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.NonEmptyFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.PresentFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.RangeFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ServiceIdentifierIdentityTypeValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
|
||||
|
||||
public class ValidatingInterceptor implements ServerInterceptor {
|
||||
@@ -39,7 +40,8 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
"org.signal.chat.require.exactlySize", new ExactlySizeFieldValidator(),
|
||||
"org.signal.chat.require.range", new RangeFieldValidator(),
|
||||
"org.signal.chat.require.size", new SizeFieldValidator(),
|
||||
"org.signal.chat.require.base64url", new Base64UrlFieldValidator()
|
||||
"org.signal.chat.require.base64url", new Base64UrlFieldValidator(),
|
||||
"org.signal.chat.require.identityType", new ServiceIdentifierIdentityTypeValidator()
|
||||
);
|
||||
|
||||
@Override
|
||||
@@ -64,9 +66,6 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
try {
|
||||
validateMessage(message);
|
||||
super.onMessage(message);
|
||||
} catch (final StatusRuntimeException e) {
|
||||
call.close(e.getStatus(), e.getTrailers());
|
||||
forwardCalls = false;
|
||||
} catch (RuntimeException runtimeException) {
|
||||
final StatusRuntimeException grpcException = switch (runtimeException) {
|
||||
case StatusRuntimeException e -> e;
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.Message;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
|
||||
public class ServiceIdentifierIdentityTypeValidator extends BaseFieldValidator<IdentityType> {
|
||||
|
||||
public ServiceIdentifierIdentityTypeValidator() {
|
||||
super("identityType", Set.of(Descriptors.FieldDescriptor.Type.MESSAGE), MissingOptionalAction.SUCCEED, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IdentityType resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
|
||||
|
||||
if (extensionValue instanceof Descriptors.EnumValueDescriptor d) {
|
||||
if (d.getType().equals(org.signal.chat.require.IdentityType.getDescriptor())) {
|
||||
return switch (Objects.requireNonNull(org.signal.chat.require.IdentityType.forNumber(d.getNumber()))) {
|
||||
case IDENTITY_TYPE_ACI -> IdentityType.IDENTITY_TYPE_ACI;
|
||||
case IDENTITY_TYPE_PNI -> IdentityType.IDENTITY_TYPE_PNI;
|
||||
default -> throw new IllegalArgumentException("unsupported value: " + d.getName());
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("value must be org.signal.chat.require.IdentityType");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validateMessageValue(final IdentityType extensionValue, final Message msg) throws FieldValidationException {
|
||||
if (msg == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg instanceof ServiceIdentifier i) {
|
||||
if (i.getIdentityType() == extensionValue) {
|
||||
return;
|
||||
}
|
||||
throw new FieldValidationException("identity type must be " + extensionValue.getValueDescriptor().getName());
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("field must be " + ServiceIdentifier.class.getName());
|
||||
}
|
||||
}
|
||||
@@ -37,8 +37,10 @@ import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
@@ -957,6 +959,42 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
});
|
||||
}
|
||||
|
||||
/// Using a pessimistic lock, updates the current profile version to `newVersion` if `currentProfileVersion` matches
|
||||
/// `expectedCurrentVersion`. The caller may provide a supplementary `Consumer<Account>` for additional updates
|
||||
///
|
||||
/// @throws WriteConflictException if the expected current version does not match the current version
|
||||
public Account updateCurrentProfileVersion(final UUID accountIdentifier, final byte[] newVersion,
|
||||
final String expectedCurrentVersion, final Consumer<Account> updater) throws WriteConflictException {
|
||||
|
||||
Objects.requireNonNull(expectedCurrentVersion, "expectedCurrentVersion");
|
||||
|
||||
// Always fetch a fresh, non-cached copy of the account before making modifications
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
final String newVersionHex = HexFormat.of().formatHex(newVersion);
|
||||
|
||||
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
|
||||
final Account maybeUpdatedAccount = update(accountIdentifier, a -> {
|
||||
if (!a.getCurrentProfileVersion().orElse("").equals(expectedCurrentVersion)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
a.setCurrentProfileVersion(newVersionHex);
|
||||
|
||||
updater.accept(a);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> v.equals(newVersionHex)).orElse(false)) {
|
||||
throw new WriteConflictException();
|
||||
}
|
||||
|
||||
return maybeUpdatedAccount;
|
||||
}, accountLockExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Specialized version of {@link #updateDevice(UUID, byte, Consumer)} that minimizes potentially contentious and
|
||||
* redundant updates of {@code device.lastSeen}
|
||||
|
||||
+2
-1
@@ -15,7 +15,8 @@ public enum DeviceCapability {
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true);
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
|
||||
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false);
|
||||
|
||||
public enum AccountCapabilityMode {
|
||||
/**
|
||||
|
||||
@@ -19,9 +19,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
@@ -31,6 +29,8 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
public class Profiles {
|
||||
@@ -93,7 +93,7 @@ public class Profiles {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public void set(final UUID uuid, final VersionedProfile profile) {
|
||||
public void set(final UUID uuid, final VersionedProfileV1 profile) {
|
||||
SET_PROFILES_TIMER.record(() -> {
|
||||
dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
@@ -105,16 +105,17 @@ public class Profiles {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> setAsync(final UUID uuid, final VersionedProfile profile) {
|
||||
return AsyncTimerUtil.record(SET_PROFILES_TIMER, () -> dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
|
||||
/// Used to update a profile during the v2 migration.
|
||||
public TransactWriteItem getTransactWriteItem(final UUID uuid, final VersionedProfileV1 profile) {
|
||||
return TransactWriteItem.builder()
|
||||
.update(Update.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(uuid, profile.version()))
|
||||
.updateExpression(buildUpdateExpression(profile))
|
||||
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
|
||||
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
|
||||
.build()
|
||||
).thenRun(Util.NOOP)
|
||||
).toCompletableFuture();
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final String version) {
|
||||
@@ -124,7 +125,7 @@ public class Profiles {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String buildUpdateExpression(final VersionedProfile profile) {
|
||||
static String buildUpdateExpression(final VersionedProfileV1 profile) {
|
||||
final List<String> updatedAttributes = new ArrayList<>(5);
|
||||
final List<String> deletedAttributes = new ArrayList<>(5);
|
||||
|
||||
@@ -186,7 +187,7 @@ public class Profiles {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfile profile) {
|
||||
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile) {
|
||||
final Map<String, AttributeValue> expressionValues = new HashMap<>();
|
||||
|
||||
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.commitment()));
|
||||
@@ -217,7 +218,7 @@ public class Profiles {
|
||||
return expressionValues;
|
||||
}
|
||||
|
||||
public Optional<VersionedProfile> get(final UUID uuid, final String version) {
|
||||
public Optional<VersionedProfileV1> get(final UUID uuid, final String version) {
|
||||
return GET_PROFILE_TIMER.record(() -> {
|
||||
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
@@ -229,19 +230,8 @@ public class Profiles {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<VersionedProfile>> getAsync(final UUID uuid, final String version) {
|
||||
return AsyncTimerUtil.record(GET_PROFILE_TIMER, () -> dynamoDbAsyncClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(uuid, version))
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.thenApply(response ->
|
||||
response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.<VersionedProfile>empty())
|
||||
).toCompletableFuture();
|
||||
}
|
||||
|
||||
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
|
||||
return new VersionedProfile(
|
||||
private static VersionedProfileV1 fromItem(final Map<String, AttributeValue> item) {
|
||||
return new VersionedProfileV1(
|
||||
AttributeValues.getString(item, ATTR_VERSION, null),
|
||||
getBytes(item, ATTR_NAME),
|
||||
AttributeValues.getString(item, ATTR_AVATAR, null),
|
||||
|
||||
+137
-65
@@ -11,8 +11,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -21,12 +23,13 @@ import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
|
||||
@@ -35,39 +38,89 @@ public class ProfilesManager {
|
||||
private final Logger logger = LoggerFactory.getLogger(ProfilesManager.class);
|
||||
|
||||
private static final String CACHE_PREFIX_V1 = "profiles_v1::";
|
||||
private static final String CACHE_PREFIX_V2 = "profiles_v2::";
|
||||
|
||||
private final Profiles profiles;
|
||||
private static final byte[] EMPTY = new byte[0];
|
||||
|
||||
private final Profiles profilesV1;
|
||||
private final ProfilesV2 profilesV2;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final S3AsyncClient s3Client;
|
||||
private final String bucket;
|
||||
private final ClusterLuaScript setLuaScript;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
private static final String RETRY_NAME = ResilienceUtil.name(ProfilesManager.class);
|
||||
|
||||
private static final String DELETE_AVATAR_COUNTER_NAME = name(ProfilesManager.class, "deleteAvatar");
|
||||
|
||||
public ProfilesManager(final Profiles profiles,
|
||||
public ProfilesManager(final Profiles profilesV1,
|
||||
final ProfilesV2 profilesV2,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final S3AsyncClient s3Client,
|
||||
final String bucket) {
|
||||
this.profiles = profiles;
|
||||
final String bucket) throws IOException {
|
||||
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
|
||||
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ProfilesManager(final Profiles profilesV1,
|
||||
final ProfilesV2 profilesV2,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final S3AsyncClient s3Client,
|
||||
final String bucket,
|
||||
final ClusterLuaScript setLuaScript) {
|
||||
this.profilesV1 = profilesV1;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.retryExecutor = retryExecutor;
|
||||
this.s3Client = s3Client;
|
||||
this.bucket = bucket;
|
||||
this.setLuaScript = setLuaScript;
|
||||
this.mapper = SystemMapper.jsonMapper();
|
||||
}
|
||||
|
||||
public void set(UUID uuid, VersionedProfile versionedProfile) {
|
||||
redisSet(uuid, versionedProfile);
|
||||
profiles.set(uuid, versionedProfile);
|
||||
public void setV1(UUID uuid, VersionedProfileV1 versionedProfile) {
|
||||
redisDelete(uuid);
|
||||
|
||||
profilesV1.set(uuid, versionedProfile);
|
||||
|
||||
redisSet(uuid, null, versionedProfile);
|
||||
|
||||
try {
|
||||
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
|
||||
// downgrades to v1, all v2 profiles are stale
|
||||
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
|
||||
|
||||
profilesV2.deleteAll(uuid);
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> setAsync(UUID uuid, VersionedProfile versionedProfile) {
|
||||
return profiles.setAsync(uuid, versionedProfile)
|
||||
.thenCompose(ignored -> redisSetAsync(uuid, versionedProfile));
|
||||
/// Transactionally sets v1 and v2 Profile data in DynamoDB.
|
||||
///
|
||||
/// Note: writes to the Redis cache are not transactional, and a failed DynamoDB write may leave incorrect data in Redis
|
||||
public void set(UUID uuid, VersionedProfileV1 versionedProfileV1, VersionedProfile versionedProfile, @Nullable byte[] expectedCurrentDataHash) throws WriteConflictException {
|
||||
|
||||
final TransactWriteItem v1TransactWriteItem = profilesV1.getTransactWriteItem(uuid, versionedProfileV1);
|
||||
|
||||
redisDelete(uuid);
|
||||
|
||||
profilesV2.set(uuid,
|
||||
versionedProfile.version(),
|
||||
versionedProfile.data(),
|
||||
versionedProfile.dataHash(),
|
||||
versionedProfile.commitment(),
|
||||
versionedProfile.paymentAddress(),
|
||||
versionedProfile.paymentAddressHash(),
|
||||
expectedCurrentDataHash,
|
||||
v1TransactWriteItem);
|
||||
|
||||
redisSet(uuid, versionedProfile, versionedProfileV1);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,7 +131,7 @@ public class ProfilesManager {
|
||||
*/
|
||||
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
|
||||
|
||||
final CompletableFuture<Void> profilesAndAvatars = Mono.fromFuture(profiles.deleteAll(uuid))
|
||||
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(avatar ->
|
||||
Mono.fromFuture(includeAvatar ? deleteAvatar(avatar) : CompletableFuture.completedFuture(null))
|
||||
@@ -87,7 +140,7 @@ public class ProfilesManager {
|
||||
.onErrorComplete())
|
||||
.then().toFuture();
|
||||
|
||||
return CompletableFuture.allOf(redisDelete(uuid), profilesAndAvatars);
|
||||
return CompletableFuture.allOf(redisDeleteAsync(uuid), profilesV1AndAvatars, profilesV2.deleteAll(uuid));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteAvatar(String avatar) {
|
||||
@@ -110,87 +163,99 @@ public class ProfilesManager {
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
public Optional<VersionedProfile> get(UUID uuid, String version) {
|
||||
Optional<VersionedProfile> profile = redisGet(uuid, version);
|
||||
|
||||
if (profile.isEmpty()) {
|
||||
profile = profiles.get(uuid, version);
|
||||
public Optional<VersionedProfileV1> getV1(UUID uuid, String version) {
|
||||
return redisGetV1(uuid, version).or(() -> {
|
||||
final Optional<VersionedProfileV1> profile = profilesV1.get(uuid, version);
|
||||
try {
|
||||
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile));
|
||||
profile.ifPresent(versionedProfile -> redisSet(uuid, null, versionedProfile));
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
}
|
||||
}
|
||||
|
||||
return profile;
|
||||
return profile;
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<VersionedProfile>> getAsync(UUID uuid, String version) {
|
||||
return redisGetAsync(uuid, version)
|
||||
.thenCompose(maybeVersionedProfile -> maybeVersionedProfile
|
||||
.map(versionedProfile -> CompletableFuture.completedFuture(maybeVersionedProfile))
|
||||
.orElseGet(() -> profiles.getAsync(uuid, version)
|
||||
.thenCompose(maybeVersionedProfileFromDynamo -> maybeVersionedProfileFromDynamo
|
||||
.map(profile -> redisSetAsync(uuid, profile)
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
return null;
|
||||
}))
|
||||
.thenApply(ignored -> maybeVersionedProfileFromDynamo))
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(maybeVersionedProfileFromDynamo)))));
|
||||
public Optional<VersionedProfile> get(UUID uuid, byte[] version) {
|
||||
return redisGet(uuid, version).or(() -> {
|
||||
final Optional<VersionedProfile> profile = profilesV2.get(uuid, version);
|
||||
try {
|
||||
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile, null));
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
}
|
||||
|
||||
return profile;
|
||||
});
|
||||
}
|
||||
|
||||
private void redisSet(UUID uuid, VersionedProfile profile) {
|
||||
@VisibleForTesting
|
||||
void redisSet(UUID uuid, @Nullable VersionedProfile v2Profile, @Nullable VersionedProfileV1 v1Profile) {
|
||||
try {
|
||||
final byte[] profileJson = mapper.writeValueAsBytes(profile);
|
||||
if (v1Profile == null && v2Profile == null) {
|
||||
logger.error("Expected at least one profile");
|
||||
return;
|
||||
}
|
||||
|
||||
final byte[] v1ProfileVersion;
|
||||
final byte[] v1ProfileBytes;
|
||||
if (v1Profile != null) {
|
||||
v1ProfileVersion = v1Profile.version().getBytes();
|
||||
v1ProfileBytes = mapper.writeValueAsBytes(v1Profile);
|
||||
} else {
|
||||
v1ProfileVersion = EMPTY;
|
||||
v1ProfileBytes = EMPTY;
|
||||
}
|
||||
|
||||
final byte[] v2ProfileVersion;
|
||||
final byte[] v2ProfileBytes;
|
||||
if (v2Profile != null) {
|
||||
v2ProfileVersion = v2Profile.version();
|
||||
v2ProfileBytes = mapper.writeValueAsBytes(v2Profile);
|
||||
} else {
|
||||
v2ProfileVersion = EMPTY;
|
||||
v2ProfileBytes = EMPTY;
|
||||
}
|
||||
|
||||
setLuaScript.executeBinary(List.of(getCacheKeyV1(uuid), getCacheKeyV2(uuid)),
|
||||
List.of(v1ProfileVersion, v1ProfileBytes, v2ProfileVersion, v2ProfileBytes));
|
||||
|
||||
cacheCluster.useBinaryCluster(connection -> connection.sync().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> redisSetAsync(UUID uuid, VersionedProfile profile) {
|
||||
final byte[] profileJson;
|
||||
|
||||
private Optional<VersionedProfile> redisGet(UUID uuid, byte[] version) {
|
||||
try {
|
||||
profileJson = mapper.writeValueAsBytes(profile);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV2(uuid), version));
|
||||
|
||||
return cacheCluster.withBinaryCluster(connection ->
|
||||
connection.async().hset(getCacheKeyV1(uuid), profile.version().getBytes(), profileJson)).toCompletableFuture()
|
||||
.thenRun(Util.NOOP)
|
||||
.toCompletableFuture();
|
||||
return parseProfileJson(json, VersionedProfile.class);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Redis exception", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<VersionedProfile> redisGet(UUID uuid, String version) {
|
||||
@VisibleForTesting
|
||||
static byte[] getCacheKeyV2(UUID uuid) {
|
||||
return (CACHE_PREFIX_V2 + '{' + uuid.toString() + '}').getBytes();
|
||||
}
|
||||
|
||||
private Optional<VersionedProfileV1> redisGetV1(UUID uuid, String version) {
|
||||
try {
|
||||
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV1(uuid), version.getBytes()));
|
||||
|
||||
return parseProfileJson(json);
|
||||
return parseProfileJson(json, VersionedProfileV1.class);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to retrieve profile from cache", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Optional<VersionedProfile>> redisGetAsync(UUID uuid, String version) {
|
||||
return cacheCluster.withBinaryCluster(connection ->
|
||||
connection.async().hget(getCacheKeyV1(uuid), version.getBytes()))
|
||||
.thenApply(this::parseProfileJson)
|
||||
.exceptionally(throwable -> {
|
||||
logger.warn("Failed to read versioned profile from Redis", throwable);
|
||||
return Optional.empty();
|
||||
})
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
private Optional<VersionedProfile> parseProfileJson(@Nullable final byte[] maybeJson) {
|
||||
private <T> Optional<T> parseProfileJson(@Nullable final byte[] maybeJson, Class<T> klass) {
|
||||
try {
|
||||
if (maybeJson != null) {
|
||||
return Optional.of(mapper.readValue(maybeJson, VersionedProfile.class));
|
||||
return Optional.of(mapper.readValue(maybeJson, klass));
|
||||
}
|
||||
return Optional.empty();
|
||||
} catch (final IOException e) {
|
||||
@@ -199,10 +264,17 @@ public class ProfilesManager {
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> redisDelete(UUID uuid) {
|
||||
private void redisDelete(UUID uuid) {
|
||||
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeRunnable(() -> cacheCluster.withBinaryCluster(
|
||||
connection -> connection.sync().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> redisDeleteAsync(UUID uuid) {
|
||||
|
||||
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeCompletionStage(retryExecutor, () -> cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid))))
|
||||
.executeCompletionStage(retryExecutor,
|
||||
() -> cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))))
|
||||
.toCompletableFuture()
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
|
||||
public class ProfilesV2 {
|
||||
|
||||
private static final String CONDITIONAL_CHECK_FAILED_CODE = "ConditionalCheckFailed";
|
||||
private static final String TRANSACTION_CONFLICT_CODE = "TransactionConflict";
|
||||
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
|
||||
// UUID of the account that owns this profile; hash key; byte array
|
||||
@VisibleForTesting
|
||||
static final String KEY_ACCOUNT_UUID = "U";
|
||||
|
||||
// Version of this profile; sort key; byte array
|
||||
@VisibleForTesting
|
||||
static final String KEY_VERSION = "V";
|
||||
|
||||
// Profile data (serialized ciphertext); byte array
|
||||
private static final String ATTR_DATA = "D";
|
||||
|
||||
// SHA-256 hash of data attribute; byte array
|
||||
private static final String ATTR_DATA_HASH = "DH";
|
||||
|
||||
// Commitment; byte array
|
||||
private static final String ATTR_COMMITMENT = "C";
|
||||
|
||||
// Payment address; byte array
|
||||
private static final String ATTR_PAYMENT_ADDRESS = "P";
|
||||
|
||||
// SHA-256 hash of payment address attribute; byte array
|
||||
private static final String ATTR_PAYMENT_ADDRESS_HASH = "PH";
|
||||
|
||||
private static final Map<String, String> UPDATE_EXPRESSION_ATTRIBUTE_NAMES = Map.of(
|
||||
"#data", ATTR_DATA,
|
||||
"#dataHash", ATTR_DATA_HASH,
|
||||
"#commitment", ATTR_COMMITMENT,
|
||||
"#paymentAddress", ATTR_PAYMENT_ADDRESS,
|
||||
"#paymentAddressHash", ATTR_PAYMENT_ADDRESS_HASH);
|
||||
|
||||
private static final Timer SET_PROFILES_TIMER = Metrics.timer(name(ProfilesV2.class, "set"));
|
||||
private static final Timer GET_PROFILE_TIMER = Metrics.timer(name(ProfilesV2.class, "get"));
|
||||
private static final String DELETE_PROFILES_TIMER_NAME = name(ProfilesV2.class, "delete");
|
||||
private static final String WRITE_CONFLICTS_COUNTER_NAME = name(ProfilesV2.class, "writeConflicts");
|
||||
|
||||
private static final int COMMITMENT_LENGTH = 97;
|
||||
|
||||
private static final int DELETE_MAX_CONCURRENCY = 32;
|
||||
|
||||
public ProfilesV2(final DynamoDbClient dynamoDbClient,
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
final String tableName) {
|
||||
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
/// Put a profile version with the given data
|
||||
///
|
||||
/// During the migration from v1 → v2, both updates are executed transactionally
|
||||
///
|
||||
/// @param uuid the account UUID
|
||||
/// @param version the profile version
|
||||
/// @param data serialized profile ciphertext
|
||||
/// @param commitment serialized profile key commitment (required for initial write, optional for updates)
|
||||
/// @param paymentAddress serialized payment address ciphertext (nullable)
|
||||
/// @param expectedCurrentDataHash the expected current data hash, used for conditional update (nullable for the initial write)
|
||||
/// @param profileV1TransactWriteItem transact write item for v1 profile during migration
|
||||
/// @throws WriteConflictException if the expected data hash does not match the stored data hash
|
||||
/// @throws IllegalArgumentException if commitment is null on initial write or commitment does not match on an update
|
||||
/// @throws IllegalStateException if commitment is missing after a write
|
||||
public void set(final UUID uuid,
|
||||
final byte[] version,
|
||||
final byte[] data,
|
||||
final byte[] dataHash,
|
||||
@Nullable final byte[] commitment,
|
||||
@Nullable final byte[] paymentAddress,
|
||||
@Nullable final byte[] paymentAddressHash,
|
||||
@Nullable final byte[] expectedCurrentDataHash,
|
||||
final TransactWriteItem profileV1TransactWriteItem) throws WriteConflictException {
|
||||
|
||||
// Commitment is required for initial write (when expectedCurrentDataHash is null)
|
||||
if (expectedCurrentDataHash == null && commitment == null) {
|
||||
throw new IllegalArgumentException("Commitment is required for initial write");
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
final List<TransactWriteItem> transactWriteItems = List.of(
|
||||
getTransactWriteItem(uuid, version, data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash),
|
||||
profileV1TransactWriteItem);
|
||||
|
||||
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
|
||||
.transactItems(transactWriteItems)
|
||||
.build());
|
||||
} catch (TransactionCanceledException e) {
|
||||
|
||||
if (e.hasCancellationReasons()) {
|
||||
|
||||
// check for fields with conditional check failures
|
||||
if (e.cancellationReasons().getFirst() != null
|
||||
&& e.cancellationReasons().getFirst().code().equals(CONDITIONAL_CHECK_FAILED_CODE)
|
||||
&& e.cancellationReasons().getFirst().hasItem()) {
|
||||
|
||||
final Map<String, AttributeValue> item = e.cancellationReasons().getFirst().item();
|
||||
|
||||
final byte[] oldCommitment = AttributeValues.getByteArray(item, ATTR_COMMITMENT, null);
|
||||
|
||||
if (oldCommitment != null && commitment != null && !Arrays.equals(oldCommitment, commitment)) {
|
||||
throw new IllegalArgumentException("Commitment is immutable");
|
||||
}
|
||||
|
||||
if (oldCommitment == null && commitment == null) {
|
||||
throw new IllegalStateException("Commitment is absent from existing profile");
|
||||
}
|
||||
}
|
||||
|
||||
final Optional<String> cancellationCode = e.cancellationReasons().stream()
|
||||
.map(CancellationReason::code)
|
||||
.filter(code -> CONDITIONAL_CHECK_FAILED_CODE.equals(code) || TRANSACTION_CONFLICT_CODE.equals(code))
|
||||
.findFirst();
|
||||
|
||||
if (cancellationCode.isPresent()) {
|
||||
// any other conditional check failure is an expected data hash mismatch, which is a write conflict
|
||||
Metrics.counter(WRITE_CONFLICTS_COUNTER_NAME, "code", cancellationCode.get()).increment();
|
||||
throw new WriteConflictException();
|
||||
}
|
||||
}
|
||||
|
||||
throw e;
|
||||
} finally {
|
||||
sample.stop(SET_PROFILES_TIMER);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a [TransactWriteItem] for a profile update during the v2 migration
|
||||
///
|
||||
/// @param uuid the account UUID
|
||||
/// @param version the profile version
|
||||
/// @param data the serialized profile ciphertext
|
||||
/// @param dataHash the serialized profile ciphertext hash
|
||||
/// @param commitment the profile key commitment (required for initial write, optional for updates)
|
||||
/// @param paymentAddress the payment address (nullable; will clear existing value for this version if null)
|
||||
/// @param paymentAddressHash the payment address hash (nullable; will clear existing value for this version if null)
|
||||
/// @param expectedCurrentDataHash the expected current data hash for conditional update (nullable for first write)
|
||||
/// @return a [TransactWriteItem] containing the Update operation
|
||||
@VisibleForTesting
|
||||
TransactWriteItem getTransactWriteItem(final UUID uuid,
|
||||
final byte[] version,
|
||||
final byte[] data,
|
||||
final byte[] dataHash,
|
||||
@Nullable final byte[] commitment,
|
||||
@Nullable final byte[] paymentAddress,
|
||||
@Nullable final byte[] paymentAddressHash,
|
||||
@Nullable final byte[] expectedCurrentDataHash) {
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
.update(Update.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(uuid, version))
|
||||
.updateExpression(buildUpdateExpression(commitment != null, paymentAddress != null))
|
||||
.conditionExpression(buildConditionExpression(commitment != null, expectedCurrentDataHash != null))
|
||||
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
|
||||
.expressionAttributeValues(buildUpdateExpressionAttributeValues(data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash))
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final byte[] version) {
|
||||
return Map.of(
|
||||
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
|
||||
KEY_VERSION, AttributeValues.fromByteArray(version));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String buildUpdateExpression(final boolean hasCommitment, final boolean hasPaymentAddress) {
|
||||
final StringBuilder updateExpressionBuilder = new StringBuilder("SET #data = :data, #dataHash = :dataHash");
|
||||
|
||||
if (hasCommitment) {
|
||||
updateExpressionBuilder.append(", #commitment = if_not_exists(#commitment, :commitment)");
|
||||
}
|
||||
|
||||
if (hasPaymentAddress) {
|
||||
updateExpressionBuilder.append(", #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash");
|
||||
} else {
|
||||
updateExpressionBuilder.append(" REMOVE #paymentAddress, #paymentAddressHash");
|
||||
}
|
||||
|
||||
return updateExpressionBuilder.toString();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String buildConditionExpression(final boolean hasCommitment, final boolean hasExpectedCurrentDataHash) {
|
||||
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
|
||||
if (hasCommitment) {
|
||||
sb.append("(attribute_not_exists(#commitment) OR #commitment = :commitment)");
|
||||
} else {
|
||||
sb.append("size(#commitment) = :commitment_length");
|
||||
}
|
||||
|
||||
if (hasExpectedCurrentDataHash) {
|
||||
// If expected hash is provided, verify it matches the stored hash
|
||||
sb.append(" AND #dataHash = :expectedDataHash");
|
||||
} else {
|
||||
// Initial write: dataHash must not exist
|
||||
sb.append(" AND attribute_not_exists(#dataHash)");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(
|
||||
final byte[] data,
|
||||
final byte[] dataHash,
|
||||
@Nullable final byte[] commitment,
|
||||
@Nullable final byte[] paymentAddress,
|
||||
@Nullable final byte[] paymentAddressHash,
|
||||
@Nullable final byte[] expectedCurrentDataHash) {
|
||||
|
||||
final Map<String, AttributeValue> expressionValues = new HashMap<>();
|
||||
|
||||
expressionValues.put(":data", AttributeValues.fromByteArray(data));
|
||||
expressionValues.put(":dataHash", AttributeValues.fromByteArray(dataHash));
|
||||
|
||||
if (commitment != null) {
|
||||
expressionValues.put(":commitment", AttributeValues.fromByteArray(commitment));
|
||||
} else {
|
||||
expressionValues.put(":commitment_length", AttributeValues.fromInt(COMMITMENT_LENGTH));
|
||||
}
|
||||
|
||||
if (paymentAddress != null) {
|
||||
expressionValues.put(":paymentAddress", AttributeValues.fromByteArray(paymentAddress));
|
||||
expressionValues.put(":paymentAddressHash", AttributeValues.fromByteArray(paymentAddressHash));
|
||||
}
|
||||
|
||||
if (expectedCurrentDataHash != null) {
|
||||
expressionValues.put(":expectedDataHash", AttributeValues.fromByteArray(expectedCurrentDataHash));
|
||||
}
|
||||
|
||||
return expressionValues;
|
||||
}
|
||||
|
||||
/// Fetch a profile version
|
||||
///
|
||||
/// @param uuid the account UUID
|
||||
/// @param version the profile version
|
||||
/// @return the VersionedProfile, if found
|
||||
public Optional<VersionedProfile> get(final UUID uuid, final byte[] version) {
|
||||
return GET_PROFILE_TIMER.record(() -> {
|
||||
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(uuid, version))
|
||||
.consistentRead(true)
|
||||
.build());
|
||||
|
||||
return response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
|
||||
return new VersionedProfile(
|
||||
Objects.requireNonNull(AttributeValues.getByteArray(item, KEY_VERSION, null)),
|
||||
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA, null)),
|
||||
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA_HASH, null)),
|
||||
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS, null),
|
||||
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS_HASH, null),
|
||||
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_COMMITMENT, null)));
|
||||
}
|
||||
|
||||
/// Deletes all profile versions for the given UUID.
|
||||
///
|
||||
/// @param uuid the account UUID
|
||||
/// @return a CompletableFuture that completes when all versions have been deleted
|
||||
public CompletableFuture<Void> deleteAll(final UUID uuid) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final AttributeValue uuidAttributeValue = AttributeValues.fromUUID(uuid);
|
||||
|
||||
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#uuid = :uuid")
|
||||
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
|
||||
.expressionAttributeValues(Map.of(":uuid", uuidAttributeValue))
|
||||
.projectionExpression(KEY_VERSION)
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_ACCOUNT_UUID, uuidAttributeValue,
|
||||
KEY_VERSION, item.get(KEY_VERSION)))
|
||||
.build())), DELETE_MAX_CONCURRENCY)
|
||||
.then()
|
||||
.doOnSuccess(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "success")))
|
||||
.doOnError(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error")))
|
||||
.toFuture();
|
||||
}
|
||||
}
|
||||
+66
-23
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -7,34 +7,77 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
|
||||
public record VersionedProfile (String version,
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] name,
|
||||
public record VersionedProfile(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] version,
|
||||
|
||||
@Nullable
|
||||
String avatar,
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] data,
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] aboutEmoji,
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] dataHash,
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] about,
|
||||
@Nullable
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] paymentAddress,
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] paymentAddress,
|
||||
@Nullable
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] paymentAddressHash,
|
||||
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] phoneNumberSharing,
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] commitment) {
|
||||
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] commitment) {}
|
||||
public VersionedProfile(byte[] version, byte[] data, @Nullable byte[] paymentAddress, byte[] commitment) {
|
||||
this(Objects.requireNonNull(version), Objects.requireNonNull(data), hash(Objects.requireNonNull(data)), paymentAddress, paymentAddress == null ? null : hash(paymentAddress), Objects.requireNonNull(commitment));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (!(o instanceof final VersionedProfile that))
|
||||
return false;
|
||||
|
||||
return Arrays.equals(data, that.data) && Arrays.equals(version, that.version) && Arrays.equals(dataHash,
|
||||
that.dataHash) && Arrays.equals(commitment, that.commitment) && Arrays.equals(paymentAddress,
|
||||
that.paymentAddress) && Arrays.equals(paymentAddressHash, that.paymentAddressHash);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(
|
||||
Arrays.hashCode(version),
|
||||
Arrays.hashCode(data),
|
||||
Arrays.hashCode(dataHash),
|
||||
Arrays.hashCode(paymentAddress),
|
||||
Arrays.hashCode(paymentAddressHash),
|
||||
Arrays.hashCode(commitment));
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the SHA-256 hash of the given data.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static byte[] hash(final byte[] data) {
|
||||
final MessageDigest sha256;
|
||||
try {
|
||||
sha256 = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
return sha256.digest(data);
|
||||
}
|
||||
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
public record VersionedProfileV1(String version,
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] name,
|
||||
|
||||
@Nullable
|
||||
String avatar,
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] aboutEmoji,
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] about,
|
||||
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] paymentAddress,
|
||||
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] phoneNumberSharing,
|
||||
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] commitment) {
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (!(o instanceof final VersionedProfileV1 that))
|
||||
return false;
|
||||
|
||||
return Arrays.equals(name, that.name) && Arrays.equals(about, that.about) && Objects.equals(avatar, that.avatar)
|
||||
&& Objects.equals(version, that.version) && Arrays.equals(aboutEmoji, that.aboutEmoji) && Arrays.equals(
|
||||
commitment, that.commitment) && Arrays.equals(paymentAddress, that.paymentAddress) && Arrays.equals(
|
||||
phoneNumberSharing, that.phoneNumberSharing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(
|
||||
version,
|
||||
Arrays.hashCode(name),
|
||||
Objects.hashCode(avatar),
|
||||
Arrays.hashCode(aboutEmoji),
|
||||
Arrays.hashCode(about),
|
||||
Arrays.hashCode(paymentAddress),
|
||||
Arrays.hashCode(phoneNumberSharing),
|
||||
Arrays.hashCode(commitment));
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class WriteConflictException extends NoStackTraceException {
|
||||
}
|
||||
@@ -1,18 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import javax.annotation.Nullable;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -23,7 +11,25 @@ import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
|
||||
public class ProfileHelper {
|
||||
public static int MAX_PROFILE_AVATAR_SIZE_BYTES = 10 * 1024 * 1024;
|
||||
@@ -86,15 +92,43 @@ public class ProfileHelper {
|
||||
}
|
||||
|
||||
public static ExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
|
||||
final byte[] encodedCredentialRequest,
|
||||
final VersionedProfile profile,
|
||||
final ProfileKeyCredentialRequest request,
|
||||
final ProfileKeyCommitment commitment,
|
||||
final ServiceId.Aci accountIdentifier,
|
||||
final ServerZkProfileOperations zkProfileOperations) throws InvalidInputException, VerificationFailedException {
|
||||
|
||||
final Instant expiration = Instant.now().plus(EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION).truncatedTo(ChronoUnit.DAYS);
|
||||
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.commitment());
|
||||
final ProfileKeyCredentialRequest request = new ProfileKeyCredentialRequest(
|
||||
encodedCredentialRequest);
|
||||
|
||||
return zkProfileOperations.issueExpiringProfileKeyCredential(request, accountIdentifier, commitment, expiration);
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public static boolean isPaymentAddressUpdateForbidden(
|
||||
final Account account, final Optional<VersionedProfile> maybeProfile,
|
||||
final Optional<VersionedProfileV1> maybeV1Profile,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
|
||||
final Optional<byte[]> currentPaymentAddress = maybeProfile.map(VersionedProfile::paymentAddress)
|
||||
.or(() -> maybeV1Profile.map(VersionedProfileV1::paymentAddress));
|
||||
final boolean hasDisallowedPrefix = dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration()
|
||||
.getDisallowedPrefixes().stream()
|
||||
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
|
||||
|
||||
return hasDisallowedPrefix && currentPaymentAddress.isEmpty();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public static String getAvatar(final CreateProfileRequest.AvatarChange avatarChange, final Optional<String> currentAvatar) {
|
||||
return switch (avatarChange) {
|
||||
case UNCHANGED -> currentAvatar.orElse(null);
|
||||
case CLEAR -> null;
|
||||
case UPDATE -> ProfileHelper.generateAvatarObjectName();
|
||||
};
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public static Optional<String> getCurrentAvatar(Optional<VersionedProfileV1> maybeV1Profile) {
|
||||
return maybeV1Profile.map(VersionedProfileV1::avatar).filter(avatar -> avatar.startsWith("profiles/"));
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -63,6 +63,7 @@ import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
@@ -220,8 +221,10 @@ public record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getAccounts().getUsedLinkDeviceTokensTableName());
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfiles().getTableName());
|
||||
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfilesV1().getTableName());
|
||||
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfilesV2().getTableName());
|
||||
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
|
||||
.credentialsProvider(awsCredentialsProvider)
|
||||
.region(Region.of(configuration.getPagedSingleUseKEMPreKeyStore().region()))
|
||||
@@ -263,7 +266,7 @@ public record CommandDependencies(
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster,
|
||||
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC(), experimentEnrollmentManager);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
configuration.getCdnConfiguration().bucket());
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
|
||||
Reference in new issue
Block a user