From ed90c1c15c1dcd72b7adfec25d92cafc6b61da22 Mon Sep 17 00:00:00 2001 From: Ravi Khadiwala Date: Wed, 1 Jul 2026 09:57:41 -0500 Subject: [PATCH] Drop unversioned profiles from grpc service --- service/pom.xml | 6 + .../ConfiguredProfileBadgeConverter.java | 15 + .../badges/ProfileBadgeConverter.java | 6 + .../textsecuregcm/grpc/KeysGrpcHelper.java | 15 +- .../grpc/ProfileAnonymousGrpcService.java | 76 +-- .../textsecuregcm/grpc/ProfileGrpcHelper.java | 239 +++++----- .../grpc/ProfileGrpcService.java | 54 +-- .../src/main/proto/org/signal/chat/keys.proto | 9 + .../main/proto/org/signal/chat/profile.proto | 220 ++++----- .../controllers/ProfileControllerTest.java | 22 +- .../grpc/KeysAnonymousGrpcServiceTest.java | 5 + .../grpc/KeysGrpcServiceTest.java | 70 +++ .../grpc/ProfileAnonymousGrpcServiceTest.java | 443 +++++------------- .../grpc/ProfileGrpcHelperTest.java | 101 ++++ .../grpc/ProfileGrpcServiceTest.java | 286 +++++------ 15 files changed, 708 insertions(+), 859 deletions(-) create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelperTest.java diff --git a/service/pom.xml b/service/pom.xml index e1e2f1436..62ade18b0 100644 --- a/service/pom.xml +++ b/service/pom.xml @@ -572,6 +572,12 @@ google-auth-library-oauth2-http + + org.bouncycastle + bcprov-jdk18on + compile + + com.stripe stripe-java diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/badges/ConfiguredProfileBadgeConverter.java b/service/src/main/java/org/whispersystems/textsecuregcm/badges/ConfiguredProfileBadgeConverter.java index 40c7aae07..2b83785d2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/badges/ConfiguredProfileBadgeConverter.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/badges/ConfiguredProfileBadgeConverter.java @@ -65,6 +65,21 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B false); } + @Override + public List visibleBadgeIds(final List accountBadges) { + if (accountBadges.isEmpty()) { + return List.of(); + } + + final Instant now = clock.instant(); + return accountBadges.stream() + .filter(accountBadge -> accountBadge.visible() + && now.isBefore(accountBadge.expiration()) + && knownBadges.containsKey(accountBadge.id())) + .map(AccountBadge::id) + .toList(); + } + @Override public List convert( final List acceptableLanguages, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/badges/ProfileBadgeConverter.java b/service/src/main/java/org/whispersystems/textsecuregcm/badges/ProfileBadgeConverter.java index b36f8946f..65416432d 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/badges/ProfileBadgeConverter.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/badges/ProfileBadgeConverter.java @@ -12,6 +12,12 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge; public interface ProfileBadgeConverter { + /// Determine displayable badge ids for an account's badges + /// + /// @param badges The full list of badges on an account + /// @return The list of badge-ids that should appear on this account's profile to other users + List visibleBadgeIds(final List badges); + /** * Converts the {@link AccountBadge}s for an account into the objects * that can be returned on a profile fetch. diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java index 67a57a09c..f9a2868fb 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/KeysGrpcHelper.java @@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.grpc; import com.google.protobuf.ByteString; +import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -24,9 +25,12 @@ import org.signal.libsignal.protocol.kem.KEMPublicKey; import org.whispersystems.textsecuregcm.entities.ECPreKey; import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; +import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum; +import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.Device; +import org.whispersystems.textsecuregcm.storage.DeviceCapability; import org.whispersystems.textsecuregcm.storage.KeyIdUtil; import org.whispersystems.textsecuregcm.storage.KeysManager; @@ -71,7 +75,16 @@ class KeysGrpcHelper { } final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder() - .setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize())); + .setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize())) + .setUnrestrictedUnidentifiedAccess(targetServiceIdentifier.identityType() == IdentityType.ACI && targetAccount.isUnrestrictedUnidentifiedAccess()); + + // Set the UAK hash if the account has a UAK and we're targeting an ACI. PNIs don't allow unidentified access. + targetAccount + .getUnidentifiedAccessKey() + .filter(_ -> targetServiceIdentifier.identityType() == IdentityType.ACI) + .map(UnidentifiedAccessChecksum::generateFor) + .map(ByteString::copyFrom) + .ifPresent(preKeyBundlesBuilder::setUnidentifiedAccessKeyFingerprint); preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> { final Device device = targetAccount.getDevice(deviceId).orElseThrow(); 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 038942fbc..9e60baa1d 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcService.java @@ -22,10 +22,8 @@ import org.signal.chat.profile.GetAvatarUploadFormRequest; import org.signal.chat.profile.GetAvatarUploadFormResponse; import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest; import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse; -import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest; -import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse; -import org.signal.chat.profile.GetVersionedProfileAnonymousRequest; -import org.signal.chat.profile.GetVersionedProfileAnonymousResponse; +import org.signal.chat.profile.GetProfileAnonymousRequest; +import org.signal.chat.profile.GetProfileAnonymousResponse; import org.signal.chat.profile.SimpleProfileAnonymousGrpc; import org.signal.libsignal.zkgroup.GenericServerSecretParams; import org.signal.libsignal.zkgroup.InvalidInputException; @@ -36,7 +34,6 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator; @@ -101,44 +98,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof } @Override - public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) { - final ServiceIdentifier targetIdentifier = - GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier()); - - // Callers must be authenticated to request unversioned profiles by PNI - if (targetIdentifier.identityType() == IdentityType.PNI) { - throw GrpcExceptions.invalidArguments("aci service identifier type required"); - } - - 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 -> - targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray())) - .orElse(false); - default -> throw GrpcExceptions.invalidArguments("invalid authentication"); - }; - - if (!authorized) { - return GetUnversionedProfileAnonymousResponse.newBuilder() - .setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance()) - .build(); - } - - return targetAccount.map(account -> - GetUnversionedProfileAnonymousResponse.newBuilder() - .setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier, - account, - profileBadgeConverter)) - .build()) - .orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder() - .setNotFound(NotFound.getDefaultInstance()) - .build()); - } - - @Override - public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) { + public GetProfileAnonymousResponse getProfile(final GetProfileAnonymousRequest request) { final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier()); final Optional targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier); @@ -152,25 +112,25 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof }; if (!authorized) { - return GetVersionedProfileAnonymousResponse.newBuilder() + return GetProfileAnonymousResponse.newBuilder() .setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance()) .build(); } + final byte[] version = request.getRequest().getVersion().toByteArray(); - 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()); + return targetAccount.flatMap(account -> ProfileGrpcHelper + .getProfile(account, profilesManager, profileBadgeConverter, version) + + // If the etag matches, drop the result + .map(profileResult -> request.getRequest().getEtag().equals(profileResult.getEtag()) + ? GetProfileAnonymousResponse.newBuilder().setEtagMatched(true).build() + : GetProfileAnonymousResponse.newBuilder().setProfile(profileResult).build()) + + // If we didn't find a v2 profile, try a v1 profile + .or(() -> ProfileGrpcHelper + .getProfileV1(account, profilesManager, profileBadgeConverter, version) + .map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build()))) + .orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()); } @Override 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 b77981f2f..42ff68397 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java @@ -7,20 +7,21 @@ package org.whispersystems.textsecuregcm.grpc; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; import java.time.Clock; import java.util.Arrays; import java.util.HexFormat; import java.util.List; -import java.util.Locale; import java.util.Optional; +import org.bouncycastle.crypto.digests.TupleHash; import org.signal.chat.common.S3UploadForm; -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.chat.profile.ProfileResult; +import org.signal.chat.profile.ProfileResultOrBuilder; +import org.signal.chat.profile.LegacyProfileResult; +import org.signal.chat.profile.AccountInfo; import org.signal.libsignal.protocol.ServiceId; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.VerificationFailedException; @@ -30,8 +31,7 @@ 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; -import org.whispersystems.textsecuregcm.entities.Badge; -import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; +import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.DeviceCapability; @@ -42,127 +42,84 @@ import org.whispersystems.textsecuregcm.util.ProfileHelper; public class ProfileGrpcHelper { + private static final byte[] ETAG_DOMAIN = "ProfileETag/v1".getBytes(StandardCharsets.UTF_8); + private static final int ETAG_LENGTH = 10; private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder() .setAcl(PostPolicyGenerator.ACL) .setAlgorithm(PostPolicyGenerator.ALGORITHM) .build(); - static Optional getVersionedProfile(final Account account, + static Optional getProfileV1(final Account account, final ProfilesManager profilesManager, - final byte[] requestVersion, - final byte[] requestDataEtag, - final byte[] requestPaymentAddressEtag) { - - final Optional profile; - if (account.hasCapability(DeviceCapability.PROFILES_V2)) { - profile = profilesManager.get(account.getUuid(), requestVersion); - } else { - profile = Optional.empty(); - } - - final Optional v1Profile; - if (profile.isEmpty()) { - v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion)); - } else { - v1Profile = Optional.empty(); - } - - if (profile.isEmpty() && v1Profile.isEmpty()) { + final ProfileBadgeConverter profileBadgeConverter, + final byte[] requestVersion) { + final Optional maybeV1Profile = + profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion)); + if (maybeV1Profile.isEmpty()) { return Optional.empty(); } + final VersionedProfileV1 v1Profile = maybeV1Profile.get(); - final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder(); + final LegacyProfileResult.Builder builder = LegacyProfileResult.newBuilder() + .setAccountInfo(buildAccountInfo(profileBadgeConverter, account)) + .setName(ByteString.copyFrom(v1Profile.name())) + .setAbout(ByteString.copyFrom(v1Profile.about())) + .setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji())) + .setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing())); - 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())) - .setEtagSha256(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 -> Arrays.equals(v, 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())) - .setEtagSha256(ByteString.copyFrom( - profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get())))) - .build()); - } - } + if (v1Profile.avatar() != null) { + builder.setAvatar(v1Profile.avatar()); } - return Optional.of(responseBuilder.build()); - } - - @VisibleForTesting - static List buildAccountCapabilities(final Account account) { - return Arrays.stream(DeviceCapability.values()) - .filter(DeviceCapability::includeInProfile) - .filter(account::hasCapability) - .map(DeviceCapabilityUtil::toGrpcDeviceCapability) - .toList(); - } - - static GetUnversionedProfileResult buildUnversionedProfileResult( - final ServiceIdentifier targetIdentifier, - final Account targetAccount, - final ProfileBadgeConverter profileBadgeConverter) { - final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder() - .setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize())) - .addAllCapabilities(buildAccountCapabilities(targetAccount)); - - switch (targetIdentifier.identityType()) { - case ACI -> { - final List acceptedLocales = RequestAttributesUtil.getAvailableAcceptedLocales(); - final List badges = - profileBadgeConverter.convert(acceptedLocales, targetAccount.getBadges(), false); - - resultBuilder - .setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess()) - .addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList()); - - targetAccount.getUnidentifiedAccessKey() - .map(UnidentifiedAccessChecksum::generateFor) - .map(ByteString::copyFrom) - .ifPresent(resultBuilder::setUnidentifiedAccess); - } - case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false); + // If present, include the payment address if the version matches the latest version on Account or the latest + // version on Account is empty + if (v1Profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) { + builder.setPaymentAddress(ByteString.copyFrom(v1Profile.paymentAddress())); } - return resultBuilder.build(); + return Optional.of(builder.build()); + } + + static Optional getProfile(final Account account, + final ProfilesManager profilesManager, + final ProfileBadgeConverter profileBadgeConverter, + final byte[] requestVersion) { + + final Optional maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2) + ? profilesManager.get(account.getUuid(), requestVersion) + : Optional.empty(); + if (maybeProfile.isEmpty()) { + return Optional.empty(); + } + final VersionedProfile profile = maybeProfile.get(); + + final ProfileResult.Builder builder = ProfileResult.newBuilder() + .setData(ByteString.copyFrom(profile.data())) + .setAccountInfo(buildAccountInfo(profileBadgeConverter, account)); + + // If present, include the payment address if the version matches the latest version on Account or the latest + // version on Account is empty + if (profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) { + builder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress())); + } + + builder.setEtag(ByteString.copyFrom(etag(builder))); + return Optional.of(builder.build()); + } + + private static AccountInfo buildAccountInfo(final ProfileBadgeConverter profileBadgeConverter, + final Account account) { + final AccountInfo.Builder accountInfoBuilder = AccountInfo.newBuilder() + .addAllBadgeIds(profileBadgeConverter.visibleBadgeIds(account.getBadges())) + .setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize())) + .setUnrestrictedUnidentifiedAccess(account.isUnrestrictedUnidentifiedAccess()); + + account.getUnidentifiedAccessKey() + .map(UnidentifiedAccessChecksum::generateFor) + .map(ByteString::copyFrom) + .ifPresent(accountInfoBuilder::setUnidentifiedAccessKeyFingerprint); + + return accountInfoBuilder.build(); } static Optional getExpiringProfileKeyCredentialResult( @@ -180,12 +137,14 @@ public class ProfileGrpcHelper { } return versionedProfile.map(VersionedProfile::commitment) - .or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version)).map(VersionedProfileV1::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), + profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential( + new ProfileKeyCredentialRequest(encodedCredentialRequest), new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations); } catch (VerificationFailedException | InvalidInputException e) { throw GrpcExceptions.invalidArguments("invalid credential request"); @@ -211,19 +170,37 @@ public class ProfileGrpcHelper { .build(); } - /** - * Computes the SHA-256 hash of the given data. - *

- * Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[]) - */ + /// Compute the etag of a [ProfileResult] + /// + /// @implNote This uses the NIST-SP 800-185 TupleHash to provide a cryptographic hash over variable length fields. + /// Clients must be able to reproduce the same etag from the data, so hash must be stable. @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); + static byte[] etag(final ProfileResultOrBuilder profile) { + final TupleHash h = new TupleHash(256, ETAG_DOMAIN, ETAG_LENGTH * Byte.SIZE); + final AccountInfo accountInfo = profile.getAccountInfo(); + + addByteArray(h, profile.getData().toByteArray()); + addByteArray(h, profile.getPaymentAddress().toByteArray()); + addByteArray(h, accountInfo.getIdentityKey().toByteArray()); + addByteArray(h, accountInfo.getUnidentifiedAccessKeyFingerprint().toByteArray()); + h.update(accountInfo.getUnrestrictedUnidentifiedAccess() ? (byte) 1 : (byte) 0); + + addInt(h, accountInfo.getBadgeIdsCount()); + accountInfo.getBadgeIdsList().asByteStringList().stream() + .map(ByteString::toByteArray) + .sorted(Arrays::compareUnsigned) + .forEach(badgeId -> addByteArray(h, badgeId)); + + final byte[] out = new byte[ETAG_LENGTH]; + h.doFinal(out, 0); + return out; + } + + private static void addByteArray(final TupleHash hash, final byte[] bytes) { + hash.update(bytes, 0, bytes.length); + } + + private static void addInt(final TupleHash hash, final int v) { + addByteArray(hash, ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.BIG_ENDIAN).putInt(v).array()); } } 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 27a8f9fa0..33a087617 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java @@ -22,10 +22,8 @@ import org.signal.chat.errors.FailedPrecondition; import org.signal.chat.errors.NotFound; import org.signal.chat.profile.GetAvatarCredentialsRequest; import org.signal.chat.profile.GetAvatarCredentialsResponse; -import org.signal.chat.profile.GetUnversionedProfileRequest; -import org.signal.chat.profile.GetUnversionedProfileResponse; -import org.signal.chat.profile.GetVersionedProfileRequest; -import org.signal.chat.profile.GetVersionedProfileResponse; +import org.signal.chat.profile.GetProfileRequest; +import org.signal.chat.profile.GetProfileResponse; import org.signal.chat.profile.PaymentsForbiddenInRegion; import org.signal.chat.profile.ProfilesV2CapabilityRequired; import org.signal.chat.profile.SetProfileRequest; @@ -252,43 +250,27 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase { } @Override - public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException { - final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); - final ServiceIdentifier targetIdentifier = - GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier()); - final Optional maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier); - - return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder() - .setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier, - account, - profileBadgeConverter)) - .build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder() - .setNotFound(NotFound.getDefaultInstance()) - .build()); - } - - @Override - public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException { + public GetProfileResponse getProfile(final GetProfileRequest request) throws RateLimitExceededException { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier()); + final byte[] version = request.getVersion().toByteArray(); + final Optional maybeAccount = + validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier); - final Optional maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier); + return maybeAccount.flatMap(account -> ProfileGrpcHelper + .getProfile(account, profilesManager, profileBadgeConverter, version) - 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()); + // If the etag matches, drop the result + .map(profileResult -> request.getEtag().equals(profileResult.getEtag()) + ? GetProfileResponse.newBuilder().setEtagMatched(true).build() + : GetProfileResponse.newBuilder().setProfile(profileResult).build()) + + // If we didn't find a v2 profile, try a v1 profile + .or(() -> ProfileGrpcHelper + .getProfileV1(account, profilesManager, profileBadgeConverter, version) + .map(v1Result -> GetProfileResponse.newBuilder().setLegacyProfile(v1Result).build()))) + .orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()); } private Optional validateRateLimitAndGetAccount(final UUID requesterUuid, diff --git a/service/src/main/proto/org/signal/chat/keys.proto b/service/src/main/proto/org/signal/chat/keys.proto index ad4c97431..f6d2e3e74 100644 --- a/service/src/main/proto/org/signal/chat/keys.proto +++ b/service/src/main/proto/org/signal/chat/keys.proto @@ -146,6 +146,15 @@ message AccountPreKeyBundles { // A map of device IDs to pre-key "bundles" for the targeted account. map device_pre_keys = 2; + + // Whether the account has enabled sealed sender from anyone. Always false + // if the request was for a PNI, which does not allow any unidentified access. + bool unrestricted_unidentified_access = 3; + + // If the target supports unidentified access and has an unidentified access + // key, a fingerprint of the target's UAK. This may be used to detect a change + // in the UAK that the sender has for the target before actually sending a message. Otherwise, empty. + bytes unidentified_access_key_fingerprint = 4; } message GetPreKeysResponse { diff --git a/service/src/main/proto/org/signal/chat/profile.proto b/service/src/main/proto/org/signal/chat/profile.proto index d458b9b93..b2b83e223 100644 --- a/service/src/main/proto/org/signal/chat/profile.proto +++ b/service/src/main/proto/org/signal/chat/profile.proto @@ -23,13 +23,9 @@ service Profile { // 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 + // Retrieves profile data. Callers with an unidentified access key for the account // should use the version of this method in `ProfileAnonymous` instead. - 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. - rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {} + rpc GetProfile(GetProfileRequest) returns (GetProfileResponse) {} // Returns anonymous credentials that may be presented with avatar operations in ProfilesAnonymous // @@ -46,10 +42,9 @@ service Profile { service ProfileAnonymous { option (require.auth) = AUTH_ONLY_ANONYMOUS; - // Retrieves versioned profile data. - rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {} - // Retrieves unversioned profile data. - rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {} + // Retrieves profile data. + rpc GetProfile(GetProfileAnonymousRequest) returns (GetProfileAnonymousResponse) {} + // Retrieves a profile key credential. rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {} @@ -177,27 +172,21 @@ message SetProfileResponse { } } -message GetVersionedProfileRequest { +message GetProfileRequest { // The ACI of the account for which to get profile data. - common.ServiceIdentifier accountIdentifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI]; + common.ServiceIdentifier account_identifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI]; // The profile version to retrieve. 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 + // The `etag` from the previous request for this Profile version. If + // unchanged, the response will omit `profile` and `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]; + bytes etag = 3 [(require.exactlySize) = 0, (require.exactlySize) = 10]; } -message GetVersionedProfileAnonymousRequest { - // Contains the data necessary to request a versioned profile. - GetVersionedProfileRequest request = 1 [(require.present) = true]; - +message GetProfileAnonymousRequest { + // Contains the data necessary to request a profile. + GetProfileRequest request = 1 [(require.present) = true]; oneof authentication { // The unidentified access key for the targeted account. bytes unidentified_access_key = 2 [(require.exactlySize) = 16]; @@ -207,60 +196,62 @@ message GetVersionedProfileAnonymousRequest { } } -message DataEtag { +message AccountInfo { + // The account identity key of the targeted account. + bytes identity_key = 1; + + // A checksum of the unidentified access key for the targeted account. + bytes unidentified_access_key_fingerprint = 2; + + // Whether the account has enabled sealed sender from anyone. + bool unrestricted_unidentified_access = 3; + + // A list of the badges ids associated with the account. Metadata to display + // badges may be obtained by cross-referencing badge ids with + // ProductConfiguration.GetConfiguration. + repeated string badge_ids = 4; +} + +message ProfileResult { + // The ciphertext of the requested version of the profile bytes data = 1; - // An entity tag for `data`. This may be used in subsequent requests for - // this profile version to optimize bandwidth. + + // The ciphertext of the MobileCoin wallet ID on the profile. + bytes payment_address = 2; + + // Information about the targeted account + AccountInfo account_info = 3; + + // An entity tag for the profile. This may be used in subsequent requests + // for this profile version to optimize bandwidth. // - // Clients may validate that the value has been correctly calculated by deriving - // the SHA-256 digest of `data`. - bytes etag_sha256 = 2; + // Note that this hash will not match the expected_data_hash used on + // SetProfile for concurrency control. + // + // Clients may validate that the value has been correctly calculated by + // calculating a 10-byte truncated TupleHash256 as follows: + // + // ``` + // TupleHash256(S = "ProfileETag/v1", L = 80 bits, tuple = [ + // data, + // payment_address, + // account_info.identity_key, + // account_info.unidentified_access_key_fingerprint, + // account_info.unrestricted_unidentified_access ? 0x01 : 0x00, + // uint32BE(count(account_info.badge_ids)), + // utf8(id) for each id in sortLexAscendingByUtf8Bytes(account_info.badge_ids), + // ]) + //``` + // + // Absent/empty fields contribute an empty element (not zero bytes omitted): + // a missing payment_address is still a present, zero-length tuple element. + // + // This etag will always exclusively cover the documented fields. If fields + // are added in the future, a new etag field must be introduced. + bytes etag = 4; } - -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 { +message LegacyProfileResult { // The ciphertext of the name on the profile. bytes name = 1; @@ -270,61 +261,54 @@ message GetVersionedProfileV1Response { bytes about_emoji = 3; // The cdn0 path of the avatar on the profile. string avatar = 4; - // The ciphertext of the phone-number sharing setting on the profile. bytes phone_number_sharing = 5; + // The ciphertext of the MobileCoin wallet ID on the profile. + bytes payment_address = 6; + // Information about the targeted account + AccountInfo account_info = 7; } -message GetUnversionedProfileRequest { - // The service identifier of the account for which to get profile data. - common.ServiceIdentifier service_identifier = 1 [(require.present) = true]; -} -message GetUnversionedProfileAnonymousRequest { - // 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. - bytes unidentified_access_key = 2; - - // A group send endorsement token for the targeted account. - bytes group_send_token = 3; - } -} - -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. Absent - // if the request was for a PNI. - bytes unidentified_access = 2; - // Whether the account has enabled sealed sender from anyone. Always false - // if the request was for a PNI. - bool unrestricted_unidentified_access = 3; - // A list of capabilities enabled on the account. - repeated common.DeviceCapability capabilities = 4; - // A list of badges associated with the account. Absent if the request was for - // a PNI. - repeated common.Badge badges = 5; -} - -message GetUnversionedProfileResponse { +message GetProfileResponse { oneof response { - GetUnversionedProfileResult result = 1; - errors.NotFound not_found = 2 [(tag.reason) = "not_found"]; + // The full profile data. The current profile did not match the provided + // etag (or no etag was provided). + ProfileResult profile = 1; + + // The current profile matched the provided etag. If present, this will always be true. + bool etag_matched = 2 [(tag.reason) = "etag_match"]; + + errors.NotFound not_found = 3 [(tag.reason) = "not_found"]; + + // 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. + LegacyProfileResult legacy_profile = 15 [(tag.reason) = "legacy_profile"]; } + // next: 4 } -message GetUnversionedProfileAnonymousResponse { +message GetProfileAnonymousResponse { 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"]; + // The full profile data. The current profile did not match the provided + // etag (or no etag was provided). + ProfileResult profile = 1; + + // The current profile matched the provided etag. If present, this will always be true. + bool etag_matched = 2 [(tag.reason) = "etag_match"]; + + errors.NotFound not_found = 3 [(tag.reason) = "not_found"]; + errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 4 [(tag.reason) = "failed_unidentified_authorization"]; + + // 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. + LegacyProfileResult profile_v1 = 15 [(tag.reason) = "profile_v1"]; } + // next: 5 } message GetExpiringProfileKeyCredentialRequest { 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 61274d070..4c96c627d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java @@ -45,6 +45,7 @@ import java.util.Collection; import java.util.Collections; import java.util.HexFormat; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -80,6 +81,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext; import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; +import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter; import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration; import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; @@ -160,9 +162,23 @@ class ProfileControllerTest { accountsManager, profilesManager, dynamicConfigurationManager, - (acceptableLanguages, accountBadges, isSelf) -> List.of(new Badge("TEST", "other", "Test Badge", - "This badge is in unit tests.", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))) - ), + new ProfileBadgeConverter() { + @Override + public List visibleBadgeIds(final List badges) { + return List.of("TEST"); + } + + @Override + public List convert(final List acceptableLanguages, final List accountBadges, + final boolean isSelf) { + return List.of(new Badge("TEST", "other", "Test Badge", + "This badge is in unit tests.", + List.of("l", "m", "h", "x", "xx", "xxx"), + "SVG", List.of(new BadgeSvg("sl", "sd"), + new BadgeSvg("ml", "md"), + new BadgeSvg("ll", "ld")))); + } + }, new BadgesConfiguration(List.of( new BadgeConfiguration("TEST", "other", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))), new BadgeConfiguration("TEST1", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcServiceTest.java index 6b3deaeca..fa4e233af 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/KeysAnonymousGrpcServiceTest.java @@ -55,6 +55,7 @@ import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.InvalidKeyException; import org.signal.libsignal.protocol.ecc.ECKeyPair; import org.signal.libsignal.zkgroup.ServerSecretParams; +import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.entities.ECPreKey; import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; @@ -129,6 +130,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getPreKeys(builder.build())); verify(preKeysRateLimiter).validate(expectedRateLimitKey); } + + @CartesianTest + void getPreKeysUnidentifiedInfo( + @CartesianTest.Enum(names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"}) final org.signal.chat.common.IdentityType grpcIdentityType, + @CartesianTest.Values(booleans = {false , true}) final boolean hasUak, + @CartesianTest.Values(booleans = {false , true}) final boolean hasUua) { + final Account targetAccount = mock(Account.class); + + final ECKeyPair identityKeyPair = ECKeyPair.generate(); + final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey()); + final UUID identifier = UUID.randomUUID(); + + final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(grpcIdentityType); + final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = switch (identityType) { + case PNI -> new PniServiceIdentifier(identifier); + case ACI -> new AciServiceIdentifier(identifier); + }; + + when(targetAccount.getUuid()).thenReturn(UUID.randomUUID()); + when(targetAccount.getIdentifier(identityType)).thenReturn(identifier); + when(targetAccount.getIdentityKey(identityType)).thenReturn(identityKey); + when(accountsManager.getByServiceIdentifier(serviceIdentifier)) + .thenReturn(Optional.of(targetAccount)); + + final byte deviceId1 = 1; + final int registrationId = 123; + + final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(3, identityKeyPair); + final Optional maybeEcPreKey = Optional.of(new ECPreKey(1, ECKeyPair.generate().getPublicKey())); + final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, identityKeyPair); + when(keysManager.takeDevicePreKeys(eq(deviceId1), eq(serviceIdentifier), any())) + .thenReturn(CompletableFuture.completedFuture(Optional.of(new KeysManager.DevicePreKeys(ecSignedPreKey, maybeEcPreKey, kemSignedPreKey)))); + + final Device device = mock(Device.class); + when(device.getId()).thenReturn(deviceId1); + when(device.getRegistrationId(any())).thenReturn(registrationId); + + final Map devices = Map.of(deviceId1, device); + when(targetAccount.getDevice(deviceId1)).thenReturn(Optional.of(device)); + when(targetAccount.getDevices()).thenReturn(new ArrayList<>(devices.values())); + + final byte[] uak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); + when(targetAccount.getUnidentifiedAccessKey()).thenReturn(hasUak ? Optional.of(uak) : Optional.empty()); + when(targetAccount.isUnrestrictedUnidentifiedAccess()).thenReturn(hasUua); + + final GetPreKeysResponse response = authenticatedServiceStub().getPreKeys(GetPreKeysRequest.newBuilder() + .setTargetIdentifier(ServiceIdentifier.newBuilder() + .setIdentityType(grpcIdentityType) + .setUuid(UUIDUtil.toByteString(identifier)) + .build()) + .setDeviceId(1) + .build()); + + assertTrue(response.hasPreKeys()); + assertEquals(identityType == IdentityType.ACI && hasUua, + response.getPreKeys().getUnrestrictedUnidentifiedAccess()); + if (identityType == IdentityType.ACI && hasUak) { + assertArrayEquals(UnidentifiedAccessChecksum.generateFor(uak), + response.getPreKeys().getUnidentifiedAccessKeyFingerprint().toByteArray()); + } else { + assertTrue(response.getPreKeys().getUnidentifiedAccessKeyFingerprint().isEmpty()); + } + + } } 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 aff793c89..92597a0c6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileAnonymousGrpcServiceTest.java @@ -13,7 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -41,7 +41,6 @@ import java.util.Collection; import java.util.Collections; import java.util.HexFormat; import java.util.List; -import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; @@ -52,13 +51,10 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; -import org.junitpioneer.jupiter.cartesian.CartesianTest; 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.DeleteAvatarRequest; import org.signal.chat.profile.DeleteAvatarResponse; import org.signal.chat.profile.ExtendAvatarTTLRequest; @@ -68,16 +64,13 @@ import org.signal.chat.profile.GetAvatarUploadFormResponse; import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest; import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse; import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest; -import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest; -import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse; -import org.signal.chat.profile.GetUnversionedProfileRequest; -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.GetVersionedProfileResult; -import org.signal.chat.profile.GetVersionedProfileV1Response; +import org.signal.chat.profile.GetProfileAnonymousRequest; +import org.signal.chat.profile.GetProfileAnonymousResponse; +import org.signal.chat.profile.GetProfileRequest; import org.signal.chat.profile.ProfileAnonymousGrpc; +import org.signal.chat.profile.ProfileResult; +import org.signal.chat.profile.LegacyProfileResult; +import org.signal.chat.profile.AccountInfo; import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.ServiceId; import org.signal.libsignal.protocol.ecc.ECKeyPair; @@ -99,8 +92,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; -import org.whispersystems.textsecuregcm.entities.Badge; -import org.whispersystems.textsecuregcm.entities.BadgeSvg; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimiter; import org.whispersystems.textsecuregcm.limits.RateLimiters; @@ -169,243 +160,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest badges = List.of(new Badge( - "TEST", - "other", - "Test Badge", - "This badge is in unit tests.", - List.of("l", "m", "h", "x", "xx", "xxx"), - "SVG", - List.of( - new BadgeSvg("sl", "sd"), - new BadgeSvg("ml", "md"), - new BadgeSvg("ll", "ld"))) - ); - - when(account.getBadges()).thenReturn(Collections.emptyList()); - when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges); - when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false); - when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); - when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey); - when(account.hasCapability(any())).thenReturn(false); - when(account.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(true); - when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account)); - - final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder() - .setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)) - .setRequest(GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid))) - .build()) - .build()) - .build(); - - final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request); - - final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey); - final GetUnversionedProfileAnonymousResponse expectedResponse = GetUnversionedProfileAnonymousResponse.newBuilder() - .setResult(GetUnversionedProfileResult.newBuilder() - .setIdentityKey(ByteString.copyFrom(identityKey.serialize())) - .setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum)) - .setUnrestrictedUnidentifiedAccess(false) - .addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET) - .addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList()) - .build() - ) - .build(); - - verify(accountsManager).getByServiceIdentifier(serviceIdentifier); - assertEquals(expectedResponse, response); - } - - @Test - void getUnversionedProfileGroupSendEndorsement() throws Exception { - final UUID targetUuid = UUID.randomUUID(); - final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(targetUuid); - - // Expiration must be on a day boundary; we want one in the future - final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS); - final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration); - - final ECKeyPair identityKeyPair = ECKeyPair.generate(); - final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey()); - - final List badges = List.of(new Badge( - "TEST", - "other", - "Test Badge", - "This badge is in unit tests.", - List.of("l", "m", "h", "x", "xx", "xxx"), - "SVG", - List.of( - new BadgeSvg("sl", "sd"), - new BadgeSvg("ml", "md"), - new BadgeSvg("ll", "ld"))) - ); - - when(account.getBadges()).thenReturn(Collections.emptyList()); - when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges); - when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false); - when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey); - when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account)); - - final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder() - .setGroupSendToken(ByteString.copyFrom(token)) - .setRequest(GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier( - GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier)) - .build()) - .build(); - - final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request); - - final GetUnversionedProfileResult expectedResult = GetUnversionedProfileResult.newBuilder() - .setIdentityKey(ByteString.copyFrom(identityKey.serialize())) - .setUnrestrictedUnidentifiedAccess(false) - .addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account)) - .addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList()) - .build(); - - verify(accountsManager).getByServiceIdentifier(serviceIdentifier); - assertTrue(response.hasResult()); - assertEquals(expectedResult, response.getResult()); - } - - @Test - void getUnversionedProfileNoAuth() { - final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder() - .setRequest(GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID())))) - .build(); - - assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getUnversionedProfile(request)); - } - - @ParameterizedTest - @MethodSource - void getUnversionedProfileIncorrectUnidentifiedAccessKey(final IdentityType identityType, final boolean wrongUnidentifiedAccessKey, final boolean accountNotFound) { - final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); - - when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); - when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false); - when(accountsManager.getByServiceIdentifier(any())).thenReturn( - accountNotFound ? Optional.empty() : Optional.of(account)); - - final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder() - .setUnidentifiedAccessKey( - ByteString.copyFrom(wrongUnidentifiedAccessKey - ? new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH] - : unidentifiedAccessKey)) - .setRequest(GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(identityType) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))))) - .build(); - - 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() { - return Stream.of( - Arguments.of(IdentityType.IDENTITY_TYPE_PNI, false, false), - Arguments.of(IdentityType.IDENTITY_TYPE_ACI, true, false), - Arguments.of(IdentityType.IDENTITY_TYPE_ACI, false, true) - ); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void getUnversionedProfileExpiredGroupSendEndorsement(final boolean accountNotFound) throws Exception { - final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); - when(accountsManager.getByServiceIdentifier(serviceIdentifier)) - .thenReturn(accountNotFound ? Optional.empty() : Optional.of(mock(Account.class))); - - // Expirations must be on a day boundary; pick one in the recent past - final Instant expiration = Instant.now().truncatedTo(ChronoUnit.DAYS); - final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration); - - final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder() - .setGroupSendToken(ByteString.copyFrom(token)) - .setRequest(GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier( - GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))) - .build(); - - final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile( - request); - - assertTrue(response.hasFailedUnidentifiedAuthorization()); - } - - @Test - void getUnversionedProfileIncorrectGroupSendEndorsement() throws Exception { - final AciServiceIdentifier targetServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); - final AciServiceIdentifier authorizedServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); - - // Expiration must be on a day boundary; we want one in the future - final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS); - final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(authorizedServiceIdentifier), expiration); - - when(accountsManager.getByServiceIdentifier(any())).thenReturn( - Optional.of(mock(Account.class))); - final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder() - .setGroupSendToken(ByteString.copyFrom(token)) - .setRequest(GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier( - GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(targetServiceIdentifier))) - .build(); - - final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request); - - assertTrue(response.hasFailedUnidentifiedAuthorization()); - } - - @Test - void getUnversionedProfileGroupSendEndorsementAccountNotFound() throws Exception { - final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); - - // Expiration must be on a day boundary; we want one in the future - final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS); - final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration); - - when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty()); - final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder() - .setGroupSendToken(ByteString.copyFrom(token)) - .setRequest(GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))) - .build(); - - final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile( - request); - - assertTrue(response.hasNotFound()); - } @ParameterizedTest @MethodSource void getVersionedProfile(final byte[] requestVersion, @Nullable final byte[] accountVersion, final boolean expectResponseHasPaymentAddress, - final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception { + final GetProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception { final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); + final ECKeyPair identityKeyPair = ECKeyPair.generate(); + final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey()); final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); + final List badgeIds = List.of("TEST-BADGE"); final byte[] name = TestRandomUtil.nextBytes(81); final byte[] emoji = TestRandomUtil.nextBytes(60); @@ -418,17 +184,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest { final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS); @@ -438,26 +205,26 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)); } - final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile( - requestBuilder.build()); + final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(requestBuilder.build()); - 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)) - ); + final LegacyProfileResult.Builder expectedResultBuilder = LegacyProfileResult.newBuilder() + .setName(ByteString.copyFrom(name)) + .setAbout(ByteString.copyFrom(about)) + .setAboutEmoji(ByteString.copyFrom(emoji)) + .setAvatar(avatar) + .setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing)) + .setAccountInfo(AccountInfo.newBuilder() + .addAllBadgeIds(badgeIds) + .setIdentityKey(ByteString.copyFrom(identityKey.serialize())) + .setUnrestrictedUnidentifiedAccess(false) + .setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))); if (expectResponseHasPaymentAddress) { - expectedResultBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder() - .setData(ByteString.copyFrom(paymentAddress)) - .setEtagSha256(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress))) - .build()); + expectedResultBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress)); } - assertEquals(expectedResultBuilder.build(), response.getResult()); + assertTrue(response.hasProfileV1()); + assertEquals(expectedResultBuilder.build(), response.getProfileV1()); } private static Collection getVersionedProfile() { @@ -465,22 +232,26 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest badgeIds = List.of("TEST-BADGE"); + final byte[] data = TestRandomUtil.nextBytes(128); final byte[] paymentAddress = TestRandomUtil.nextBytes(582); final byte[] commitment = TestRandomUtil.nextBytes(97); @@ -488,19 +259,21 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest { final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS); @@ -510,24 +283,31 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)); } - final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()); - assertTrue(response.hasResult()); + final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(requestBuilder.build()); + assertTrue(response.hasProfile()); - final GetVersionedProfileResult result = response.getResult(); - assertTrue(result.hasDataEtag()); - assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData()); - assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtagSha256()); - assertTrue(result.hasPaymentAddressDataEtag()); - assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData()); - assertEquals(ByteString.copyFrom(Objects.requireNonNull(v2Profile.paymentAddressHash())), result.getPaymentAddressDataEtag().getEtagSha256()); - assertFalse(result.getDataEtagMatched()); - assertFalse(result.getPaymentAddressEtagMatched()); - assertFalse(result.hasV1Response()); + final ProfileResult.Builder expectedBuilder = ProfileResult.newBuilder() + .setData(ByteString.copyFrom(data)) + .setPaymentAddress(ByteString.copyFrom(paymentAddress)) + .setAccountInfo(AccountInfo.newBuilder() + .addAllBadgeIds(badgeIds) + .setIdentityKey(ByteString.copyFrom(identityKey.serialize())) + .setUnrestrictedUnidentifiedAccess(true) + .setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))); + expectedBuilder.setEtag(ByteString.copyFrom(ProfileGrpcHelper.etag(expectedBuilder))); + + final ProfileResult result = response.getProfile(); + assertEquals(expectedBuilder.build(), result); } @Test void getVersionedProfileV2EtagMatched() { - final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); + final ECKeyPair identityKeyPair = ECKeyPair.generate(); + final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey()); + final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes( + UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); + final List badgeIds = List.of("TEST-BADGE"); + final byte[] data = TestRandomUtil.nextBytes(128); final byte[] paymentAddress = TestRandomUtil.nextBytes(582); final byte[] commitment = TestRandomUtil.nextBytes(97); @@ -535,39 +315,40 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey)); } - final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()); + final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(requestBuilder.build()); switch (authenticationCase) { case GROUP_SEND_TOKEN -> assertTrue(response.hasNotFound()); @@ -636,9 +417,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest unauthenticatedServiceStub().getVersionedProfile(request)); + assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getProfile(request)); } @Test void getVersionedProfileNoAuth() { - final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder() - .setRequest(GetVersionedProfileRequest.newBuilder() + final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder() + .setRequest(GetProfileRequest.newBuilder() .setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID())))) .build(); //noinspection ThrowableNotThrown - assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request)); + assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getProfile(request)); } @Test @@ -670,9 +451,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest etagTestVectors() { + // Expected values of the etag calculation for example profile data sets. A failure here indicates a potential + // backwards compatability issue. + return Stream.of( + Arguments.argumentSet("empty", ProfileResult.newBuilder().setAccountInfo(AccountInfo.getDefaultInstance()).build(), "6NXrB3FC907RoA=="), + Arguments.argumentSet("all fields set", profile().build(), "zrvx5cC+UDrLzQ=="), + Arguments.argumentSet("collection ordering", ProfileResult.newBuilder().setAccountInfo(AccountInfo.newBuilder() + .addBadgeIds("badgeZ").addBadgeIds("badgeQ").addBadgeIds("badgeQQ")) + .build() , "AS2DN9M/IapIgA=="), + Arguments.argumentSet("data only", ProfileResult.newBuilder().setData(ByteString.fromHex("abcde123")).build(), "ZKDfIrGEKT1+Sw=="), + Arguments.argumentSet("payment address only", ProfileResult.newBuilder().setPaymentAddress(ByteString.fromHex("abcde123")).build(), "5CWKoXAq1/cuAg==") + ); + } + + @ParameterizedTest + @MethodSource + void etagTestVectors(final ProfileResult profile, final String expectedEtagB64) { + final byte[] etag = ProfileGrpcHelper.etag(profile); + final byte[] expectedEtag = Base64.getDecoder().decode(expectedEtagB64); + + assertEquals(10, etag.length); + assertArrayEquals(expectedEtag, etag); + } + + @Test + void etagIgnoresBadgeOrdering() { + final byte[] ascending = ProfileGrpcHelper.etag(ProfileResult.newBuilder() + .setAccountInfo(AccountInfo.newBuilder() + .addBadgeIds("badge-a") + .addBadgeIds("badge-b")) + .build()); + + final byte[] descending = ProfileGrpcHelper.etag(ProfileResult.newBuilder() + .setAccountInfo(AccountInfo.newBuilder() + .addBadgeIds("badge-b") + .addBadgeIds("badge-a")) + .build()); + + assertArrayEquals(ascending, descending); + } + + @Test + void etagIgnoresEtag() { + final ProfileResult profile = profile().build(); + final byte[] etag = ProfileGrpcHelper.etag(profile); + final ProfileResult withEtagSet = profile.toBuilder().setEtag(ByteString.copyFrom(etag)).build(); + + assertArrayEquals(etag, ProfileGrpcHelper.etag(withEtagSet)); + } + + @Test + void absentAndEmptyHaveSameEtag() { + final byte[] unset = ProfileGrpcHelper.etag(ProfileResult.newBuilder().build()); + final byte[] explicitlyEmpty = ProfileGrpcHelper.etag(ProfileResult.newBuilder() + .setData(ByteString.EMPTY) + .setPaymentAddress(ByteString.EMPTY) + .setAccountInfo(AccountInfo.newBuilder() + .setIdentityKey(ByteString.EMPTY) + .setUnidentifiedAccessKeyFingerprint(ByteString.EMPTY) + .addAllBadgeIds(Collections.emptyList())) + .build()); + + assertArrayEquals(unset, explicitlyEmpty); + } + + private static ProfileResult.Builder profile() { + return ProfileResult.newBuilder() + .setData(ByteString.copyFromUtf8("profile-data")) + .setPaymentAddress(ByteString.copyFromUtf8("payment-address")) + .setAccountInfo(AccountInfo.newBuilder() + .setIdentityKey(ByteString.copyFromUtf8("identity-key")) + .setUnidentifiedAccessKeyFingerprint(ByteString.copyFromUtf8("uak-checksum")) + .setUnrestrictedUnidentifiedAccess(true) + .addBadgeIds("badge-a") + .addBadgeIds("badge-b")); + } + +} 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 fe90bd993..f3cce5642 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java @@ -8,11 +8,10 @@ package org.whispersystems.textsecuregcm.grpc; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -52,24 +51,20 @@ import javax.annotation.Nullable; 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.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; 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.DataEtag; import org.signal.chat.profile.GetAvatarCredentialsRequest; import org.signal.chat.profile.GetAvatarCredentialsResponse; -import org.signal.chat.profile.GetUnversionedProfileRequest; -import org.signal.chat.profile.GetUnversionedProfileResponse; -import org.signal.chat.profile.GetUnversionedProfileResult; -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.GetProfileRequest; +import org.signal.chat.profile.GetProfileResponse; +import org.signal.chat.profile.LegacyProfileResult; import org.signal.chat.profile.ProfileGrpc; +import org.signal.chat.profile.ProfileResult; +import org.signal.chat.profile.AccountInfo; import org.signal.chat.profile.SetProfileRequest; import org.signal.chat.profile.SetProfileResponse; import org.signal.chat.profile.SetProfileResult; @@ -93,11 +88,8 @@ import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration; import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPaymentsConfiguration; -import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; -import org.whispersystems.textsecuregcm.entities.Badge; import org.whispersystems.textsecuregcm.entities.BadgeSvg; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.limits.RateLimiter; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator; @@ -610,107 +602,13 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest badgeIds = List.of("TEST-BADGE"); - final List badges = List.of(new Badge( - "TEST", - "other", - "Test Badge", - "This badge is in unit tests.", - List.of("l", "m", "h", "x", "xx", "xxx"), - "SVG", - List.of( - new BadgeSvg("sl", "sd"), - new BadgeSvg("ml", "md"), - new BadgeSvg("ll", "ld"))) - ); - - when(account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType))).thenReturn(identityKey); - when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true); - when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); - when(account.getBadges()).thenReturn(Collections.emptyList()); - when(account.hasCapability(any())).thenReturn(false); - when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges); - when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account)); - - final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request); - - final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey); - final GetUnversionedProfileResult prototypeExpectedResult = GetUnversionedProfileResult.newBuilder() - .setIdentityKey(ByteString.copyFrom(identityKey.serialize())) - .setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum)) - .setUnrestrictedUnidentifiedAccess(true) - .addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList()) - .build(); - - final GetUnversionedProfileResult expectedResponse; - if (identityType == IdentityType.IDENTITY_TYPE_PNI) { - expectedResponse = GetUnversionedProfileResult.newBuilder(prototypeExpectedResult) - .clearUnidentifiedAccess() - .clearBadges() - .setUnrestrictedUnidentifiedAccess(false) - .build(); - } else { - expectedResponse = prototypeExpectedResult; - } - - verify(rateLimiter).validate(AUTHENTICATED_ACI); - verify(accountsManager).getByServiceIdentifier(targetIdentifier); - - assertTrue(response.hasResult()); - assertEquals(expectedResponse, response.getResult()); - } - - @Test - void getUnversionedProfileTargetAccountNotFound() { - when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty()); - - final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) - .build()) - .build(); - - final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request); - assertTrue(response.hasNotFound()); - } - - @ParameterizedTest - @EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"}) - void getUnversionedProfileRatelimited(final IdentityType identityType) throws Exception { - final Duration retryAfterDuration = Duration.ofMinutes(7); - when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account)); - doThrow(new RateLimitExceededException(retryAfterDuration)) - .when(rateLimiter).validate(any(UUID.class)); - - final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder() - .setServiceIdentifier(ServiceIdentifier.newBuilder() - .setIdentityType(identityType) - .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) - .build()) - .build(); - - assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getUnversionedProfile(request), accountsManager); - } - - @ParameterizedTest - @MethodSource - void getVersionedProfile(final byte[] requestVersion, @Nullable final byte[] accountVersion, final boolean expectResponseHasPaymentAddress) { final byte[] name = TestRandomUtil.nextBytes(81); final byte[] emoji = TestRandomUtil.nextBytes(60); final byte[] about = TestRandomUtil.nextBytes(156); @@ -721,7 +619,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() + final GetProfileRequest request = GetProfileRequest.newBuilder() .setAccountIdentifier(ServiceIdentifier.newBuilder() .setIdentityType(IdentityType.IDENTITY_TYPE_ACI) .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) @@ -733,29 +631,35 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest getVersionedProfile() { + + private static Collection getProfile() { final byte[] version1 = TestRandomUtil.nextBytes(32); final byte[] version2 = TestRandomUtil.nextBytes(32); return List.of( @@ -766,7 +670,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest badgeIds = List.of("TEST-BADGE"); + final byte[] data = TestRandomUtil.nextBytes(128); final byte[] paymentAddress = TestRandomUtil.nextBytes(582); final byte[] commitment = TestRandomUtil.nextBytes(97); @@ -775,17 +684,21 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest badgeIds = List.of("TEST-BADGE"); + final byte[] data = TestRandomUtil.nextBytes(128); final byte[] paymentAddress = TestRandomUtil.nextBytes(582); final byte[] commitment = TestRandomUtil.nextBytes(97); @@ -817,44 +737,48 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest getVersionedProfileAccountOrProfileNotFound() { + private static Stream getProfileAccountOrProfileNotFound() { return Stream.of( Arguments.of(true, false), Arguments.of(false, true) @@ -876,10 +800,10 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getVersionedProfile(request), accountsManager, profilesManager); + assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getProfile(request), accountsManager, profilesManager); } @Test - void getVersionedProfilePniInvalidArgument() { - final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder() + void getProfilePniInvalidArgument() { + final GetProfileRequest request = GetProfileRequest.newBuilder() .setAccountIdentifier(ServiceIdentifier.newBuilder() .setIdentityType(IdentityType.IDENTITY_TYPE_PNI) .setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID()))) @@ -900,7 +824,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getVersionedProfile(request)); + assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getProfile(request)); } @Test