diff --git a/service/config/sample.yml b/service/config/sample.yml index 3880ca52a..e5d629ed8 100644 --- a/service/config/sample.yml +++ b/service/config/sample.yml @@ -125,6 +125,8 @@ dynamoDbTables: tableName: Example_PhoneNumberIdentifiers profiles: tableName: Example_Profiles + profilesV2: + tableName: Example_ProfilesV2 pushChallenge: tableName: Example_PushChallenge pushNotificationExperimentSamples: diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 9ae34d94c..d03a6729b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -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 new WebApplicationException(Response.Status.UNAUTHORIZED)); - final Optional currentProfile = - profilesManager.get(auth.accountIdentifier(), request.version()); + if (account.hasCapability(DeviceCapability.PROFILES_V2)) { + return Response.status(Response.Status.PRECONDITION_FAILED).build(); + } + + final Optional 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 currentAvatar = Optional.empty(); - if (currentProfile.isPresent() && currentProfile.get().avatar() != null && currentProfile.get().avatar() - .startsWith("profiles/")) { - currentAvatar = Optional.of(currentProfile.get().avatar()); - } + final Optional 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 maybeProfile = profilesManager.get(account.getUuid(), version); + final Optional 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( diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AvatarChangeUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AvatarChangeUtil.java index fd0db7a7b..a4b398663 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AvatarChangeUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/AvatarChangeUtil.java @@ -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; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DeviceCapabilityUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DeviceCapabilityUtil.java index 77feba8c2..47e410913 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DeviceCapabilityUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DeviceCapabilityUtil.java @@ -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; }; } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcService.java index 260805e23..9f8cf8c72 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcService.java @@ -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 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 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 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 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)); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java index 5cc4d957d..cce50f800 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java @@ -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 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 profile; + if (account.hasCapability(DeviceCapability.PROFILES_V2)) { + profile = profilesManager.get(account.getUuid(), requestVersion); + } else { + profile = Optional.empty(); } - return responseBuilder.build(); + final Optional 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 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( + 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; + 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. + *

+ * 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); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java index fe11b81a2..23436daaf 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java @@ -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 currentAvatar, Optional 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 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 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 maybeProfile = profilesManager.get(authenticatedDevice.accountIdentifier(), + version); + final Optional 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 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 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 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 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 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 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 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) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java index a5be479ec..aec84aa4c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java @@ -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; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/validators/ServiceIdentifierIdentityTypeValidator.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/validators/ServiceIdentifierIdentityTypeValidator.java new file mode 100644 index 000000000..6adc29fa3 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/validators/ServiceIdentifierIdentityTypeValidator.java @@ -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 { + + 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()); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java index 7e224e252..1774d25e3 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -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 implemen }); } + /// Using a pessimistic lock, updates the current profile version to `newVersion` if `currentProfileVersion` matches + /// `expectedCurrentVersion`. The caller may provide a supplementary `Consumer` 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 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} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceCapability.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceCapability.java index 89e2354a3..108205a42 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceCapability.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceCapability.java @@ -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 { /** diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java index 4279015b6..cd882eef4 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java @@ -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 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 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 updatedAttributes = new ArrayList<>(5); final List deletedAttributes = new ArrayList<>(5); @@ -186,7 +187,7 @@ public class Profiles { } @VisibleForTesting - static Map buildUpdateExpressionAttributeValues(final VersionedProfile profile) { + static Map buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile) { final Map expressionValues = new HashMap<>(); expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.commitment())); @@ -217,7 +218,7 @@ public class Profiles { return expressionValues; } - public Optional get(final UUID uuid, final String version) { + public Optional 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> 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.empty()) - ).toCompletableFuture(); - } - - private static VersionedProfile fromItem(final Map item) { - return new VersionedProfile( + private static VersionedProfileV1 fromItem(final Map item) { + return new VersionedProfileV1( AttributeValues.getString(item, ATTR_VERSION, null), getBytes(item, ATTR_NAME), AttributeValues.getString(item, ATTR_AVATAR, null), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java index 46f3987c7..0b615b13f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java @@ -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 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 deleteAll(UUID uuid, final boolean includeAvatar) { - final CompletableFuture profilesAndAvatars = Mono.fromFuture(profiles.deleteAll(uuid)) + final CompletableFuture 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 deleteAvatar(String avatar) { @@ -110,87 +163,99 @@ public class ProfilesManager { .thenRun(Util.NOOP); } - public Optional get(UUID uuid, String version) { - Optional profile = redisGet(uuid, version); - - if (profile.isEmpty()) { - profile = profiles.get(uuid, version); + public Optional getV1(UUID uuid, String version) { + return redisGetV1(uuid, version).or(() -> { + final Optional 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> 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 get(UUID uuid, byte[] version) { + return redisGet(uuid, version).or(() -> { + final Optional 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 redisSetAsync(UUID uuid, VersionedProfile profile) { - final byte[] profileJson; - + private Optional 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 redisGet(UUID uuid, String version) { + @VisibleForTesting + static byte[] getCacheKeyV2(UUID uuid) { + return (CACHE_PREFIX_V2 + '{' + uuid.toString() + '}').getBytes(); + } + + private Optional 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> 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 parseProfileJson(@Nullable final byte[] maybeJson) { + private Optional parseProfileJson(@Nullable final byte[] maybeJson, Class 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 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 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); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesV2.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesV2.java new file mode 100644 index 000000000..88dbe0581 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesV2.java @@ -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 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 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 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 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 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 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 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 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 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 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(); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/VersionedProfile.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/VersionedProfile.java index c00a4efc6..707964f06 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/VersionedProfile.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/VersionedProfile.java @@ -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); + } + +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/VersionedProfileV1.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/VersionedProfileV1.java new file mode 100644 index 000000000..5bf0f6b59 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/VersionedProfileV1.java @@ -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)); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/WriteConflictException.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/WriteConflictException.java new file mode 100644 index 000000000..1d7b97dea --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/WriteConflictException.java @@ -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 { +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java index cc6cf3704..d9a088604 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/util/ProfileHelper.java @@ -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 maybeProfile, + final Optional maybeV1Profile, + final DynamicConfigurationManager dynamicConfigurationManager) { + + final Optional 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 currentAvatar) { + return switch (avatarChange) { + case UNCHANGED -> currentAvatar.orElse(null); + case CLEAR -> null; + case UPDATE -> ProfileHelper.generateAvatarObjectName(); + }; + } + + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + public static Optional getCurrentAvatar(Optional maybeV1Profile) { + return maybeV1Profile.map(VersionedProfileV1::avatar).filter(avatar -> avatar.startsWith("profiles/")); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index 25f540d19..5a2b0b405 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -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(), diff --git a/service/src/main/proto/org/signal/chat/common.proto b/service/src/main/proto/org/signal/chat/common.proto index dcd34af3b..99b3c2b23 100644 --- a/service/src/main/proto/org/signal/chat/common.proto +++ b/service/src/main/proto/org/signal/chat/common.proto @@ -19,7 +19,7 @@ enum IdentityType { message ServiceIdentifier { // The type of identity represented by this service identifier. - IdentityType identity_type = 1; + IdentityType identity_type = 1 [(require.specified) = true]; // The UUID of the identity represented by this service identifier. bytes uuid = 2 [(require.exactlySize) = 16]; @@ -83,6 +83,7 @@ enum DeviceCapability { reserved 5; DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6; DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7; + DEVICE_CAPABILITY_PROFILES_V2 = 8; } message ZkCredential { diff --git a/service/src/main/proto/org/signal/chat/profile.proto b/service/src/main/proto/org/signal/chat/profile.proto index 196d7fa37..c8fb025af 100644 --- a/service/src/main/proto/org/signal/chat/profile.proto +++ b/service/src/main/proto/org/signal/chat/profile.proto @@ -10,44 +10,22 @@ option java_multiple_files = true; package org.signal.chat.profile; import "org/signal/chat/common.proto"; +import "org/signal/chat/errors.proto"; +import "org/signal/chat/require.proto"; +import "org/signal/chat/tag.proto"; // Provides methods for working with profiles and profile-related data. service Profile { - // Sets profile data and if needed, returns S3 credentials used by clients to upload an avatar. - // - // This RPC may fail with `PERMISSION_DENIED` if it attempts to set the MobileCoin wallet ID - // on an account whose profile does not currently have a MobileCoin wallet ID and - // whose phone number contains a disallowed country prefix. + // Sets profile data and, if needed, returns credentials used by clients to upload a v1 avatar. rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {} // Retrieves versioned profile data. Callers with an unidentified access key for the account // should use the version of this method in `ProfileAnonymous` instead. - // - // This RPC may fail with a `NOT_FOUND` status if the target account was not - // found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been - // exceeded, in which case a `retry-after` header containing an ISO 8601 - // duration string will be present in the response trailers. rpc GetVersionedProfile(GetVersionedProfileRequest) returns (GetVersionedProfileResponse) {} // Retrieves unversioned profile data. Callers with an unidentified access key for the account // should use the version of this method in `ProfileAnonymous` instead. - // - // This RPC may fail with a `NOT_FOUND` status if the target account was not - // found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been - // exceeded, in which case a `retry-after` header containing an ISO 8601 - // duration string will be present in the response trailers. rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {} - - // Retrieves a profile key credential. - // Callers with an unidentified access key for the account - // should use the version of this method in `ProfileAnonymous` instead. - // - // This RPC may fail with a `NOT_FOUND` status if the target account was not - // found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been - // exceeded, in which case a `retry-after` header containing an ISO 8601 - // duration string will be present in the response trailers. It may also fail with an - // `INVALID_ARGUMENT` status if the given credential type is invalid. - rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialRequest) returns (GetExpiringProfileKeyCredentialResponse) {} } // Provides methods for working with profiles and profile-related data using "unidentified access" @@ -58,97 +36,206 @@ service Profile { // methods in `Profile` instead. service ProfileAnonymous { // Retrieves versioned profile data. - // - // This RPC may fail with a `NOT_FOUND` status if the target account was not - // found. It may also fail with an `UNAUTHENTICATED` status if the given - // unidentified access key did not match the target account's unidentified - // access key. - rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileResponse) {} + rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {} // Retrieves unversioned profile data. - // - // This RPC may fail with a `NOT_FOUND` status if the target account was not - // found. It may also fail with an `UNAUTHENTICATED` status if the given - // unidentified access key did not match the target account's unidentified - // access key. - rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileResponse) {} + rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {} // Retrieves a profile key credential. - // - // This RPC may fail with a `NOT_FOUND` status if the target account was not - // found. It may also fail with an `UNAUTHENTICATED` status if the given - // unidentified access key did not match the target account's unidentified - // access key, or an `INVALID_ARGUMENT` status if the given credential type is invalid. - rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialResponse) {} + rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {} } -message SetProfileRequest { +message SetProfileV1Request { enum AvatarChange { AVATAR_CHANGE_UNCHANGED = 0; AVATAR_CHANGE_CLEAR = 1; AVATAR_CHANGE_UPDATE = 2; } - // The profile version. Must be set. - string version = 1; + // The ciphertext of a name that users must set on the profile. - bytes name = 2; + bytes name = 1 [(require.exactlySize) = 81, (require.exactlySize) = 285]; + // An enum to indicate what change, if any, is made to the avatar with this request. - AvatarChange avatarChange = 3; + AvatarChange avatar_change = 2; + // The ciphertext of an emoji that users can set on their profile. - bytes about_emoji = 4; + bytes about_emoji = 3 [(require.exactlySize) = 0, (require.exactlySize) = 60]; + // The ciphertext of a description that users can set on their profile. - bytes about = 5; - // The ciphertext of the MobileCoin wallet ID on the profile. - bytes payment_address = 6; - // A list of badge IDs associated with the profile. - repeated string badge_ids = 7; + bytes about = 4 [(require.exactlySize) = 0, (require.exactlySize) = 156, (require.exactlySize) = 282, (require.exactlySize) = 540]; + // The ciphertext of the phone-number sharing setting on the profile. 29-byte encrypted boolean. - bytes phone_number_sharing = 8; + bytes phone_number_sharing = 6 [(require.exactlySize) = 29]; +} + +message SetProfileRequest { + + // The profile version. Required. + bytes version = 1 [(require.exactlySize) = 32]; + + // The ciphertext of a serialized Profile protobuf. Required. + // 937 max length = 909 plaintext serialization + 28 bytes encryption overhead + bytes data = 2 [(require.nonEmpty) = true, (require.size).max = 937]; + + // The SHA-256 hash of the Profile ciphertext being replaced. + // This is used an optimistic lock against concurrent changes. + // + // Optional, if this is the initial request to create a version. + bytes expected_current_data_hash = 3 [(require.exactlySize) = 0, (require.exactlySize) = 32]; + + // The current profile version being updated. + // This is used as an optimistic lock against concurrent changes. + // + // Optional, if there is no current profile version for the account. + bytes expected_current_version = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32]; + // The ciphertext of the MobileCoin wallet ID on the profile. + bytes payment_address = 5 [(require.exactlySize) = 0, (require.exactlySize) = 582]; + // A list of badge IDs associated with the profile. + repeated string badge_ids = 6; + // The profile key commitment. Used to issue a profile key credential response. - // Must be set on the request. - bytes commitment = 9; + // + // Required during the v1 -> v2 migration period. Afterwards will be optional, if this is an update to an existing version. + bytes commitment = 7 [(require.exactlySize) = 0, (require.exactlySize) = 97]; + + // An embedded v1 request. Required during the v1 -> v2 migration period. + // + // Because this is a temporary field during the migration, it has the highest + // field number without serialization overhead. This is purely aesthetic. + SetProfileV1Request v1Request = 15 [(require.present) = true]; + + // next: 8 +} + +// Indicates that the account is not permitted to set a payment address, +// due to a disallowed country prefix on the account's phone number. +message PaymentsForbiddenInRegion {} + +// Indicates that the account does not have the Profiles v2 capability, which +// is required to call Profiles.SetProfile +message ProfilesV2CapabilityRequired {} + + +message SetProfileResult { + // If the request included a v1 avatar change, this field contains the policy + // and credential used by clients to upload an avatar to the CDN. + // + // Because this is a temporary field during the migration, it has the highest + // field number without serialization overhead. This is purely aesthetic. + optional ProfileAvatarUploadAttributes v1_avatar_upload_form = 15; + + // next: 1 } message SetProfileResponse { - // The policy and credential used by clients to upload an avatar to S3. - ProfileAvatarUploadAttributes attributes = 1; + oneof response { + SetProfileResult result = 1; + errors.FailedPrecondition write_conflict = 2 [(tag.reason) = "write_conflict"]; + PaymentsForbiddenInRegion payments_forbidden_in_region = 3 [(tag.reason) = "payments_forbidden_in_region"]; + + // Because this is a temporary field during the migration, it has the highest + // field number without serialization overhead. This is purely aesthetic. + ProfilesV2CapabilityRequired profiles_v2_capability_required = 15 [(tag.reason) = "profiles_v2_capability_required"]; + + // next: 4 + } } message GetVersionedProfileRequest { // The ACI of the account for which to get profile data. - common.ServiceIdentifier accountIdentifier = 1; + common.ServiceIdentifier accountIdentifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI]; // The profile version to retrieve. - string version = 2; + bytes version = 2 [(require.exactlySize) = 32]; + + // The `data_etag` from the previous request for this Profile version. If + // unchanged, the response will omit `data` and `data_etag_matched` will be + // `true`. + bytes data_etag = 3 [(require.exactlySize) = 0, (require.exactlySize) = 32]; + + // The `payment_address_etag` from the previous request for this account’s + // profile. If unchanged, the response will omit `payment_address` and + // `payment_address_etag_matched` will be `true`. + bytes payment_address_etag = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32]; } message GetVersionedProfileAnonymousRequest { // Contains the data necessary to request a versioned profile. - GetVersionedProfileRequest request = 1; + GetVersionedProfileRequest request = 1 [(require.present) = true]; // The unidentified access key for the targeted account. - bytes unidentified_access_key = 2; + bytes unidentified_access_key = 2 [(require.exactlySize) = 16]; +} + +message DataEtag { + bytes data = 1; + // An entity tag for `data`. This may be used in subsequent requests for + // this profile version to optimize bandwidth. + bytes etag = 2; +} + + +message GetVersionedProfileResult { + + oneof data_result { + // The ciphertext of a serialized Profile. + // Absent if a v2 Profile is not available + // for this version, in which the client should use `v1_response`. + DataEtag data_etag = 1; + // Indicates that the request’s ETag matched the stored `data` + bool data_etag_matched = 2; + + // Will be present if there is no v2 Profile data for this version. + // + // Because this is a temporary field during the migration, it has the highest + // field number without serialization overhead. This is purely aesthetic. + GetVersionedProfileV1Response v1_response = 15; + } + + oneof payment_address_result { + // The ciphertext of the MobileCoin wallet ID on the profile. + DataEtag payment_address_data_etag = 3; + // Indicates that the request’s ETag matched the stored `payment_address` + bool payment_address_etag_matched = 4; + } + + // next: 5 } message GetVersionedProfileResponse { + oneof response { + GetVersionedProfileResult result = 1; + errors.NotFound not_found = 2 [(tag.reason) = "not_found"]; + } +} + +message GetVersionedProfileAnonymousResponse { + oneof response { + GetVersionedProfileResult result = 1; + errors.NotFound not_found = 2 [(tag.reason) = "not_found"]; + errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"]; + } +} + +message GetVersionedProfileV1Response { + // The ciphertext of the name on the profile. bytes name = 1; // The ciphertext of the description on the profile. bytes about = 2; // The ciphertext of the emoji on the profile. bytes about_emoji = 3; - // The S3 path of the avatar on the profile. + // The cdn0 path of the avatar on the profile. string avatar = 4; - // The ciphertext of the MobileCoin wallet ID on the profile. - bytes payment_address = 5; + // The ciphertext of the phone-number sharing setting on the profile. - bytes phone_number_sharing = 6; + bytes phone_number_sharing = 5; } message GetUnversionedProfileRequest { // The service identifier of the account for which to get profile data. - common.ServiceIdentifier serviceIdentifier = 1; + common.ServiceIdentifier service_identifier = 1 [(require.present) = true]; } message GetUnversionedProfileAnonymousRequest { - // Contains the data necessary to request an unversioned profile. - GetUnversionedProfileRequest request = 1; + // Note: Only ACI service identifiers are permitted for anonymous requests. + GetUnversionedProfileRequest request = 1 [(require.present) = true]; oneof authentication { // The unidentified access key for the targeted account. @@ -159,7 +246,7 @@ message GetUnversionedProfileAnonymousRequest { } } -message GetUnversionedProfileResponse { +message GetUnversionedProfileResult { // The identity key of the targeted account/identity type. bytes identity_key = 1; // A checksum of the unidentified access key for the targeted account. @@ -172,28 +259,61 @@ message GetUnversionedProfileResponse { repeated Badge badges = 5; } +message GetUnversionedProfileResponse { + oneof response { + GetUnversionedProfileResult result = 1; + errors.NotFound not_found = 2 [(tag.reason) = "not_found"]; + } +} + +message GetUnversionedProfileAnonymousResponse { + oneof response { + GetUnversionedProfileResult result = 1; + // The target profile was not found + errors.NotFound not_found = 2 [(tag.reason) = "not_found"]; + // The unidentified access key or group send endorsement were not valid for + // the request. + errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"]; + } +} + message GetExpiringProfileKeyCredentialRequest { // The ACI of the account for which to get a profile key credential. - common.ServiceIdentifier accountIdentifier = 1; + common.ServiceIdentifier account_identifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI]; // A zkgroup request for a profile key credential. - bytes credential_request = 2; + bytes credential_request = 2 [(require.nonEmpty) = true]; // The type of credential being requested. - CredentialType credential_type = 3; + CredentialType credential_type = 3 [(require.specified) = true]; // The profile version for which to generate a profile key credential. - string version = 4; + bytes version = 4 [(require.exactlySize) = 32]; } message GetExpiringProfileKeyCredentialAnonymousRequest { // Contains the data necessary to request an expiring profile key credential. - GetExpiringProfileKeyCredentialRequest request = 1; + GetExpiringProfileKeyCredentialRequest request = 1 [(require.present) = true]; // The unidentified access key for the targeted account. - bytes unidentified_access_key = 2; + bytes unidentified_access_key = 2 [(require.exactlySize) = 16]; +} + +message GetExpiringProfileKeyCredentialResult { + // A zkgroup credential used by a client to prove that it has the profile key + // of a targeted account. + bytes profile_key_credential = 1; } message GetExpiringProfileKeyCredentialResponse { - // A zkgroup credential used by a client to prove that it has the profile key - // of a targeted account. - bytes profileKeyCredential = 1; + oneof response { + GetExpiringProfileKeyCredentialResult result = 1; + errors.NotFound not_found = 2 [(tag.reason) = "not_found"]; + } +} + +message GetExpiringProfileKeyCredentialAnonymousResponse { + oneof response { + GetExpiringProfileKeyCredentialResult result = 1; + errors.NotFound not_found = 2 [(tag.reason) = "not_found"]; + errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"]; + } } message ProfileAvatarUploadAttributes { diff --git a/service/src/main/proto/org/signal/chat/require.proto b/service/src/main/proto/org/signal/chat/require.proto index bbfeaf1d1..bb3bd9d4e 100644 --- a/service/src/main/proto/org/signal/chat/require.proto +++ b/service/src/main/proto/org/signal/chat/require.proto @@ -157,11 +157,28 @@ extend google.protobuf.FieldOptions { * import "org/signal/chat/require.proto"; * * message Data { - * string myString = 1 [(require.base64url)]; + * string myString = 1 [(require.base64url) = true]; * } * ``` */ optional bool base64url = 70008; + + /* + * Requires a common.ServiceIdentifier field to have its IdentityType + * be the given type (`aci` or `pni`). + * + * ``` + * import "org/signal/chat/require.proto"; + * import "org/signal/chat/common.proto"; + * + * message Data { + * common.ServiceIdentifier accountIdentifier = 1 [(require.identityType) = IDENTITY_TYPE_ACI]; + * } + * ``` + */ + optional IdentityType identityType = 70009; + + // next 70010 } message SizeConstraint { @@ -197,3 +214,11 @@ enum Auth { AUTH_ONLY_ANONYMOUS = 2; } +// This is duplicated from common.proto because: +// 1. importing would be a circular dependency +// 2. the canonical declaration belongs there +enum IdentityType { + IDENTITY_TYPE_UNSPECIFIED = 0; + IDENTITY_TYPE_ACI = 1; + IDENTITY_TYPE_PNI = 2; +} diff --git a/service/src/main/resources/lua/profile_set.lua b/service/src/main/resources/lua/profile_set.lua new file mode 100644 index 000000000..8a41f5b37 --- /dev/null +++ b/service/src/main/resources/lua/profile_set.lua @@ -0,0 +1,15 @@ +-- Atomically sets v1 and v2 profile cache entries +local v1Key = KEYS[1] -- v1 profile hash key +local v2Key = KEYS[2] -- v2 profile hash key +local v1Field = ARGV[1] -- v1 profile version +local v1Value = ARGV[2] -- v1 profile data +local v2Field = ARGV[3] -- v2 profile version +local v2Value = ARGV[4] -- v2 profile data + +if #v1Field > 0 then + redis.call("HSET", v1Key, v1Field, v1Value) +end + +if #v2Field > 0 then + redis.call("HSET", v2Key, v2Field, v2Value) +end diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java index 84b36a349..c77210f99 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java @@ -106,7 +106,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.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; @@ -232,8 +232,8 @@ class ProfileControllerTest { final byte[] about = TestRandomUtil.nextBytes(156); final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29); - when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty()); - when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfile( + when(profilesManager.getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty()); + when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfileV1( versionHex("validversion"), name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes()))); when(profilesManager.deleteAvatar(anyString())).thenReturn(CompletableFuture.completedFuture(null)); @@ -467,10 +467,10 @@ class ProfileControllerTest { name, null, null, null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion"))); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion"))); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture()); verifyNoMoreInteractions(profilesManager); @@ -516,10 +516,10 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion"))); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion"))); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verifyNoMoreInteractions(profilesManager); @@ -546,10 +546,10 @@ class ProfileControllerTest { name, null, null, null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar"); assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize()); @@ -575,10 +575,10 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar")); assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize()); @@ -605,10 +605,10 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verify(profilesManager, never()).deleteAvatar(anyString()); assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize()); @@ -633,10 +633,10 @@ class ProfileControllerTest { null, null, null, false, true, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE))) { - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion"))); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar")); assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize()); @@ -663,10 +663,10 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(version)); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(version)); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture()); verify(profilesManager, never()).deleteAvatar(anyString()); assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize()); @@ -694,10 +694,10 @@ class ProfileControllerTest { null, null, null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version)); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version)); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar"); assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize()); @@ -731,14 +731,14 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version)); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version)); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verifyNoMoreInteractions(profilesManager); - final VersionedProfile profile = profileArgumentCaptor.getValue(); + final VersionedProfileV1 profile = profileArgumentCaptor.getValue(); assertThat(profile.commitment()).isEqualTo(commitment.serialize()); assertThat(profile.avatar()).isNull(); assertThat(profile.version()).isEqualTo(version); @@ -771,14 +771,14 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version)); - verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version)); + verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verifyNoMoreInteractions(profilesManager); - final VersionedProfile profile = profileArgumentCaptor.getValue(); + final VersionedProfileV1 profile = profileArgumentCaptor.getValue(); assertThat(profile.commitment()).isEqualTo(commitment.serialize()); assertThat(profile.avatar()).isNull(); assertThat(profile.version()).isEqualTo(version); @@ -813,7 +813,7 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(403); assertThat(response.hasEntity()).isFalse(); - verify(profilesManager, never()).set(any(), any()); + verify(profilesManager, never()).setV1(any(), any()); } } @@ -831,9 +831,9 @@ class ProfileControllerTest { clearInvocations(AuthHelper.VALID_ACCOUNT_TWO); - when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any())) + when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), any())) .thenReturn(Optional.of( - new VersionedProfile("1", name, null, null, null, + new VersionedProfileV1("1", name, null, null, null, existingPaymentAddressOnProfile ? TestRandomUtil.nextBytes(582) : null, phoneNumberSharing, commitment.serialize()))); @@ -852,14 +852,14 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version)); - verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version)); + verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verifyNoMoreInteractions(profilesManager); - final VersionedProfile profile = profileArgumentCaptor.getValue(); + final VersionedProfileV1 profile = profileArgumentCaptor.getValue(); assertThat(profile.commitment()).isEqualTo(commitment.serialize()); assertThat(profile.avatar()).isNull(); assertThat(profile.version()).isEqualTo(version); @@ -871,7 +871,7 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(403); assertThat(response.hasEntity()).isFalse(); - verify(profilesManager, never()).set(any(), any()); + verify(profilesManager, never()).setV1(any(), any()); } } } @@ -895,10 +895,10 @@ class ProfileControllerTest { assertThat(response.getStatus()).isEqualTo(200); assertThat(response.hasEntity()).isFalse(); - final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); + final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); - verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version)); - verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); + verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version)); + verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture()); verifyNoMoreInteractions(profilesManager); @@ -919,7 +919,7 @@ class ProfileControllerTest { final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29); final String version = versionHex("validversion"); - when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfile( + when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfileV1( version, name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes()))); final VersionedProfileResponse profile = resources.getJerseyTest() @@ -970,8 +970,8 @@ class ProfileControllerTest { void testGetProfileReturnsNoPaymentAddressIfCurrentVersionMismatch() { final byte[] paymentAddress = TestRandomUtil.nextBytes(582); final String version = versionHex("validversion"); - when(profilesManager.get(AuthHelper.VALID_UUID_TWO, version)).thenReturn( - Optional.of(new VersionedProfile(null, null, null, null, null, paymentAddress, null, null))); + when(profilesManager.getV1(AuthHelper.VALID_UUID_TWO, version)).thenReturn( + Optional.of(new VersionedProfileV1(version, null, null, null, null, paymentAddress, null, null))); { final VersionedProfileResponse profile = resources.getJerseyTest() @@ -1016,7 +1016,7 @@ class ProfileControllerTest { when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("version"))); when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account)); - when(profilesManager.get(any(), any())).thenReturn(Optional.empty()); + when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty()); final ExpiringProfileKeyCredentialProfileResponse profile = resources.getJerseyTest() .target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, versionHex("version-that-does-not-exist"), "credential-request")) @@ -1211,7 +1211,7 @@ class ProfileControllerTest { final ProfileKey profileKey = new ProfileKey(profileKeyBytes); final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID)); - final VersionedProfile versionedProfile = mock(VersionedProfile.class); + final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class); when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize()); final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext = @@ -1233,7 +1233,7 @@ class ProfileControllerTest { serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(AuthHelper.VALID_UUID), profileKeyCommitment, expiration); when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account)); - when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile)); + when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile)); when(zkProfileOperations.issueExpiringProfileKeyCredential(eq(credentialRequest), eq(new ServiceId.Aci(AuthHelper.VALID_UUID)), eq(profileKeyCommitment), any())) .thenReturn(credentialResponse); @@ -1279,7 +1279,7 @@ class ProfileControllerTest { final ProfileKey profileKey = new ProfileKey(profileKeyBytes); final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID)); - final VersionedProfile versionedProfile = mock(VersionedProfile.class); + final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class); when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize()); final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext = @@ -1294,7 +1294,7 @@ class ProfileControllerTest { when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version)); when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account)); - when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile)); + when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile)); when(zkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any())) .thenThrow(new VerificationFailedException()); @@ -1324,7 +1324,7 @@ class ProfileControllerTest { final ProfileKey profileKey = new ProfileKey(profileKeyBytes); final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID)); - final VersionedProfile versionedProfile = mock(VersionedProfile.class); + final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class); when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize()); final String avatar = "avatar"; when(versionedProfile.avatar()).thenReturn(avatar); @@ -1341,7 +1341,7 @@ class ProfileControllerTest { when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("the-current-version"))); when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account)); - when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile)); + when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile)); final Response response = resources.getJerseyTest() .target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, version, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcTestUtils.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcTestUtils.java index 55e518055..31b0eba69 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcTestUtils.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcTestUtils.java @@ -10,23 +10,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verifyNoInteractions; -import com.google.protobuf.Any; import com.google.protobuf.Message; import com.google.rpc.ErrorInfo; import com.google.rpc.RetryInfo; -import io.grpc.BindableService; -import io.grpc.ServerInterceptors; import io.grpc.Status; -import io.grpc.StatusException; import io.grpc.StatusRuntimeException; import java.time.Duration; -import java.util.List; -import java.util.UUID; import io.grpc.protobuf.StatusProto; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.function.Executable; -import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor; -import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; public final class GrpcTestUtils { @@ -34,9 +26,11 @@ public final class GrpcTestUtils { // noop } - public static void assertStatusException(final Status expected, final Executable serviceCall) { + public static StatusRuntimeException assertStatusException(final Status expected, final Executable serviceCall) { final StatusRuntimeException exception = Assertions.assertThrows(StatusRuntimeException.class, serviceCall); assertEquals(expected.getCode(), exception.getStatus().getCode()); + + return exception; } public static void assertStatusException(final Status expected, final String expectedReason, final Executable serviceCall) { @@ -45,16 +39,16 @@ public final class GrpcTestUtils { assertEquals(expectedReason, extractErrorInfo(exception).getReason()); } - public static void assertStatusInvalidArgument(final Executable serviceCall) { - assertStatusException(Status.INVALID_ARGUMENT, serviceCall); + public static StatusRuntimeException assertStatusInvalidArgument(final Executable serviceCall) { + return assertStatusException(Status.INVALID_ARGUMENT, serviceCall); } - public static void assertStatusUnauthenticated(final Executable serviceCall) { - assertStatusException(Status.UNAUTHENTICATED, serviceCall); + public static StatusRuntimeException assertStatusUnauthenticated(final Executable serviceCall) { + return assertStatusException(Status.UNAUTHENTICATED, serviceCall); } - public static void assertStatusPermissionDenied(final Executable serviceCall) { - assertStatusException(Status.PERMISSION_DENIED, serviceCall); + public static StatusRuntimeException assertStatusPermissionDenied(final Executable serviceCall) { + return assertStatusException(Status.PERMISSION_DENIED, serviceCall); } public static void assertRateLimitExceeded( @@ -68,8 +62,8 @@ public final class GrpcTestUtils { final ErrorInfo errorInfo = extractErrorInfo(exception); final RetryInfo retryInfo = extractDetail(RetryInfo.class, exception); final Duration actual = Duration.ofSeconds(retryInfo.getRetryDelay().getSeconds(), retryInfo.getRetryDelay().getNanos()); - assertEquals(errorInfo.getDomain(), GrpcExceptions.DOMAIN); - assertEquals(errorInfo.getReason(), "RESOURCE_EXHAUSTED"); + assertEquals(GrpcExceptions.DOMAIN, errorInfo.getDomain()); + assertEquals("RESOURCE_EXHAUSTED", errorInfo.getReason()); assertEquals(expectedRetryAfter, actual); for (final Object mock: mocksToCheckForNoInteraction) { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java index 985f87db8..2d0b6d8fd 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java @@ -7,9 +7,16 @@ package org.whispersystems.textsecuregcm.grpc; import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -20,12 +27,15 @@ import com.google.protobuf.ByteString; import io.grpc.ServerInterceptor; import io.grpc.Status; import java.nio.charset.StandardCharsets; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.Collection; import java.util.Collections; +import java.util.HexFormat; import java.util.List; -import java.util.Locale; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; @@ -34,24 +44,28 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.signal.chat.common.IdentityType; import org.signal.chat.common.ServiceIdentifier; import org.signal.chat.profile.CredentialType; +import org.signal.chat.profile.DataEtag; import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest; +import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse; import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest; -import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse; import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest; +import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse; import org.signal.chat.profile.GetUnversionedProfileRequest; -import org.signal.chat.profile.GetUnversionedProfileResponse; +import org.signal.chat.profile.GetUnversionedProfileResult; import org.signal.chat.profile.GetVersionedProfileAnonymousRequest; +import org.signal.chat.profile.GetVersionedProfileAnonymousResponse; import org.signal.chat.profile.GetVersionedProfileRequest; -import org.signal.chat.profile.GetVersionedProfileResponse; +import org.signal.chat.profile.GetVersionedProfileResult; +import org.signal.chat.profile.GetVersionedProfileV1Response; import org.signal.chat.profile.ProfileAnonymousGrpc; import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.ServiceId; import org.signal.libsignal.protocol.ecc.ECKeyPair; -import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.ServerSecretParams; import org.signal.libsignal.zkgroup.VerificationFailedException; import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations; @@ -60,6 +74,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKey; import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment; import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest; import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext; +import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter; @@ -71,6 +86,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager; 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.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; import org.whispersystems.textsecuregcm.util.TestRandomUtil; @@ -78,7 +94,7 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil; public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest { - private final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate(); + private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate(); @Mock private Account account; @@ -92,17 +108,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getUnversionedProfile(request)); + if (IdentityType.IDENTITY_TYPE_PNI.equals(identityType)) { + assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getUnversionedProfile(request)); + } else { + + final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request); + + assertTrue(response.hasFailedUnidentifiedAuthorization()); + } } private static Stream getUnversionedProfileIncorrectUnidentifiedAccessKey() { @@ -254,9 +288,13 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getUnversionedProfile(request)); + final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile( + request); + + assertTrue(response.hasFailedUnidentifiedAuthorization()); } @Test @@ -281,7 +322,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getUnversionedProfile(request)); + final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request); + + assertTrue(response.hasFailedUnidentifiedAuthorization()); } @Test @@ -307,13 +350,16 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getUnversionedProfile(request)); + final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile( + request); + + assertTrue(response.hasNotFound()); } @ParameterizedTest @MethodSource - void getVersionedProfile(final String requestVersion, - @Nullable final String accountVersion, + void getVersionedProfile(final byte[] requestVersion, + @Nullable final byte[] accountVersion, final boolean expectResponseHasPaymentAddress) { final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); @@ -324,14 +370,14 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest profile = Optional.of(new VersionedProfileV1(HexFormat.of().formatHex(requestVersion), name, avatar, emoji, about, paymentAddress, phoneNumberSharing, new byte[0])); - when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion)); + when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v))); when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false); when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account)); - when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile)); + when(profilesManager.getV1(any(), any())).thenReturn(profile); final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder() .setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)) @@ -340,34 +386,131 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest getVersionedProfile() { - return Stream.of( - Arguments.of("version1", "version1", true), - Arguments.of("version1", null, true), - Arguments.of("version1", "version2", false) + private static Collection getVersionedProfile() { + final byte[] version1 = TestRandomUtil.nextBytes(32); + final byte[] version2 = TestRandomUtil.nextBytes(32); + return List.of( + Arguments.argumentSet("current profile version matches", version1, version1, true), + Arguments.argumentSet("current profile version absent",version1, null, true), + Arguments.argumentSet("current profile version mismatch",version1, version2, false) ); } + @Test + void getVersionedProfileV2() { + final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); + final byte[] data = TestRandomUtil.nextBytes(128); + final byte[] paymentAddress = TestRandomUtil.nextBytes(582); + final byte[] commitment = TestRandomUtil.nextBytes(97); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment); + + when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex)); + when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false); + when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); + when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true); + when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account)); + when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile)); + when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty()); + + final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder() + .setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)) + .setRequest(GetVersionedProfileRequest.newBuilder() + .setAccountIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) + .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) + .build()) + .setVersion(ByteString.copyFrom(version)) + .build()) + .build(); + + final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request); + assertTrue(response.hasResult()); + + final GetVersionedProfileResult result = response.getResult(); + assertTrue(result.hasDataEtag()); + assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData()); + assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtag()); + assertTrue(result.hasPaymentAddressDataEtag()); + assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData()); + assertEquals(ByteString.copyFrom(Objects.requireNonNull(v2Profile.paymentAddressHash())), result.getPaymentAddressDataEtag().getEtag()); + assertFalse(result.getDataEtagMatched()); + assertFalse(result.getPaymentAddressEtagMatched()); + assertFalse(result.hasV1Response()); + } + + @Test + void getVersionedProfileV2EtagMatched() { + final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); + final byte[] data = TestRandomUtil.nextBytes(128); + final byte[] paymentAddress = TestRandomUtil.nextBytes(582); + final byte[] commitment = TestRandomUtil.nextBytes(97); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment); + + when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex)); + when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false); + when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); + when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true); + when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account)); + when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile)); + when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty()); + + final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder() + .setAccountIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) + .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) + .build()) + .setVersion(ByteString.copyFrom(version)) + .setDataEtag(ByteString.copyFrom(v2Profile.dataHash())); + + if (v2Profile.paymentAddressHash() != null) { + builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash())); + } + + final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder() + .setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)) + .setRequest(builder.build()) + .build(); + + final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request); + assertTrue(response.hasResult()); + + final GetVersionedProfileResult result = response.getResult(); + assertTrue(result.getDataEtagMatched()); + assertTrue(result.getPaymentAddressEtagMatched()); + assertFalse(result.hasDataEtag()); + assertFalse(result.hasPaymentAddressDataEtag()); + assertFalse(result.hasV1Response()); + } + @Test void getVersionedProfileVersionNotFound() { final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); @@ -376,7 +519,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getVersionedProfile(request)); + final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile( + request); + + assertTrue(response.hasNotFound()); } @ParameterizedTest @MethodSource - void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, - final boolean accountNotFound) { + void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) { final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false); @@ -409,14 +554,23 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build())); + } else { requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)); + final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile( + requestBuilder.build()); + + assertEquals(accountNotFound, response.hasNotFound()); + assertNotEquals(accountNotFound, response.hasFailedUnidentifiedAuthorization()); } - assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build())); + } private static Stream getVersionedProfileUnauthenticated() { return Stream.of( @@ -436,7 +590,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest - clientZkProfile.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, new ExpiringProfileKeyCredentialResponse(response.getProfileKeyCredential().toByteArray()))); + clientZkProfile.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, + new ExpiringProfileKeyCredentialResponse(response.getResult().getProfileKeyCredential().toByteArray()))); } @ParameterizedTest @@ -507,14 +663,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getExpiringProfileKeyCredential(requestBuilder.build())); - assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(requestBuilder.build())); + } else { + requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)); + + final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential( + requestBuilder.build()); + + assertEquals(missingAccount, response.hasNotFound()); + assertNotEquals(missingAccount, response.hasFailedUnidentifiedAuthorization()); + } verifyNoInteractions(profilesManager); } @@ -522,7 +686,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest getExpiringProfileKeyCredentialUnauthenticated() { return Stream.of( Arguments.of(true, false), - Arguments.of(false, true) + Arguments.of(false, true), + Arguments.of(true, true) ); } @@ -532,11 +697,15 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getExpiringProfileKeyCredential(request)); + final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential( + request); + + assertTrue(response.hasNotFound()); } @ParameterizedTest @MethodSource void getExpiringProfileKeyCredentialInvalidArgument(final IdentityType identityType, final CredentialType credentialType, + final byte[] credentialRequest, final boolean throwZkVerificationException) throws VerificationFailedException { final UUID targetUuid = UUID.randomUUID(); final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); - final VersionedProfile profile = mock(VersionedProfile.class); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + + final VersionedProfileV1 profile = mock(VersionedProfileV1.class); when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8)); when(account.getUuid()).thenReturn(targetUuid); when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account)); - when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile)); + when(profilesManager.getV1(targetUuid, versionHex)).thenReturn(Optional.of(profile)); + + if (throwZkVerificationException) { + doThrow(VerificationFailedException.class) + .when(zkProfileOperations).issueExpiringProfileKeyCredential(any(), any(), any(), any()); + } final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder() .setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)) @@ -575,23 +756,37 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getExpiringProfileKeyCredential(request)); } - private static Stream getExpiringProfileKeyCredentialInvalidArgument() { + private static Stream getExpiringProfileKeyCredentialInvalidArgument() throws Exception { + final byte[] invalidCredentialRequest = "invalidRequest".getBytes(); + + final UUID targetUuid = UUID.randomUUID(); + + final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(SERVER_SECRET_PARAMS.getPublicParams()); + + final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32); + + final ProfileKey profileKey = new ProfileKey(profileKeyBytes); + final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid)); + final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext = + clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey); + final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest(); + + final byte[] validCredentialRequest = credentialRequest.serialize(); + return Stream.of( - // Credential type unspecified - Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, false), - // Illegal identity type - Arguments.of(IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, false), - // Artificially fails zero knowledge verification - Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, true) + Arguments.argumentSet("Credential type unspecified", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, validCredentialRequest, false), + Arguments.argumentSet("Illegal identity type", IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, validCredentialRequest, false), + Arguments.argumentSet("Invalid credential request", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, invalidCredentialRequest, false), + Arguments.argumentSet("ZK verification failure", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, validCredentialRequest, true) ); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java index 80872b143..378438fea 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java @@ -6,15 +6,15 @@ package org.whispersystems.textsecuregcm.grpc; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.refEq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -24,25 +24,29 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded; import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException; +import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusInvalidArgument; import com.google.common.net.InetAddresses; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import com.google.protobuf.ByteString; +import com.google.rpc.BadRequest; import io.grpc.ServerInterceptor; import io.grpc.Status; -import java.nio.charset.StandardCharsets; +import io.grpc.StatusRuntimeException; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; -import java.time.temporal.ChronoUnit; +import java.util.Collection; import java.util.Collections; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; @@ -55,31 +59,26 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.signal.chat.common.IdentityType; import org.signal.chat.common.ServiceIdentifier; -import org.signal.chat.profile.CredentialType; -import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest; -import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse; +import org.signal.chat.profile.DataEtag; import org.signal.chat.profile.GetUnversionedProfileRequest; import org.signal.chat.profile.GetUnversionedProfileResponse; +import org.signal.chat.profile.GetUnversionedProfileResult; import org.signal.chat.profile.GetVersionedProfileRequest; import org.signal.chat.profile.GetVersionedProfileResponse; +import org.signal.chat.profile.GetVersionedProfileResult; +import org.signal.chat.profile.GetVersionedProfileV1Response; import org.signal.chat.profile.ProfileGrpc; 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; +import org.signal.chat.profile.SetProfileV1Request.AvatarChange; +import org.signal.chat.profile.test.PlaintextProfileData; import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.ServiceId; import org.signal.libsignal.protocol.ecc.ECKeyPair; import org.signal.libsignal.zkgroup.InvalidInputException; -import org.signal.libsignal.zkgroup.ServerPublicParams; -import org.signal.libsignal.zkgroup.ServerSecretParams; -import org.signal.libsignal.zkgroup.VerificationFailedException; -import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations; -import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse; import org.signal.libsignal.zkgroup.profiles.ProfileKey; -import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment; -import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest; -import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext; -import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter; @@ -99,10 +98,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.tests.util.AccountsHelper; +import org.whispersystems.textsecuregcm.storage.VersionedProfileV1; +import org.whispersystems.textsecuregcm.storage.WriteConflictException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; import org.whispersystems.textsecuregcm.util.MockUtils; @@ -111,10 +112,17 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil; public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest { - private static final String VERSION = "someVersion"; + private static final byte[] VERSION = TestRandomUtil.nextBytes(32); + + private static final byte[] VALID_DATA = new byte[128]; private static final byte[] VALID_NAME = new byte[81]; + private static final SetProfileV1Request V1_REQUEST = SetProfileV1Request.newBuilder() + .setName(ByteString.copyFrom(VALID_NAME)) + .setPhoneNumberSharing(ByteString.copyFrom(TestRandomUtil.nextBytes(29))) + .build(); + @Mock private AccountsManager accountsManager; @@ -125,7 +133,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest v2 migration, commitment can be null if expectedDataHash is present .setPaymentAddress(ByteString.copyFrom(validPaymentAddress)) - .setPhoneNumberSharing(ByteString.copyFrom(validPhoneNumberSharing)) - .setCommitment(ByteString.copyFrom(commitment)) + .setV1Request(V1_REQUEST.toBuilder() + .setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED) + .setAboutEmoji(ByteString.copyFrom(validAboutEmoji)) + .setAbout(ByteString.copyFrom(validAbout)) + .setPhoneNumberSharing(ByteString.copyFrom(validPhoneNumberSharing)) + ) .build(); authenticatedServiceStub().setProfile(request); + final ArgumentCaptor profileV1ArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class); final ArgumentCaptor profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class); - verify(profilesManager).set(eq(account.getUuid()), profileArgumentCaptor.capture()); + verify(profilesManager).set(eq(account.getUuid()), profileV1ArgumentCaptor.capture(), profileArgumentCaptor.capture(), isNull()); final VersionedProfile profile = profileArgumentCaptor.getValue(); - assertThat(profile.commitment()).isEqualTo(commitment); - assertThat(profile.avatar()).isNull(); assertThat(profile.version()).isEqualTo(VERSION); - assertThat(profile.name()).isEqualTo(VALID_NAME); - assertThat(profile.aboutEmoji()).isEqualTo(validAboutEmoji); - assertThat(profile.about()).isEqualTo(validAbout); + assertThat(profile.data()).isEqualTo(VALID_DATA); + assertThat(profile.dataHash()).hasSize(32); + assertThat(profile.commitment()).isEqualTo(commitment); assertThat(profile.paymentAddress()).isEqualTo(validPaymentAddress); - assertThat(profile.phoneNumberSharing()).isEqualTo(validPhoneNumberSharing); + assertThat(profile.paymentAddressHash()).hasSize(32); + + final VersionedProfileV1 v1Profile = profileV1ArgumentCaptor.getValue(); + + assertThat(v1Profile.commitment()).isEqualTo(commitment); + assertThat(v1Profile.avatar()).isNull(); + assertThat(v1Profile.version()).isEqualTo(HexFormat.of().formatHex(VERSION)); + assertThat(v1Profile.name()).isEqualTo(VALID_NAME); + assertThat(v1Profile.aboutEmoji()).isEqualTo(validAboutEmoji); + assertThat(v1Profile.about()).isEqualTo(validAbout); + assertThat(v1Profile.paymentAddress()).isEqualTo(validPaymentAddress); + assertThat(v1Profile.phoneNumberSharing()).isEqualTo(validPhoneNumberSharing); + } + + @Test + void setProfileWithoutCapability() { + when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(false); + + final SetProfileRequest request = SetProfileRequest.newBuilder() + .setVersion(ByteString.copyFrom(VERSION)) + .setData(ByteString.copyFrom(VALID_DATA)) + .setExpectedCurrentDataHash(ByteString.copyFrom(TestRandomUtil.nextBytes(32))) + .setV1Request(V1_REQUEST) + .build(); + + final SetProfileResponse response = authenticatedServiceStub().setProfile(request); + + assertTrue(response.hasProfilesV2CapabilityRequired()); } @ParameterizedTest @@ -256,22 +289,25 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().setProfile(request)); + void setProfileInvalidRequestData(final SetProfileRequest request, final String invalidFieldOrMessageFragment, final boolean assertFieldViolation) { + assertStatusInvalidArgument(() -> authenticatedServiceStub().setProfile(request)); + // com.google.rpc.Status.parseFrom(exception.getTrailers().valueAsBytes(0)).getDetailsList().get(1).unpack(BadRequest.class).getFieldViolationsList().getFirst().getField() + final StatusRuntimeException e = assertStatusInvalidArgument(() -> authenticatedServiceStub().setProfile(request)); + if (assertFieldViolation) { + final List fieldViolations = GrpcTestUtils.extractDetail(BadRequest.class, e) + .getFieldViolationsList(); + + assertEquals(1, fieldViolations.size()); + assertEquals(invalidFieldOrMessageFragment, fieldViolations.getFirst().getField()); + } else { + assertThat(e.getMessage()).contains(invalidFieldOrMessageFragment); + } } private static Stream setProfileInvalidRequestData() throws InvalidInputException{ @@ -309,40 +356,49 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().setProfile(request), - "Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address"); + assertTrue(response.hasResult(), "Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address"); } else { - assertStatusException(Status.PERMISSION_DENIED, () -> authenticatedServiceStub().setProfile(request)); + assertTrue(response.hasPaymentsForbiddenInRegion()); } } @Test - void setProfileBadges() throws InvalidInputException { + void setProfileBadges() throws Exception { final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize(); final SetProfileRequest request = SetProfileRequest.newBuilder() - .setVersion(VERSION) - .setName(ByteString.copyFrom(VALID_NAME)) - .setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED) + .setVersion(ByteString.copyFrom(VERSION)) + .setData(ByteString.copyFrom(VALID_DATA)) .addAllBadgeIds(List.of("TEST3")) .setCommitment(ByteString.copyFrom(commitment)) + .setV1Request(V1_REQUEST) .build(); final int accountsManagerUpdateRetryCount = 2; - AccountsHelper.setupMockUpdateWithRetries(accountsManager, accountsManagerUpdateRetryCount); + setUpMockUpdateWithRetries(accountsManager, accountsManagerUpdateRetryCount); // set up two invocations -- one for each AccountsManager#update try when(account.getBadges()) .thenReturn(List.of(new AccountBadge("TEST3", Instant.ofEpochSecond(41), false))) @@ -415,6 +472,36 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest existingBadges = List.of( + new AccountBadge("TEST1", Instant.ofEpochSecond(41), true), + new AccountBadge("TEST2", Instant.ofEpochSecond(41), true)); + when(account.getBadges()).thenReturn(existingBadges); + + setUpMockUpdateWithRetries(accountsManager, 1); + + authenticatedServiceStub().setProfile(request); + + @SuppressWarnings("unchecked") + final ArgumentCaptor> badgeCaptor = ArgumentCaptor.forClass(List.class); + verify(account).setBadges(refEq(clock), badgeCaptor.capture()); + + assertEquals(List.of( + new AccountBadge("TEST1", Instant.ofEpochSecond(41), false), + new AccountBadge("TEST2", Instant.ofEpochSecond(41), false)), + badgeCaptor.getValue()); + } + @ParameterizedTest @EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"}) void getUnversionedProfile(final IdentityType identityType) throws Exception { @@ -456,28 +543,29 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getUnversionedProfile(request)); + final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request); + assertTrue(response.hasNotFound()); } @ParameterizedTest @@ -514,7 +603,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest profile = Optional.of(new VersionedProfileV1(HexFormat.of().formatHex(requestVersion), name, avatar, emoji, about, paymentAddress, + phoneNumberSharing, new byte[0])); final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder() .setAccountIdentifier(ServiceIdentifier.newBuilder() .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) .build()) - .setVersion(requestVersion) + .setVersion(ByteString.copyFrom(requestVersion)) .build(); - when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion)); + when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v))); when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account)); - when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile)); + when(profilesManager.getV1(any(), any())).thenReturn(profile); final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request); - final GetVersionedProfileResponse.Builder expectedResponseBuilder = GetVersionedProfileResponse.newBuilder() - .setName(ByteString.copyFrom(name)) - .setAbout(ByteString.copyFrom(about)) - .setAboutEmoji(ByteString.copyFrom(emoji)) - .setAvatar(avatar) - .setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing)); + final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder() + .setV1Response(GetVersionedProfileV1Response.newBuilder() + .setName(ByteString.copyFrom(name)) + .setAbout(ByteString.copyFrom(about)) + .setAboutEmoji(ByteString.copyFrom(emoji)) + .setAvatar(avatar) + .setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing)) + .build()); if (expectResponseHasPaymentAddress) { - expectedResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress)); + expectedResultBuilder.setPaymentAddressDataEtag( + DataEtag.newBuilder().setData(ByteString.copyFrom(paymentAddress)) + .setEtag(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress))) + .build()); + } - assertEquals(expectedResponseBuilder.build(), response); + assertTrue(response.hasResult()); + assertEquals(expectedResultBuilder.build(), response.getResult()); } - private static Stream getVersionedProfile() { - return Stream.of( - Arguments.of("version1", "version1", true), - Arguments.of("version1", null, true), - Arguments.of("version1", "version2", false) + private static Collection getVersionedProfile() { + final byte[] version1 = TestRandomUtil.nextBytes(32); + final byte[] version2 = TestRandomUtil.nextBytes(32); + return List.of( + Arguments.argumentSet("current profile version matches", version1, version1, true), + Arguments.argumentSet("current profile version absent",version1, null, true), + Arguments.argumentSet("current profile version mismatch",version1, version2, false) ); } + @Test + void getVersionedProfileV2() { + final byte[] data = TestRandomUtil.nextBytes(128); + final byte[] paymentAddress = TestRandomUtil.nextBytes(582); + final byte[] commitment = TestRandomUtil.nextBytes(97); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + + final UUID targetAci = UUID.randomUUID(); + final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment); + + final Account targetAccount = mock(Account.class); + when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))) + .thenReturn(Optional.of(targetAccount)); + when(targetAccount.getUuid()).thenReturn(targetAci); + when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex)); + when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true); + + when(profilesManager.get(eq(targetAci), aryEq(version))).thenReturn(Optional.of(v2Profile)); + when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty()); + + final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder() + .setAccountIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) + .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci))) + .build()) + .setVersion(ByteString.copyFrom(version)) + .build(); + + final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request); + assertTrue(response.hasResult()); + final GetVersionedProfileResult result = response.getResult(); + + assertTrue(result.hasDataEtag()); + assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData()); + assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtag()); + assertTrue(result.hasPaymentAddressDataEtag()); + assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData()); + assertEquals(ByteString.copyFrom(v2Profile.paymentAddressHash()), result.getPaymentAddressDataEtag().getEtag()); + assertFalse(result.getDataEtagMatched()); + assertFalse(result.getPaymentAddressEtagMatched()); + assertFalse(result.hasV1Response()); + } + + @Test + void getVersionedProfileV2EtagMatched() { + final byte[] data = TestRandomUtil.nextBytes(128); + final byte[] paymentAddress = TestRandomUtil.nextBytes(582); + final byte[] commitment = TestRandomUtil.nextBytes(97); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment); + + final UUID targetAci = UUID.randomUUID(); + final Account targetAccount = mock(Account.class); + when(targetAccount.getUuid()).thenReturn(targetAci); + when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true); + when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(targetAccount)); + + when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex)); + when(profilesManager.get(targetAci, version)).thenReturn(Optional.of(v2Profile)); + when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty()); + + final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder() + .setAccountIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) + .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci))) + .build()) + .setVersion(ByteString.copyFrom(version)) + .setDataEtag(ByteString.copyFrom(v2Profile.dataHash())); + + if (v2Profile.paymentAddressHash() != null) { + builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash())); + } + + final GetVersionedProfileRequest request = builder.build(); + + final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request); + assertTrue(response.hasResult()); + final GetVersionedProfileResult result = response.getResult(); + + assertTrue(result.getDataEtagMatched()); + assertTrue(result.getPaymentAddressEtagMatched()); + assertFalse(result.hasDataEtag()); + assertFalse(result.hasPaymentAddressDataEtag()); + assertFalse(result.hasV1Response()); + } + @ParameterizedTest @MethodSource void getVersionedProfileAccountOrProfileNotFound(final boolean missingAccount, final boolean missingProfile) { @@ -568,12 +754,13 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getVersionedProfile(request)); + final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request); + assertTrue(response.hasNotFound()); } private static Stream getVersionedProfileAccountOrProfileNotFound() { @@ -592,7 +779,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getVersionedProfile(request), accountsManager, profilesManager); @@ -605,155 +792,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getVersionedProfile(request)); } - @Test - void getExpiringProfileKeyCredential() throws InvalidInputException, VerificationFailedException { - final UUID targetUuid = UUID.randomUUID(); - - final ServerSecretParams serverSecretParams = ServerSecretParams.generate(); - final ServerPublicParams serverPublicParams = serverSecretParams.getPublicParams(); - - final ServerZkProfileOperations serverZkProfile = new ServerZkProfileOperations(serverSecretParams); - final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams); - - final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32); - final ProfileKey profileKey = new ProfileKey(profileKeyBytes); - final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid)); - final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext = - clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey); - - when(account.getUuid()).thenReturn(targetUuid); - when(profile.commitment()).thenReturn(profileKeyCommitment.serialize()); - when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account)); - when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile)); - - final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest(); - - final Instant expiration = Instant.now().plus(org.whispersystems.textsecuregcm.util.ProfileHelper.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION) - .truncatedTo(ChronoUnit.DAYS); - - final ExpiringProfileKeyCredentialResponse credentialResponse = - serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration); - - when(serverZkProfileOperations.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration)) - .thenReturn(credentialResponse); - - final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder() - .setAccountIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid))) - .build()) - .setCredentialRequest(ByteString.copyFrom(credentialRequest.serialize())) - .setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) - .setVersion("someVersion") - .build(); - - final GetExpiringProfileKeyCredentialResponse response = authenticatedServiceStub().getExpiringProfileKeyCredential(request); - - assertArrayEquals(credentialResponse.serialize(), response.getProfileKeyCredential().toByteArray()); - - verify(serverZkProfileOperations).issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration); - - final ClientZkProfileOperations clientZkProfileCipher = new ClientZkProfileOperations(serverPublicParams); - assertThatNoException().isThrownBy(() -> - clientZkProfileCipher.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, new ExpiringProfileKeyCredentialResponse(response.getProfileKeyCredential().toByteArray()))); - } - - @Test - void getExpiringProfileKeyCredentialRateLimited() { - final Duration retryAfterDuration = MockUtils.updateRateLimiterResponseToFail( - rateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(5)); - when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account)); - - final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder() - .setAccountIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) - .build()) - .setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8))) - .setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) - .setVersion("someVersion") - .build(); - - assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request), profilesManager); - } - - @ParameterizedTest - @MethodSource - void getExpiringProfileKeyCredentialAccountOrProfileNotFound(final boolean missingAccount, - final boolean missingProfile) { - final UUID targetUuid = UUID.randomUUID(); - - when(account.getUuid()).thenReturn(targetUuid); - when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))) - .thenReturn(missingAccount ? Optional.empty() : Optional.of(account)); - when(profilesManager.get(targetUuid, "someVersion")) - .thenReturn(missingProfile ? Optional.empty() : Optional.of(profile)); - - final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder() - .setAccountIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid))) - .build()) - .setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8))) - .setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) - .setVersion("someVersion") - .build(); - - assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request)); - } - - private static Stream getExpiringProfileKeyCredentialAccountOrProfileNotFound() { - return Stream.of( - Arguments.of(true, false), - Arguments.of(false, true) - ); - } - - @ParameterizedTest - @MethodSource - void getExpiringProfileKeyCredentialInvalidArgument(final IdentityType identityType, final CredentialType credentialType, - final boolean throwZkVerificationException) throws VerificationFailedException { - final UUID targetUuid = UUID.randomUUID(); - - if (throwZkVerificationException) { - when(serverZkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any())).thenThrow(new VerificationFailedException()); - } - - when(account.getUuid()).thenReturn(targetUuid); - when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8)); - when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account)); - when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile)); - - final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder() - .setAccountIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(identityType) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid))) - .build()) - .setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8))) - .setCredentialType(credentialType) - .setVersion("someVersion") - .build(); - - assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request)); - } - - private static Stream getExpiringProfileKeyCredentialInvalidArgument() { - return Stream.of( - // Credential type unspecified - Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, false), - // Illegal identity type - Arguments.of(IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, false), - // Artificially fails zero knowledge verification - Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, true) - ); - } - @Override protected List customizeInterceptors(List serverInterceptors) { return serverInterceptors.stream() @@ -762,4 +806,55 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest !(interceptor instanceof ErrorConformanceInterceptor)) .toList(); } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 16, 32}) + void testProfileSerialized(int aboutEmojiLength) { + + // This test demonstrates the calculation for the (require.size).max = 909 + 28 + // in profiles.proto, as well as how padding calculation results in a constant size. + // + // This should be largely integrated into libsignal in the future. + + // in gRPC, field + varint length encoding has: + // field number: 1 byte per field < number 16 + // varint: 1 byte for length < 128, 2 bytes for < 16,384 + final int serializedSize = + 1 + 257 + 2 + + 1 + 512 + 2 + + 1 + aboutEmojiLength + 1 + + 1 + 64 + 1 + + 1 + 1 + + 1 + (64 - (257 + 512 + aboutEmojiLength + 64 + 1) % 64) + 1; + + assertEquals(909, serializedSize); + + final PlaintextProfileData data = PlaintextProfileData.newBuilder() + .setNameBytes(ByteString.copyFrom(new byte[257])) + .setAboutBytes(ByteString.copyFrom(new byte[512])) + .setAboutEmojiBytes(ByteString.copyFrom(new byte[aboutEmojiLength])) + .setAvatarBytes(ByteString.copyFrom(new byte[64])) + .setPhoneNumberSharing(true) + .setPadding(ByteString.copyFrom(new byte[64 - (257 + 512 + aboutEmojiLength + 64 + 1) % 64])) + .build(); + + assertEquals(serializedSize, data.getSerializedSize()); + } + + static void setUpMockUpdateWithRetries(final AccountsManager accountsManager, final int retryCount) { + try { + when(accountsManager.updateCurrentProfileVersion(any(), any(), any(), any())) + .thenAnswer(a -> { + final Account account = accountsManager.getByAccountIdentifier(a.getArgument(0, UUID.class)).orElseThrow(); + for (int i = 0; i < retryCount; i++) { + //noinspection unchecked + a.getArgument(3, Consumer.class).accept(account); + } + + return account; + }); + } catch (final WriteConflictException e) { + throw new RuntimeException(e); + } + } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java index fa60ba6c5..a8629c55e 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java @@ -16,6 +16,7 @@ import io.grpc.StatusRuntimeException; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; @@ -29,8 +30,11 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; +import org.signal.chat.common.IdentityType; +import org.signal.chat.common.ServiceIdentifier; import org.signal.chat.require.Auth; import org.signal.chat.rpc.Color; import org.signal.chat.rpc.NestedMessage; @@ -43,6 +47,7 @@ import org.signal.chat.rpc.ValidationsRequest; import org.signal.chat.rpc.ValidationsResponse; import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils; import org.whispersystems.textsecuregcm.util.TestRandomUtil; +import org.whispersystems.textsecuregcm.util.UUIDUtil; public class ValidatingInterceptorTest { @@ -122,6 +127,51 @@ public class ValidatingInterceptorTest { .build())); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void serviceIdentifierIdentityTypeFieldValidator(final boolean messagePresent) { + + final ValidationsRequest.Builder builder = builderWithValidDefaults(); + + if (messagePresent) { + builder.setAciServiceIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) + .setUuid(UUIDUtil.toByteString(UUID.randomUUID())) + .build()) + .setPniServiceIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_PNI) + .setUuid(UUIDUtil.toByteString(UUID.randomUUID())) + .build()); + } else { + builder.clearAciServiceIdentifier() + .clearPniServiceIdentifier(); + } + + assertDoesNotThrow(() -> stub.validationsEndpoint(builder.build())); + } + + @ParameterizedTest + @EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_UNSPECIFIED", "IDENTITY_TYPE_PNI"}) + public void testServiceIdentifierIdentityTypeAciValidationFailure(final IdentityType identityType) { + + assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults() + .setAciServiceIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(identityType) + .setUuid(UUIDUtil.toByteString(UUID.randomUUID()))) + .build())); + } + + @ParameterizedTest + @EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_UNSPECIFIED", "IDENTITY_TYPE_ACI"}) + public void testServiceIdentifierIdentityTypePniValidationFailure(final IdentityType identityType) { + + assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults() + .setPniServiceIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(identityType) + .setUuid(UUIDUtil.toByteString(UUID.randomUUID()))) + .build())); + } + @ParameterizedTest @ValueSource(ints = {0, 1, 2, 3, 4, 6, 1000}) public void testExactlySizeValidationFailure(final int size) throws Exception { @@ -470,7 +520,15 @@ public class ValidatingInterceptorTest { .setNested(NestedMessage.getDefaultInstance()) .addRepeatedNested(NestedMessage.getDefaultInstance()) .putMapNested("test", NestedMessage.getDefaultInstance()) - .setBase64Url("123aBc_-"); + .setBase64Url("123aBc_-") + .setAciServiceIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) + .setUuid(UUIDUtil.toByteString(UUID.randomUUID())) + .build()) + .setPniServiceIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(IdentityType.IDENTITY_TYPE_PNI) + .setUuid(UUIDUtil.toByteString(UUID.randomUUID())) + .build()); } private static void assertStatusException(final Status expected, final Executable serviceCall) { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java index 42a4d5900..e33bb75a4 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java @@ -44,9 +44,12 @@ import java.security.InvalidKeyException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.Arrays; import java.util.Base64; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; @@ -1446,6 +1449,48 @@ class AccountsManagerTest { ); } + @ParameterizedTest + @MethodSource + void updateCurrentProfileVersion(final byte[] currentVersion, final byte[] expectedVersion, final byte[] newVersion, final boolean expectException) throws Exception { + final Account account = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); + final UUID accountIdentifier = account.getIdentifier(IdentityType.ACI); + addRetrievableAccount(account); + + account.setCurrentProfileVersion(HexFormat.of().formatHex(currentVersion)); + + final AccountBadge badge = new AccountBadge("test", CLOCK.instant().plusSeconds(60), true); + + assertTrue(account.getBadges().isEmpty()); + + if (expectException) { + assertThrows(WriteConflictException.class, () -> accountsManager.updateCurrentProfileVersion(accountIdentifier, newVersion, HexFormat.of().formatHex(expectedVersion), _ -> {})); + } else { + final Account updatedAccount = accountsManager.updateCurrentProfileVersion(accountIdentifier, newVersion, + HexFormat.of().formatHex(expectedVersion), a -> { + + a.setBadges(CLOCK, new ArrayList<>(List.of(badge))); + }); + + assertArrayEquals(newVersion, HexFormat.of().parseHex(updatedAccount.getCurrentProfileVersion().orElseThrow())); + assertEquals(List.of(badge), updatedAccount.getBadges()); + } + } + + static Collection updateCurrentProfileVersion() { + + final byte[] empty = new byte[0]; + final byte[] version1 = TestRandomUtil.nextBytes(16); + final byte[] version2 = Arrays.copyOf(version1, version1.length); + version2[0] = (byte) (version2[0] + 1); + + return List.of( + Arguments.argumentSet("no current version - matches", empty, empty, version1, false), + Arguments.argumentSet("no current version - conflict", empty, version1, version1, true), + Arguments.argumentSet("current version - empty conflict", version1, empty, version2, true), + Arguments.argumentSet("current version - matches", version1, version1, version2, false) + ); + } + private void addRetrievableAccount(final Account account) { when(accounts.getByAccountIdentifier(account.getIdentifier(IdentityType.ACI))) .thenReturn(Optional.of(account)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java index ac171007a..d4432ffe5 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java @@ -258,6 +258,20 @@ public final class DynamoDbExtensionSchema { .build()), List.of(), List.of()), + PROFILES_V2("profiles_v2_test", + ProfilesV2.KEY_ACCOUNT_UUID, + ProfilesV2.KEY_VERSION, + List.of( + AttributeDefinition.builder() + .attributeName(ProfilesV2.KEY_ACCOUNT_UUID) + .attributeType(ScalarAttributeType.B) + .build(), + AttributeDefinition.builder() + .attributeName(ProfilesV2.KEY_VERSION) + .attributeType(ScalarAttributeType.B) + .build()), + List.of(), List.of()), + PUSH_CHALLENGES("push_challenge_test", PushChallengeDynamoDb.KEY_ACCOUNT_UUID, null, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java index 5aade8083..f5e02c3a3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java @@ -7,11 +7,13 @@ package org.whispersystems.textsecuregcm.storage; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -22,238 +24,203 @@ import static org.mockito.Mockito.when; import io.lettuce.core.RedisException; import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands; import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands; +import java.util.Arrays; +import java.util.Collection; +import java.util.HexFormat; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; +import javax.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.signal.libsignal.protocol.ServiceId; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.profiles.ProfileKey; +import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; +import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper; +import org.whispersystems.textsecuregcm.util.SystemMapper; import org.whispersystems.textsecuregcm.util.TestRandomUtil; +import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; @Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) public class ProfilesManagerTest { - private Profiles profiles; - private RedisAdvancedClusterCommands binaryCommands; - private RedisAdvancedClusterAsyncCommands binaryAsyncCommands; + private Profiles profilesV1; + private ProfilesV2 profilesV2; + private RedisAdvancedClusterCommands commands; + private RedisAdvancedClusterAsyncCommands asyncCommands; private S3AsyncClient s3Client; + private ClusterLuaScript setLuaScript; private ProfilesManager profilesManager; private static final String BUCKET = "bucket"; @BeforeEach - void setUp() { + void setUp() throws Exception { //noinspection unchecked - binaryCommands = mock(RedisAdvancedClusterCommands.class); + commands = mock(RedisAdvancedClusterCommands.class); //noinspection unchecked - binaryAsyncCommands = mock(RedisAdvancedClusterAsyncCommands.class); + asyncCommands = mock(RedisAdvancedClusterAsyncCommands.class); final FaultTolerantRedisClusterClient cacheCluster = RedisClusterHelper.builder() - .binaryCommands(binaryCommands) - .binaryAsyncCommands(binaryAsyncCommands) + .binaryCommands(commands) + .binaryAsyncCommands(asyncCommands) .build(); - profiles = mock(Profiles.class); + profilesV1 = mock(Profiles.class); + profilesV2 = mock(ProfilesV2.class); s3Client = mock(S3AsyncClient.class); + setLuaScript = mock(ClusterLuaScript.class); - profilesManager = new ProfilesManager(profiles, cacheCluster, mock(ScheduledExecutorService.class), s3Client, BUCKET); + profilesManager = new ProfilesManager(profilesV1, profilesV2, cacheCluster, mock(ScheduledExecutorService.class), + s3Client, BUCKET, setLuaScript); } @Test - public void testGetProfileInCache() throws InvalidInputException { + public void testGetV1ProfileInCache() throws InvalidInputException { final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); final byte[] name = TestRandomUtil.nextBytes(81); final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize(); - when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))) + when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()))) .thenReturn(String.format( - "{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}", + "{\"version\": \"%s\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}", + versionHex, ProfileTestHelper.encodeToBase64(name), ProfileTestHelper.encodeToBase64(commitment)).getBytes()); - Optional profile = profilesManager.get(uuid, "someversion"); + Optional profile = profilesManager.getV1(uuid, versionHex); assertTrue(profile.isPresent()); assertArrayEquals(profile.get().name(), name); assertEquals("someavatar", profile.get().avatar()); assertArrayEquals(profile.get().commitment(), commitment); - verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())); - verifyNoMoreInteractions(binaryCommands); - verifyNoMoreInteractions(profiles); + verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes())); + verifyNoMoreInteractions(commands); + verifyNoMoreInteractions(profilesV1); } @Test - public void testGetProfileAsyncInCache() throws InvalidInputException { + public void testGetV1ProfileNotInCache() throws Exception { final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); final byte[] name = TestRandomUtil.nextBytes(81); - final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize(); - - when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))) - .thenReturn(MockRedisFuture.completedFuture(String.format("{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}", - ProfileTestHelper.encodeToBase64(name), - ProfileTestHelper.encodeToBase64(commitment)).getBytes())); - - Optional profile = profilesManager.getAsync(uuid, "someversion").join(); - - assertTrue(profile.isPresent()); - assertArrayEquals(profile.get().name(), name); - assertEquals("someavatar", profile.get().avatar()); - assertArrayEquals(profile.get().commitment(), commitment); - - verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())); - verifyNoMoreInteractions(binaryAsyncCommands); - verifyNoMoreInteractions(profiles); - } - - @Test - public void testGetProfileNotInCache() { - final UUID uuid = UUID.randomUUID(); - final byte[] name = TestRandomUtil.nextBytes(81); - final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, + final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null, null, null, "somecommitment".getBytes()); - when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))).thenReturn(null); - when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile)); + when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes()))).thenReturn(null); + when(profilesV1.get(eq(uuid), eq(versionHex))).thenReturn(Optional.of(profile)); - Optional retrieved = profilesManager.get(uuid, "someversion"); + Optional retrieved = profilesManager.getV1(uuid, versionHex); assertTrue(retrieved.isPresent()); - assertSame(retrieved.get(), profile); + assertEquals(retrieved.get(), profile); - verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())); - verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class)); - verifyNoMoreInteractions(binaryCommands); + final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile); - verify(profiles, times(1)).get(eq(uuid), eq("someversion")); - verifyNoMoreInteractions(profiles); - } + verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes())); + verify(setLuaScript, times(1)).executeBinary( + argThat(keys -> + Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid)) + && Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))), + argThat(args -> + Arrays.equals(args.get(0), versionHex.getBytes()) + && Arrays.equals(args.get(1), v1ProfileBytes) + && args.get(2).length == 0)); - @Test - public void testGetProfileAsyncNotInCache() { - final UUID uuid = UUID.randomUUID(); - final byte[] name = TestRandomUtil.nextBytes(81); - final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, - null, null, "somecommitment".getBytes()); + verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes())); + verifyNoMoreInteractions(commands); + verifyNoMoreInteractions(setLuaScript); - when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()))).thenReturn(MockRedisFuture.completedFuture(null)); - when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class))).thenReturn(MockRedisFuture.completedFuture(null)); - when(profiles.getAsync(eq(uuid), eq("someversion"))).thenReturn(CompletableFuture.completedFuture(Optional.of(profile))); - - Optional retrieved = profilesManager.getAsync(uuid, "someversion").join(); - - assertTrue(retrieved.isPresent()); - assertSame(retrieved.get(), profile); - - verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes())); - verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class)); - verifyNoMoreInteractions(binaryAsyncCommands); - - verify(profiles, times(1)).getAsync(eq(uuid), eq("someversion")); - verifyNoMoreInteractions(profiles); + verify(profilesV1, times(1)).get(eq(uuid), eq(versionHex)); + verifyNoMoreInteractions(profilesV1); } @ParameterizedTest @ValueSource(booleans = {true, false}) - public void testGetProfileBrokenCache(final boolean failUpdateCache) { + public void testGetV1ProfileBrokenCache(final boolean failUpdateCache) { final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); final byte[] name = TestRandomUtil.nextBytes(81); - final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, + final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null, null, null, "somecommitment".getBytes()); - when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))).thenThrow(new RedisException("Connection lost")); + when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()))).thenThrow(new RedisException("Connection lost")); if (failUpdateCache) { - when(binaryCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class))) + when(commands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()), any(byte[].class))) .thenThrow(new RedisException("Connection lost")); } - when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile)); + when(profilesV1.get(eq(uuid), eq(versionHex))).thenReturn(Optional.of(profile)); - Optional retrieved = profilesManager.get(uuid, "someversion"); + Optional retrieved = profilesManager.getV1(uuid, versionHex); assertTrue(retrieved.isPresent()); - assertSame(retrieved.get(), profile); + assertEquals(retrieved.get(), profile); - verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())); - verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class)); - verifyNoMoreInteractions(binaryCommands); + verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes())); + verify(setLuaScript, times(1)).executeBinary( + argThat(keys -> + Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid)) + && Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))), + argThat(args -> + Arrays.equals(args.get(0), versionHex.getBytes()) + && args.get(1).length > 0 + && args.get(2).length == 0)); + verifyNoMoreInteractions(commands); + verifyNoMoreInteractions(setLuaScript); - verify(profiles, times(1)).get(eq(uuid), eq("someversion")); - verifyNoMoreInteractions(profiles); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testGetProfileAsyncBrokenCache(final boolean failUpdateCache) { - final UUID uuid = UUID.randomUUID(); - final byte[] name = TestRandomUtil.nextBytes(81); - final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, - null, null, "somecommitment".getBytes()); - - when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()))).thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost"))); - when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class))) - .thenReturn(failUpdateCache - ? MockRedisFuture.failedFuture(new RedisException("Connection lost")) - : MockRedisFuture.completedFuture(null)); - when(profiles.getAsync(eq(uuid), eq("someversion"))).thenReturn(CompletableFuture.completedFuture(Optional.of(profile))); - - Optional retrieved = profilesManager.getAsync(uuid, "someversion").join(); - - assertTrue(retrieved.isPresent()); - assertSame(retrieved.get(), profile); - - verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes())); - verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class)); - verifyNoMoreInteractions(binaryAsyncCommands); - - verify(profiles, times(1)).getAsync(eq(uuid), eq("someversion")); - verifyNoMoreInteractions(profiles); + verify(profilesV1, times(1)).get(eq(uuid), eq(versionHex)); + verifyNoMoreInteractions(profilesV1); } @Test - public void testSet() { + public void testSetV1() throws Exception { final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); final byte[] name = TestRandomUtil.nextBytes(81); - final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, + final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null, null, null, "somecommitment".getBytes()); - profilesManager.set(uuid, profile); + profilesManager.setV1(uuid, profile); - verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class)); - verifyNoMoreInteractions(binaryCommands); + final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile); - verify(profiles, times(1)).set(eq(uuid), eq(profile)); - verifyNoMoreInteractions(profiles); - } + verify(setLuaScript, times(1)).executeBinary( + argThat(keys -> + Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid)) + && Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))), + argThat(args -> + Arrays.equals(args.get(0), versionHex.getBytes()) + && Arrays.equals(args.get(1), v1ProfileBytes) + && args.get(2).length == 0 + && args.get(3).length == 0)); + verifyNoMoreInteractions(setLuaScript); - @Test - public void testSetAsync() { - final UUID uuid = UUID.randomUUID(); - final byte[] name = TestRandomUtil.nextBytes(81); - final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, - null, null, "somecommitment".getBytes()); - - when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class))).thenReturn(MockRedisFuture.completedFuture(null)); - when(profiles.setAsync(eq(uuid), eq(profile))).thenReturn(CompletableFuture.completedFuture(null)); - - profilesManager.setAsync(uuid, profile).join(); - - verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any()); - verifyNoMoreInteractions(binaryAsyncCommands); - - verify(profiles, times(1)).setAsync(eq(uuid), eq(profile)); - verifyNoMoreInteractions(profiles); + verify(profilesV1, times(1)).set(eq(uuid), eq(profile)); + verifyNoMoreInteractions(profilesV1); + verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid))); + verify(profilesV2).deleteAll(uuid); } @ParameterizedTest @@ -263,16 +230,18 @@ public class ProfilesManagerTest { final String avatarOne = "avatar1"; final String avatarTwo = "avatar2"; - when(profiles.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(List.of(avatarOne, avatarTwo))); - when(binaryAsyncCommands.del(ProfilesManager.getCacheKeyV1(uuid))).thenReturn(MockRedisFuture.completedFuture(null)); + when(profilesV1.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(List.of(avatarOne, avatarTwo))); + when(profilesV2.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(null)); + when(asyncCommands.del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid))).thenReturn(MockRedisFuture.completedFuture(null)); when(s3Client.deleteObject(any(DeleteObjectRequest.class))) .thenReturn(CompletableFuture.completedFuture(null)) .thenReturn(CompletableFuture.failedFuture(new RuntimeException("some error"))); profilesManager.deleteAll(uuid, includeAvatar).join(); - verify(profiles).deleteAll(uuid); - verify(binaryAsyncCommands).del(ProfilesManager.getCacheKeyV1(uuid)); + verify(profilesV1).deleteAll(uuid); + verify(profilesV2).deleteAll(uuid); + verify(asyncCommands).del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid)); if (includeAvatar) { verify(s3Client).deleteObject(DeleteObjectRequest.builder() .bucket(BUCKET) @@ -286,4 +255,257 @@ public class ProfilesManagerTest { verifyNoInteractions(s3Client); } } + + @Test + public void testGetProfileInCache() { + final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final byte[] data = TestRandomUtil.nextBytes(128); + final byte[] dataHash = TestRandomUtil.nextBytes(32); + final byte[] commitment = TestRandomUtil.nextBytes(32); + final byte[] paymentAddress = TestRandomUtil.nextBytes(64); + final byte[] paymentAddressHash = TestRandomUtil.nextBytes(32); + + when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenReturn(String.format( + """ + { + "version":"%s", + "data":"%s", + "dataHash":"%s", + "paymentAddress":"%s", + "paymentAddressHash":"%s", + "commitment":"%s" + } + """, + ProfileTestHelper.encodeToBase64(version), + ProfileTestHelper.encodeToBase64(data), + ProfileTestHelper.encodeToBase64(dataHash), + ProfileTestHelper.encodeToBase64(paymentAddress), + ProfileTestHelper.encodeToBase64(paymentAddressHash), + ProfileTestHelper.encodeToBase64(commitment)).getBytes()); + + Optional profile = profilesManager.get(uuid, version); + + assertTrue(profile.isPresent()); + assertArrayEquals(profile.get().data(), data); + assertArrayEquals(profile.get().dataHash(), dataHash); + assertArrayEquals(profile.get().commitment(), commitment); + assertArrayEquals(profile.get().paymentAddress(), paymentAddress); + assertArrayEquals(profile.get().paymentAddressHash(), paymentAddressHash); + + verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version)); + verifyNoMoreInteractions(commands); + verifyNoMoreInteractions(profilesV2); + } + + @Test + public void testGetProfileNotInCache() throws Exception { + final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final VersionedProfile profile = new VersionedProfile(version, TestRandomUtil.nextBytes(128), + TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64), + TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32)); + + when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenReturn(null); + when(profilesV2.get(eq(uuid), aryEq(version))).thenReturn(Optional.of(profile)); + + final Optional retrieved = profilesManager.get(uuid, version); + + assertTrue(retrieved.isPresent()); + assertEquals(retrieved.get(), profile); + + final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile); + + verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version)); + verify(setLuaScript, times(1)).executeBinary( + argThat(keys -> + Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid)) + && Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))), + argThat(args -> + args.get(0).length == 0 + && args.get(1).length == 0 + && Arrays.equals(args.get(2), version) + && Arrays.equals(args.get(3), v2ProfileBytes))); + verifyNoMoreInteractions(commands); + + verify(profilesV2, times(1)).get(eq(uuid), aryEq(version)); + verifyNoMoreInteractions(profilesV2); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void testGetProfileBrokenCache(final boolean failUpdateCache) throws Exception { + final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final VersionedProfile profile = new VersionedProfile(version, TestRandomUtil.nextBytes(128), + TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64), + TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32)); + + when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenThrow(new RedisException("Connection lost")); + if (failUpdateCache) { + when(commands.hset(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version), any(byte[].class))) + .thenThrow(new RedisException("Connection lost")); + } + when(profilesV2.get(eq(uuid), aryEq(version))).thenReturn(Optional.of(profile)); + + final Optional retrieved = profilesManager.get(uuid, version); + + assertTrue(retrieved.isPresent()); + assertEquals(retrieved.get(), profile); + + final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile); + + verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version)); + verify(setLuaScript, times(1)).executeBinary( + argThat(keys -> + Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid)) + && Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))), + argThat(args -> + args.get(0).length == 0 + && args.get(1).length == 0 + && Arrays.equals(args.get(2), version) + && Arrays.equals(args.get(3), v2ProfileBytes))); verifyNoMoreInteractions(commands); + + verify(profilesV2, times(1)).get(eq(uuid), aryEq(version)); + verifyNoMoreInteractions(profilesV2); + } + + @Test + public void testSet() throws Exception { + final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + + final byte[] name = TestRandomUtil.nextBytes(81); + final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize(); + final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment); + + final byte[] expectedCurrentDataHash = TestRandomUtil.nextBytes(32); + final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128), + TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64), + TestRandomUtil.nextBytes(32), commitment); + + final TransactWriteItem v1Item = TransactWriteItem.builder().build(); + when(profilesV1.getTransactWriteItem(eq(uuid), eq(profileV1))).thenReturn(v1Item); + + profilesManager.set(uuid, profileV1, profileV2, expectedCurrentDataHash); + + final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profileV1); + final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profileV2); + + verify(setLuaScript, times(1)).executeBinary( + argThat(keys -> + Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid)) + && Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))), + argThat(args -> + Arrays.equals(args.get(0), versionHex.getBytes()) + && Arrays.equals(args.get(1), v1ProfileBytes) + && Arrays.equals(args.get(2), version) + && Arrays.equals(args.get(3), v2ProfileBytes))); + verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid))); + verifyNoMoreInteractions(commands); + verifyNoMoreInteractions(setLuaScript); + + verify(profilesV1).getTransactWriteItem(eq(uuid), eq(profileV1)); + verifyNoMoreInteractions(profilesV1); + + verify(profilesV2).set(eq(uuid), aryEq(version), aryEq(profileV2.data()), aryEq(profileV2.dataHash()), aryEq(profileV2.commitment()), aryEq(profileV2.paymentAddress()), aryEq(profileV2.paymentAddressHash()), aryEq(expectedCurrentDataHash), eq(v1Item)); + verifyNoMoreInteractions(profilesV2); + } + + @ParameterizedTest + @MethodSource + public void testSetExceptionCleansUpCache(final Class exceptionClass) throws WriteConflictException, InvalidInputException { + final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + + final byte[] name = TestRandomUtil.nextBytes(81); + final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize(); + final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment); + + final byte[] wrongHash = TestRandomUtil.nextBytes(32); + final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128), + TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64), + TestRandomUtil.nextBytes(32), commitment); + + final TransactWriteItem v1Item = TransactWriteItem.builder().build(); + when(profilesV1.getTransactWriteItem(eq(uuid), eq(profileV1))).thenReturn(v1Item); + + when(asyncCommands.del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid))).thenReturn(MockRedisFuture.completedFuture(null)); + + doThrow(exceptionClass).when(profilesV2).set(eq(uuid), aryEq(version), aryEq(profileV2.data()), aryEq(profileV2.dataHash()), aryEq(profileV2.commitment()), + aryEq(profileV2.paymentAddress()), aryEq(profileV2.paymentAddressHash()), aryEq(wrongHash), eq(v1Item)); + + assertThrows(exceptionClass, () -> profilesManager.set(uuid, profileV1, profileV2, wrongHash)); + + verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid))); + } + + static Collection testSetExceptionCleansUpCache() { + return List.of( + Arguments.of(WriteConflictException.class), + Arguments.of(DynamoDbException.class) + ); + } + + @Nested + class Redis { + + @RegisterExtension + private static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); + + @BeforeEach + void setUp() throws Exception { + profilesManager = new ProfilesManager(profilesV1, profilesV2, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class), + s3Client, BUCKET); + } + + @ParameterizedTest + @MethodSource + void testSetGet(@Nullable final VersionedProfileV1 v1Profile, @Nullable final VersionedProfile v2Profile) { + + final UUID uuid = UUID.randomUUID(); + + profilesManager.redisSet(uuid, v2Profile, v1Profile); + + if (v1Profile != null) { + + final Optional v1Actual = profilesManager.getV1(uuid, v1Profile.version()); + + assertTrue(v1Actual.isPresent()); + assertEquals(v1Profile, v1Actual.get()); + } + + if (v2Profile != null) { + final Optional v2Actual = profilesManager.get(uuid, v2Profile.version()); + + assertTrue(v2Actual.isPresent()); + assertEquals(v2Profile, v2Actual.get()); + } + + } + + static Collection testSetGet() throws Exception { + final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final String versionHex = HexFormat.of().formatHex(version); + + final byte[] name = TestRandomUtil.nextBytes(81); + final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize(); + final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment); + + final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128), + TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64), + TestRandomUtil.nextBytes(32), commitment); + + return List.of( + Arguments.argumentSet("only v1", profileV1, null), + Arguments.argumentSet("only v2", null, profileV2), + Arguments.argumentSet("both", profileV1, profileV2) + ); + } + } + } + diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java index cce145cbf..1c0fe8b80 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java @@ -28,6 +28,7 @@ import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; import org.whispersystems.textsecuregcm.util.AttributeValues; import org.whispersystems.textsecuregcm.util.TestRandomUtil; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; @Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) public class ProfilesTest { @@ -36,7 +37,7 @@ public class ProfilesTest { static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.PROFILES); private Profiles profiles; - private VersionedProfile validProfile; + private VersionedProfileV1 validProfile; @BeforeEach void setUp() throws InvalidInputException { @@ -51,28 +52,14 @@ public class ProfilesTest { final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16); final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29); - validProfile = new VersionedProfile(version, name, avatar, validAboutEmoji, validAbout, null, phoneNumberSharing, commitment); + validProfile = new VersionedProfileV1(version, name, avatar, validAboutEmoji, validAbout, null, phoneNumberSharing, commitment); } @Test void testSetGet() { profiles.set(ACI, validProfile); - Optional retrieved = profiles.get(ACI, validProfile.version()); - - assertThat(retrieved.isPresent()).isTrue(); - assertThat(retrieved.get().name()).isEqualTo(validProfile.name()); - assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar()); - assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment()); - assertThat(retrieved.get().about()).isEqualTo(validProfile.about()); - assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji()); - } - - @Test - void testSetGetAsync() { - profiles.setAsync(ACI, validProfile).join(); - - Optional retrieved = profiles.getAsync(ACI, validProfile.version()).join(); + Optional retrieved = profiles.get(ACI, validProfile.version()); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get().name()).isEqualTo(validProfile.name()); @@ -97,12 +84,12 @@ public class ProfilesTest { final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29); final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); - VersionedProfile updatedProfile = new VersionedProfile(version, name, differentAvatar, + VersionedProfileV1 updatedProfile = new VersionedProfileV1(version, name, differentAvatar, differentEmoji, differentAbout, paymentAddress, phoneNumberSharing, commitment); profiles.set(ACI, updatedProfile); - Optional retrieved = profiles.get(ACI, version); + Optional retrieved = profiles.get(ACI, version); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get().name()).isEqualTo(updatedProfile.name()); @@ -118,11 +105,11 @@ public class ProfilesTest { final byte[] name = TestRandomUtil.nextBytes(81); final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); - VersionedProfile profile = new VersionedProfile(version, name, null, null, null, null, null, + VersionedProfileV1 profile = new VersionedProfileV1(version, name, null, null, null, null, null, commitment); profiles.set(ACI, profile); - Optional retrieved = profiles.get(ACI, version); + Optional retrieved = profiles.get(ACI, version); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get().name()).isEqualTo(profile.name()); @@ -136,7 +123,7 @@ public class ProfilesTest { void testSetReplace() throws InvalidInputException { profiles.set(ACI, validProfile); - Optional retrieved = profiles.get(ACI, validProfile.version()); + Optional retrieved = profiles.get(ACI, validProfile.version()); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get().name()).isEqualTo(validProfile.name()); @@ -153,7 +140,7 @@ public class ProfilesTest { final byte[] differentPhoneNumberSharing = TestRandomUtil.nextBytes(29); final byte[] differentCommitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); - VersionedProfile updated = new VersionedProfile(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null, + VersionedProfileV1 updated = new VersionedProfileV1(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null, differentPhoneNumberSharing, differentCommitment); profiles.set(ACI, updated); @@ -187,14 +174,14 @@ public class ProfilesTest { final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); - VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null, + VersionedProfileV1 profileOne = new VersionedProfileV1(versionOne, nameOne, avatarOne, null, null, null, null, commitmentOne); - VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo); + VersionedProfileV1 profileTwo = new VersionedProfileV1(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo); profiles.set(ACI, profileOne); profiles.set(ACI, profileTwo); - Optional retrieved = profiles.get(ACI, versionOne); + Optional retrieved = profiles.get(ACI, versionOne); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get().name()).isEqualTo(profileOne.name()); @@ -218,7 +205,7 @@ public class ProfilesTest { profiles.set(ACI, validProfile); final String missingVersion = "missingVersion"; - Optional retrieved = profiles.get(ACI, missingVersion); + Optional retrieved = profiles.get(ACI, missingVersion); assertThat(retrieved.isPresent()).isFalse(); } @@ -242,10 +229,10 @@ public class ProfilesTest { final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); final byte[] commitmentThree = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); - VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null, + VersionedProfileV1 profileOne = new VersionedProfileV1(versionOne, nameOne, avatarOne, null, null, null, null, commitmentOne); - VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo); - VersionedProfile profileThree = new VersionedProfile(versionThree, nameTwo, null, aboutEmoji, about, null, null, + VersionedProfileV1 profileTwo = new VersionedProfileV1(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo); + VersionedProfileV1 profileThree = new VersionedProfileV1(versionThree, nameTwo, null, aboutEmoji, about, null, null, commitmentThree); profiles.set(ACI, profileOne); @@ -255,7 +242,7 @@ public class ProfilesTest { final List avatars = profiles.deleteAll(ACI).join(); for (String version : List.of(versionOne, versionTwo, versionThree)) { - final Optional retrieved = profiles.get(ACI, version); + final Optional retrieved = profiles.get(ACI, version); assertThat(retrieved.isPresent()).isFalse(); } @@ -263,9 +250,23 @@ public class ProfilesTest { assertThat(avatars.containsAll(List.of(avatarOne, avatarTwo))).isTrue(); } + @Test + void testGetTransactWriteItem() { + final TransactWriteItem transactWriteItem = profiles.getTransactWriteItem(ACI, validProfile); + + assertThat(transactWriteItem).isNotNull() + .extracting(TransactWriteItem::update).isNotNull(); + + assertThat(transactWriteItem.update().tableName()).isEqualTo(Tables.PROFILES.tableName()); + assertThat(transactWriteItem.update().key()).isNotNull(); + assertThat(transactWriteItem.update().updateExpression()).isEqualTo(Profiles.buildUpdateExpression(validProfile)); + assertThat(transactWriteItem.update().expressionAttributeValues()) + .isEqualTo(Profiles.buildUpdateExpressionAttributeValues(validProfile)); + } + @ParameterizedTest @MethodSource - void buildUpdateExpression(final VersionedProfile profile, final String expectedUpdateExpression) { + void buildUpdateExpression(final VersionedProfileV1 profile, final String expectedUpdateExpression) { assertEquals(expectedUpdateExpression, Profiles.buildUpdateExpression(profile)); } @@ -281,38 +282,38 @@ public class ProfilesTest { return Stream.of( Arguments.of( - new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment), + new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment), "SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji, #paymentAddress = :paymentAddress, #phoneNumberSharing = :phoneNumberSharing"), Arguments.of( - new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, null, commitment), + new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, null, commitment), "SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji, #paymentAddress = :paymentAddress REMOVE #phoneNumberSharing"), Arguments.of( - new VersionedProfile(version, name, avatar, emoji, about, null, null, commitment), + new VersionedProfileV1(version, name, avatar, emoji, about, null, null, commitment), "SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji REMOVE #paymentAddress, #phoneNumberSharing"), Arguments.of( - new VersionedProfile(version, name, avatar, emoji, null, null, null, commitment), + new VersionedProfileV1(version, name, avatar, emoji, null, null, null, commitment), "SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #aboutEmoji = :aboutEmoji REMOVE #about, #paymentAddress, #phoneNumberSharing"), Arguments.of( - new VersionedProfile(version, name, avatar, null, null, null, null, commitment), + new VersionedProfileV1(version, name, avatar, null, null, null, null, commitment), "SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar REMOVE #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing"), Arguments.of( - new VersionedProfile(version, name, null, null, null, null, null, commitment), + new VersionedProfileV1(version, name, null, null, null, null, null, commitment), "SET #commitment = if_not_exists(#commitment, :commitment), #name = :name REMOVE #avatar, #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing"), Arguments.of( - new VersionedProfile(version, null, null, null, null, null, null, commitment), + new VersionedProfileV1(version, null, null, null, null, null, null, commitment), "SET #commitment = if_not_exists(#commitment, :commitment) REMOVE #name, #avatar, #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing") ); } @ParameterizedTest @MethodSource - void buildUpdateExpressionAttributeValues(final VersionedProfile profile, final Map expectedAttributeValues) { + void buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile, final Map expectedAttributeValues) { assertEquals(expectedAttributeValues, Profiles.buildUpdateExpressionAttributeValues(profile)); } @@ -328,7 +329,7 @@ public class ProfilesTest { return Stream.of( Arguments.of( - new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment), + new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment), Map.of( ":commitment", AttributeValues.fromByteArray(commitment), ":name", AttributeValues.fromByteArray(name), @@ -339,7 +340,7 @@ public class ProfilesTest { ":phoneNumberSharing", AttributeValues.fromByteArray(phoneNumberSharing))), Arguments.of( - new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, null, commitment), + new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, null, commitment), Map.of( ":commitment", AttributeValues.fromByteArray(commitment), ":name", AttributeValues.fromByteArray(name), @@ -349,7 +350,7 @@ public class ProfilesTest { ":paymentAddress", AttributeValues.fromByteArray(paymentAddress))), Arguments.of( - new VersionedProfile(version, name, avatar, emoji, about, null, null, commitment), + new VersionedProfileV1(version, name, avatar, emoji, about, null, null, commitment), Map.of( ":commitment", AttributeValues.fromByteArray(commitment), ":name", AttributeValues.fromByteArray(name), @@ -358,7 +359,7 @@ public class ProfilesTest { ":about", AttributeValues.fromByteArray(about))), Arguments.of( - new VersionedProfile(version, name, avatar, emoji, null, null, null, commitment), + new VersionedProfileV1(version, name, avatar, emoji, null, null, null, commitment), Map.of( ":commitment", AttributeValues.fromByteArray(commitment), ":name",AttributeValues.fromByteArray(name), @@ -366,20 +367,20 @@ public class ProfilesTest { ":aboutEmoji", AttributeValues.fromByteArray(emoji))), Arguments.of( - new VersionedProfile(version, name, avatar, null, null, null, null, commitment), + new VersionedProfileV1(version, name, avatar, null, null, null, null, commitment), Map.of( ":commitment", AttributeValues.fromByteArray(commitment), ":name", AttributeValues.fromByteArray(name), ":avatar", AttributeValues.fromString(avatar))), Arguments.of( - new VersionedProfile(version, name, null, null, null, null, null, commitment), + new VersionedProfileV1(version, name, null, null, null, null, null, commitment), Map.of( ":commitment", AttributeValues.fromByteArray(commitment), ":name", AttributeValues.fromByteArray(name))), Arguments.of( - new VersionedProfile(version, null, null, null, null, null, null, commitment), + new VersionedProfileV1(version, null, null, null, null, null, null, commitment), Map.of(":commitment", AttributeValues.fromByteArray(commitment))) ); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesV2Test.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesV2Test.java new file mode 100644 index 000000000..0b8310ebe --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesV2Test.java @@ -0,0 +1,467 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junitpioneer.jupiter.cartesian.CartesianTest; +import org.signal.libsignal.protocol.ServiceId; +import org.signal.libsignal.zkgroup.InvalidInputException; +import org.signal.libsignal.zkgroup.profiles.ProfileKey; +import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables; +import org.whispersystems.textsecuregcm.util.AttributeValues; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; +import software.amazon.awssdk.core.SdkBytes; +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.TransactWriteItem; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; +import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; + +@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) +public class ProfilesV2Test { + private static final UUID ACI = UUID.randomUUID(); + + @RegisterExtension + static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.PROFILES_V2); + + private ProfilesV2 profilesV2; + private byte[] version; + private byte[] data; + private byte[] commitment; + private byte[] paymentAddress; + + private VersionedProfile profile; + + @BeforeEach + void setUp() throws InvalidInputException { + profilesV2 = new ProfilesV2(DYNAMO_DB_EXTENSION.getDynamoDbClient(), + DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + Tables.PROFILES_V2.tableName()); + + commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(ACI)).serialize(); + version = TestRandomUtil.nextBytes(32); + data = TestRandomUtil.nextBytes(256); + paymentAddress = TestRandomUtil.nextBytes(582); + + profile = new VersionedProfile(version, data, paymentAddress, commitment); + } + + /// Generates a no-op transaction write item for tests that don’t need a real one + private TransactWriteItem getAdditionalTransactWriteItem() { + return TransactWriteItem.builder() + .conditionCheck(builder -> builder + .tableName(Tables.PROFILES_V2.tableName()) + .key(Map.of( + ProfilesV2.KEY_ACCOUNT_UUID, AttributeValues.b(UUID.randomUUID()), + ProfilesV2.KEY_VERSION, AttributeValue.builder().b(SdkBytes.fromByteArray("not-a-real-version".getBytes())).build())) + .conditionExpression("attribute_not_exists(#uuid)") + .expressionAttributeNames(Map.of("#uuid", ProfilesV2.KEY_ACCOUNT_UUID))) + .build(); + } + + @Test + void testSetFirstWrite() throws WriteConflictException { + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem()); + + final Optional retrieved = profilesV2.get(ACI, version); + + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(data); + assertThat(retrieved.get().commitment()).isEqualTo(commitment); + assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress); + assertThat(retrieved.get().dataHash()).isNotNull(); + assertThat(retrieved.get().paymentAddressHash()).isNotNull(); + } + + @Test + void testSetWithoutPaymentAddress() throws WriteConflictException { + + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), null, null, null, getAdditionalTransactWriteItem()); + + final Optional retrieved = profilesV2.get(ACI, version); + + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(data); + assertThat(retrieved.get().commitment()).isEqualTo(commitment); + assertThat(retrieved.get().paymentAddress()).isNull(); + assertThat(retrieved.get().paymentAddressHash()).isNull(); + } + + @Test + void testInitialSetRequiresCommitment() { + assertThrows(IllegalArgumentException.class, () -> { + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), null, profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem()); + }); + } + + @Test + void testConditionalUpdateSuccess() throws WriteConflictException { + + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem()); + + Optional retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + + // Update with correct expected hash + final byte[] newData = TestRandomUtil.nextBytes(256); + profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(), getAdditionalTransactWriteItem()); + + retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(newData); + } + + @Test + void testConditionalUpdateFailure() throws WriteConflictException { + + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem()); + + final byte[] wrongHash = TestRandomUtil.nextBytes(32); + + assertThrows(WriteConflictException.class, () -> { + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), wrongHash, getAdditionalTransactWriteItem()); + }); + + // Verify data is unchanged + final Optional retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(data); + } + + @Test + void testCommitmentImmutability() throws InvalidInputException, WriteConflictException { + + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem()); + + Optional retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + + // Try to update with a different commitment + final byte[] newData = TestRandomUtil.nextBytes(256); + final byte[] differentCommitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); + + assertThrows(IllegalArgumentException.class, + () -> profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), differentCommitment, profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(), + getAdditionalTransactWriteItem())); + } + + @Test + void testUpdateWithNullCommitmentSucceeds() throws WriteConflictException { + profilesV2.set(ACI,profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem()); + + Optional retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + final byte[] originalCommitment = retrieved.get().commitment(); + + final byte[] newData = TestRandomUtil.nextBytes(256); + profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), null, profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(), getAdditionalTransactWriteItem()); + + retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(newData); + assertThat(retrieved.get().commitment()).isEqualTo(originalCommitment); + } + + @Test + void testMultipleVersions() throws InvalidInputException, WriteConflictException { + final byte[] versionOne = TestRandomUtil.nextBytes(32); + final byte[] versionTwo = TestRandomUtil.nextBytes(32); + + final byte[] dataOne = TestRandomUtil.nextBytes(256); + final byte[] dataTwo = TestRandomUtil.nextBytes(256); + + final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); + final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); + + profilesV2.set(ACI, versionOne, dataOne, VersionedProfile.hash(dataOne), commitmentOne, paymentAddress, + VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem()); + profilesV2.set(ACI, versionTwo, dataTwo, VersionedProfile.hash(dataTwo), commitmentTwo, null, null,null, getAdditionalTransactWriteItem()); + + Optional retrieved = profilesV2.get(ACI, versionOne); + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(dataOne); + assertThat(retrieved.get().commitment()).isEqualTo(commitmentOne); + assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress); + + retrieved = profilesV2.get(ACI, versionTwo); + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(dataTwo); + assertThat(retrieved.get().commitment()).isEqualTo(commitmentTwo); + assertThat(retrieved.get().paymentAddress()).isNull(); + } + + @Test + void testMissing() throws WriteConflictException { + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem()); + final byte[] missingVersion = TestRandomUtil.nextBytes(32); + + final Optional retrieved = profilesV2.get(ACI, missingVersion); + assertThat(retrieved.isPresent()).isFalse(); + } + + @Test + void testDeleteAll() throws InvalidInputException, WriteConflictException { + final byte[] versionOne = TestRandomUtil.nextBytes(32); + final byte[] versionTwo = TestRandomUtil.nextBytes(32); + final byte[] versionThree = TestRandomUtil.nextBytes(32); + + final byte[] dataOne = TestRandomUtil.nextBytes(256); + final byte[] dataTwo = TestRandomUtil.nextBytes(256); + final byte[] dataThree = TestRandomUtil.nextBytes(256); + + final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); + final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); + final byte[] commitmentThree = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); + + profilesV2.set(ACI, versionOne, dataOne, VersionedProfile.hash(dataOne), commitmentOne, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem()); + profilesV2.set(ACI, versionTwo, dataTwo, VersionedProfile.hash(dataTwo), commitmentTwo, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem()); + profilesV2.set(ACI, versionThree, dataThree, VersionedProfile.hash(dataThree), commitmentThree, null, null,null, getAdditionalTransactWriteItem()); + + profilesV2.deleteAll(ACI).join(); + + for (byte[] v : List.of(versionOne, versionTwo, versionThree)) { + final Optional retrieved = profilesV2.get(ACI, v); + assertThat(retrieved.isPresent()).isFalse(); + } + } + + @Test + void testUpdatePaymentAddress() throws WriteConflictException { + + profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem()); + + Optional retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress); + + // Update to remove payment address + final byte[] newData = TestRandomUtil.nextBytes(256); + profilesV2.set(ACI, version, newData, VersionedProfile.hash(newData), commitment, null, null, retrieved.get().dataHash(), getAdditionalTransactWriteItem()); + + retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + assertThat(retrieved.get().data()).isEqualTo(newData); + assertThat(retrieved.get().paymentAddress()).isNull(); + assertThat(retrieved.get().paymentAddressHash()).isNull(); + } + + @Test + void testSetWithAdditionalTransactWriteItemConflict() throws WriteConflictException { + + profilesV2.set(ACI, version, data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem()); + + final Optional retrieved = profilesV2.get(ACI, version); + assertThat(retrieved.isPresent()).isTrue(); + + // write an update + final byte[] updatedData = TestRandomUtil.nextBytes(256); + profilesV2.set(ACI, version, updatedData, VersionedProfile.hash(updatedData), null, paymentAddress, VersionedProfile.hash(paymentAddress), retrieved.get().dataHash(), getAdditionalTransactWriteItem()); + + // attempt a second update with a stale hash + assertThrows(WriteConflictException.class, () -> { + final byte[] conflictedData = TestRandomUtil.nextBytes(256); + profilesV2.set(ACI, version, conflictedData, VersionedProfile.hash(conflictedData), null, paymentAddress, VersionedProfile.hash(paymentAddress), retrieved.get().dataHash(), getAdditionalTransactWriteItem()); + }); + + // still has updatedData + final Optional retrievedV2 = profilesV2.get(ACI, version); + assertThat(retrievedV2.isPresent()).isTrue(); + assertThat(retrievedV2.get().data()).isEqualTo(updatedData); + } + + @CartesianTest + void testGetTransactWriteItem( + @CartesianTest.Values(booleans = {true, false}) final boolean hasCommitment, + @CartesianTest.Values(booleans = {true, false}) final boolean hasExpectedDataHash) { + final byte[] commitment = hasCommitment ? profile.commitment() : null; + final byte[] expectedDataHash = hasExpectedDataHash ? TestRandomUtil.nextBytes(32) : null; + + final TransactWriteItem transactWriteItem = profilesV2.getTransactWriteItem( + ACI, profile.version(), profile.data(), profile.dataHash(), commitment, profile.paymentAddress(), profile.paymentAddressHash(), expectedDataHash); + + assertThat(transactWriteItem).isNotNull(); + assertThat(transactWriteItem.update()).isNotNull(); + assertThat(transactWriteItem.update().tableName()).isEqualTo(Tables.PROFILES_V2.tableName()); + assertThat(transactWriteItem.update().key()).isNotNull(); + assertThat(transactWriteItem.update().updateExpression()).isEqualTo(ProfilesV2.buildUpdateExpression(commitment != null, paymentAddress != null)); + assertThat(transactWriteItem.update().conditionExpression()).isEqualTo(ProfilesV2.buildConditionExpression(commitment != null, expectedDataHash != null)); + assertThat(transactWriteItem.update().expressionAttributeValues()) + .isEqualTo(ProfilesV2.buildUpdateExpressionAttributeValues(data, profile.dataHash(), commitment, paymentAddress, profile.paymentAddressHash(), expectedDataHash)); + } + + @ParameterizedTest + @MethodSource + void testBuildUpdateExpression(final byte[] commitment, final byte[] paymentAddress, final String expectedUpdateExpression) { + assertEquals(expectedUpdateExpression, ProfilesV2.buildUpdateExpression(commitment != null, paymentAddress != null)); + } + + private static Stream testBuildUpdateExpression() { + final byte[] commitment = TestRandomUtil.nextBytes(32); + final byte[] paymentAddress = TestRandomUtil.nextBytes(582); + + return Stream.of( + Arguments.argumentSet("with commitment and payment address", + commitment, + paymentAddress, + "SET #data = :data, #dataHash = :dataHash, #commitment = if_not_exists(#commitment, :commitment), #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash"), + Arguments.argumentSet("with commitment, without payment address", + commitment, + null, + "SET #data = :data, #dataHash = :dataHash, #commitment = if_not_exists(#commitment, :commitment) REMOVE #paymentAddress, #paymentAddressHash"), + Arguments.argumentSet("without commitment, with payment address", + null, + paymentAddress, + "SET #data = :data, #dataHash = :dataHash, #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash"), + Arguments.argumentSet("without commitment or payment address", + null, + null, + "SET #data = :data, #dataHash = :dataHash REMOVE #paymentAddress, #paymentAddressHash") + ); + } + + @ParameterizedTest + @MethodSource + void testBuildConditionExpression(final byte[] commitment, final byte[] expectedCurrentDataHash, final String expectedConditionExpression) { + assertEquals(expectedConditionExpression, ProfilesV2.buildConditionExpression(commitment != null, expectedCurrentDataHash != null)); + } + + private static Stream testBuildConditionExpression() { + final byte[] commitment = TestRandomUtil.nextBytes(97); + final byte[] dataHash = TestRandomUtil.nextBytes(32); + + return Stream.of( + Arguments.argumentSet("initial write", + commitment, + null, + "(attribute_not_exists(#commitment) OR #commitment = :commitment) AND attribute_not_exists(#dataHash)"), + Arguments.argumentSet("update with commitment", + commitment, + dataHash, + "(attribute_not_exists(#commitment) OR #commitment = :commitment) AND #dataHash = :expectedDataHash"), + Arguments.argumentSet("update without commitment", + null, + dataHash, + "size(#commitment) = :commitment_length AND #dataHash = :expectedDataHash") + ); + } + + @ParameterizedTest + @MethodSource + void testBuildUpdateExpressionAttributeValues( + final byte[] data, + final byte[] dataHash, + final byte[] commitment, + final byte[] paymentAddress, + final byte[] paymentAddressHash, + final byte[] expectedCurrentDataHash, + final int expectedMapSize) { + + final Map result = ProfilesV2.buildUpdateExpressionAttributeValues( + data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash); + + assertEquals(expectedMapSize, result.size()); + assertThat(result.containsKey(":data")).isTrue(); + assertThat(result.containsKey(":dataHash")).isTrue(); + + if (commitment != null) { + assertThat(result.containsKey(":commitment")).isTrue(); + } else { + assertThat(result.containsKey(":commitment_length")).isTrue(); + } + + if (expectedCurrentDataHash != null) { + assertThat(result.containsKey(":expectedDataHash")).isTrue(); + } + + if (paymentAddress != null) { + assertThat(result.containsKey(":paymentAddress")).isTrue(); + assertThat(result.containsKey(":paymentAddressHash")).isTrue(); + } + + } + + private static Stream testBuildUpdateExpressionAttributeValues() throws InvalidInputException { + final byte[] data = TestRandomUtil.nextBytes(256); + final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize(); + final byte[] paymentAddress = TestRandomUtil.nextBytes(582); + final byte[] dataHash = TestRandomUtil.nextBytes(32); + + return Stream.of( + Arguments.argumentSet("all fields present", + data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), dataHash, 6), + Arguments.argumentSet("no payment address", + data, VersionedProfile.hash(data), commitment, null, null, dataHash, 4), + Arguments.argumentSet("no commitment", + data, VersionedProfile.hash(data), null, paymentAddress, VersionedProfile.hash(paymentAddress), dataHash, 6), + Arguments.argumentSet("only data fields", + data, VersionedProfile.hash(data), null, null, null, dataHash, 4) + ); + } + + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + @ParameterizedTest + @MethodSource + void testSetWithTransactionCanceledException(final Optional> maybeCodes, final Class expectedException) throws InvalidInputException { + final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class); + final ProfilesV2 profilesV2 = new ProfilesV2(dynamoDbClient, mock(DynamoDbAsyncClient.class), Tables.PROFILES_V2.tableName()); + + final UUID uuid = UUID.randomUUID(); + final byte[] version = TestRandomUtil.nextBytes(32); + final byte[] data = TestRandomUtil.nextBytes(256); + final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize(); + final byte[] paymentAddress = TestRandomUtil.nextBytes(582); + final byte[] expectedHash = TestRandomUtil.nextBytes(32); + + final TransactionCanceledException.Builder exceptionBuilder = TransactionCanceledException.builder(); + maybeCodes.ifPresent(codes -> { + final CancellationReason[] cancellationReasons = codes.stream().map(code -> + CancellationReason.builder().code(code).build()) + .toArray(CancellationReason[]::new); + + exceptionBuilder.cancellationReasons(cancellationReasons); + }); + final TransactionCanceledException exception = exceptionBuilder.build(); + + when(dynamoDbClient.transactWriteItems(any(TransactWriteItemsRequest.class))) + .thenThrow(exception); + + assertThrows(expectedException, () -> + profilesV2.set(uuid, version, data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), expectedHash, getAdditionalTransactWriteItem())); + } + + static Collection testSetWithTransactionCanceledException() { + return List.of( + Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ConditionalCheckFailed")), WriteConflictException.class), + Arguments.argumentSet("TransactionConflict throws WriteConflictException", Optional.of(List.of("TransactionConflict")), WriteConflictException.class), + Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ConditionalCheckFailed", "ThrottlingError")), WriteConflictException.class), + Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ThrottlingError", "ConditionalCheckFailed")), WriteConflictException.class), + Arguments.argumentSet("ThrottlingError throws TransactionCanceledException", Optional.of(List.of("ThrottlingError")), TransactionCanceledException.class), + Arguments.argumentSet("No code throws TransactionCanceledException", Optional.empty(), TransactionCanceledException.class) + ); + } + +} diff --git a/service/src/test/proto/profile.proto b/service/src/test/proto/profile.proto new file mode 100644 index 000000000..397d8a631 --- /dev/null +++ b/service/src/test/proto/profile.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; + +option java_multiple_files = true; + +package org.signal.chat.profile.test; + +// This may be removed in favor of a canonical libsignal definition in a future release +message PlaintextProfileData { + string name = 1; // max length = 257 + optional string about = 2; // max length = 512 + optional string aboutEmoji = 3; // max length = 32 + optional string avatar = 4; // max length = 64 + bool phoneNumberSharing = 5; + + // 15 is the highest field number without serialization overhead + optional bytes padding = 15; // length = 64 - (len(name) + len(about) + len(aboutEmoji) + len(avatar) + 1) % 64 + + // next: 6 +} diff --git a/service/src/test/proto/validation_test.proto b/service/src/test/proto/validation_test.proto index 7c3cd0345..6ab6520d9 100644 --- a/service/src/test/proto/validation_test.proto +++ b/service/src/test/proto/validation_test.proto @@ -10,6 +10,7 @@ option java_multiple_files = true; package org.signal.chat.rpc; import "org/signal/chat/require.proto"; +import "org/signal/chat/common.proto"; import "google/protobuf/empty.proto"; service ValidationTestService { @@ -79,6 +80,11 @@ message ValidationsRequest { } optional string base64url = 33 [(require.base64url) = true]; + + optional common.ServiceIdentifier aciServiceIdentifier = 34 [(require.identityType) = IDENTITY_TYPE_ACI]; + optional common.ServiceIdentifier pniServiceIdentifier = 35 [(require.identityType) = IDENTITY_TYPE_PNI]; + + // next 36 } message NestedMessage { diff --git a/service/src/test/resources/config/test.yml b/service/src/test/resources/config/test.yml index 99c760c2f..c487f6ec2 100644 --- a/service/src/test/resources/config/test.yml +++ b/service/src/test/resources/config/test.yml @@ -131,6 +131,8 @@ dynamoDbTables: tableName: pni_test profiles: tableName: profiles_test + profilesV2: + tableName: profilesV2_test pushChallenge: tableName: push_challenge_test pushNotificationExperimentSamples: