Drop unversioned profiles from grpc service

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-07-14 16:06:31 -05:00
1 parent 5147fe57f2
commit ed90c1c15c
15 files changed
+708 -859

No files matched your search

+6
View File
@@ -572,6 +572,12 @@
<artifactId>google-auth-library-oauth2-http</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
@@ -65,6 +65,21 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
false);
}
@Override
public List<String> visibleBadgeIds(final List<AccountBadge> 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<Badge> convert(
final List<Locale> acceptableLanguages,
@@ -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<String> visibleBadgeIds(final List<AccountBadge> badges);
/**
* Converts the {@link AccountBadge}s for an account into the objects
* that can be returned on a profile fetch.
@@ -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();
@@ -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<Account> 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<Account> 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
@@ -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<GetVersionedProfileResult> getVersionedProfile(final Account account,
static Optional<LegacyProfileResult> getProfileV1(final Account account,
final ProfilesManager profilesManager,
final byte[] requestVersion,
final byte[] requestDataEtag,
final byte[] requestPaymentAddressEtag) {
final Optional<VersionedProfile> profile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
profile = profilesManager.get(account.getUuid(), requestVersion);
} else {
profile = Optional.empty();
}
final Optional<VersionedProfileV1> v1Profile;
if (profile.isEmpty()) {
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
} else {
v1Profile = Optional.empty();
}
if (profile.isEmpty() && v1Profile.isEmpty()) {
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfileV1> 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<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
if (paymentAddress.isPresent()) {
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
profile.map(VersionedProfile::paymentAddressHash)
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
.orElse(false);
if (paymentAddressETagMatches) {
responseBuilder.setPaymentAddressEtagMatched(true);
} else {
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress.get()))
.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<org.signal.chat.common.DeviceCapability> 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<Locale> acceptedLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
final List<Badge> 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<ProfileResult> getProfile(final Account account,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfile> 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> 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.
* <p>
* 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());
}
}
@@ -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<Account> 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<Account> maybeAccount =
validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Optional<Account> 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<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
@@ -146,6 +146,15 @@ message AccountPreKeyBundles {
// A map of device IDs to pre-key "bundles" for the targeted account.
map<uint32, DevicePreKeyBundle> 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 {
@@ -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 {
@@ -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<String> visibleBadgeIds(final List<AccountBadge> badges) {
return List.of("TEST");
}
@Override
public List<Badge> convert(final List<Locale> acceptableLanguages, final List<AccountBadge> 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"))),
@@ -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<KeysAnonymousGrpcS
final GetPreKeysAnonymousResponse expectedResponse = GetPreKeysAnonymousResponse.newBuilder()
.setPreKeys(AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
@@ -182,6 +184,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final GetPreKeysAnonymousResponse expectedResponse = GetPreKeysAnonymousResponse.newBuilder()
.setPreKeys(AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
@@ -235,6 +238,8 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final GetPreKeysAnonymousResponse expectedResponse = GetPreKeysAnonymousResponse.newBuilder()
.setPreKeys(AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))
.setUnrestrictedUnidentifiedAccess(true)
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
@@ -5,7 +5,9 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -56,6 +58,8 @@ import org.signal.chat.keys.SetOneTimeEcPreKeysRequest;
import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -68,9 +72,11 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
@@ -643,4 +649,68 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
assertRateLimitExceeded(retryAfterDuration, () -> 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<ECPreKey> 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<Byte, Device> 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());
}
}
}
@@ -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<ProfileA
);
}
@Test
void getUnversionedProfileUnidentifiedAccessKey() {
final UUID targetUuid = UUID.randomUUID();
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(targetUuid);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final List<Badge> 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<Badge> 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<Arguments> 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<String> 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<ProfileA
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
final GetProfileAnonymousRequest.Builder requestBuilder = GetProfileAnonymousRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(requestVersion))
.build());
.setVersion(ByteString.copyFrom(requestVersion)));
switch (authenticationCase) {
case GROUP_SEND_TOKEN -> {
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
@@ -438,26 +205,26 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
case UNIDENTIFIED_ACCESS_KEY -> 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<Arguments> getVersionedProfile() {
@@ -465,22 +232,26 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final byte[] version2 = TestRandomUtil.nextBytes(32);
return List.of(
Arguments.argumentSet("current profile version matches, unidentified access key auth", version1, version1, true,
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
GetProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version absent, unidentified access key auth",version1, null, true,
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
GetProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version mismatch, unidentified access key auth",version1, version2, false,
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
GetProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version matches, group send endorsement auth", version1, version1, true,
GetVersionedProfileAnonymousRequest.AuthenticationCase.GROUP_SEND_TOKEN)
GetProfileAnonymousRequest.AuthenticationCase.GROUP_SEND_TOKEN)
);
}
@ParameterizedTest
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
void getVersionedProfileV2(
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<String> 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<ProfileA
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
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.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
final GetProfileAnonymousRequest.Builder requestBuilder = GetProfileAnonymousRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(version))
.build());
.setVersion(ByteString.copyFrom(version)));
switch (authenticationCase) {
case GROUP_SEND_TOKEN -> {
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
@@ -510,24 +283,31 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
case UNIDENTIFIED_ACCESS_KEY -> 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<String> 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<ProfileA
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
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()));
final byte[] expectedEtag = ProfileGrpcHelper.etag(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)))));
if (v2Profile.paymentAddressHash() != null) {
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
}
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(builder.build())
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(ByteString.copyFrom(version))
.setEtag(ByteString.copyFrom(expectedEtag)))
.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());
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(request);
assertTrue(response.hasEtagMatched());
assertTrue(response.getEtagMatched());
}
@Test
@@ -580,9 +361,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -591,7 +372,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(
request);
assertTrue(response.hasNotFound());
@@ -600,7 +381,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@ParameterizedTest
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
void getVersionedProfileAccountNotFound(
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase
final GetProfileAnonymousRequest.AuthenticationCase authenticationCase
) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
@@ -609,8 +390,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
final GetProfileAnonymousRequest.Builder requestBuilder = GetProfileAnonymousRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build());
@@ -624,7 +405,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
case UNIDENTIFIED_ACCESS_KEY -> 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<ProfileA
void getVersionedProfilePniInvalidArgument() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -648,18 +429,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build();
//noinspection ThrowableNotThrown
assertStatusException(Status.INVALID_ARGUMENT, () -> 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<ProfileA
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -681,7 +462,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
@@ -700,16 +481,16 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS,
List.of(wrongIdentifier ? wrongServiceIdentifier : serviceIdentifier), expiration);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
@@ -0,0 +1,101 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.protobuf.ByteString;
import java.util.Base64;
import java.util.Collections;
import java.util.stream.Stream;
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.signal.chat.common.DeviceCapability;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.AccountInfo;
class ProfileGrpcHelperTest {
public static Stream<Arguments> 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"));
}
}
@@ -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<ProfileGrpcServic
}
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"})
void getUnversionedProfile(final IdentityType identityType) throws Exception {
final UUID targetUuid = UUID.randomUUID();
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier targetIdentifier =
identityType == IdentityType.IDENTITY_TYPE_ACI ? new AciServiceIdentifier(targetUuid) : new PniServiceIdentifier(targetUuid);
final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(identityType)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.build();
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
@MethodSource
void getProfile(final byte[] requestVersion, @Nullable final byte[] accountVersion, final boolean expectResponseHasPaymentAddress) {
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> badgeIds = List.of("TEST-BADGE");
final List<Badge> 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<ProfileGrpcServic
final Optional<VersionedProfileV1> 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<ProfileGrpcServic
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).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.visibleBadgeIds(anyList())).thenReturn(badgeIds);
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());
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
final LegacyProfileResult.Builder expectedV1ResponseBuilder = 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(true)
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey))));
if (expectResponseHasPaymentAddress) {
expectedResultBuilder.setPaymentAddressDataEtag(
DataEtag.newBuilder().setData(ByteString.copyFrom(paymentAddress))
.setEtagSha256(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress)))
.build());
expectedV1ResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
}
assertTrue(response.hasResult());
assertEquals(expectedResultBuilder.build(), response.getResult());
assertTrue(response.hasLegacyProfile());
assertEquals(expectedV1ResponseBuilder.build(), response.getLegacyProfile());
}
private static Collection<Arguments> getVersionedProfile() {
private static Collection<Arguments> 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<ProfileGrpcServic
}
@Test
void getVersionedProfileV2() {
void getProfileV2() {
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> 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<ProfileGrpcServic
final UUID targetAci = UUID.randomUUID();
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
final Account targetAccount = mock(Account.class);
when(account.getUuid()).thenReturn(targetAci);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci)))
.thenReturn(Optional.of(targetAccount));
when(targetAccount.getUuid()).thenReturn(targetAci);
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
.thenReturn(Optional.of(account));
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(profilesManager.get(eq(targetAci), aryEq(version))).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
final GetProfileRequest request = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci)))
@@ -793,23 +706,30 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setVersion(ByteString.copyFrom(version))
.build();
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
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(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)));
assertTrue(response.hasProfile());
final ProfileResult result = response.getProfile();
assertEquals(expectedBuilder.build(), result);
}
@Test
void getVersionedProfileV2EtagMatched() {
void getProfileV2EtagMatched() {
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> 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<ProfileGrpcServic
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(account.getUuid()).thenReturn(targetAci);
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(account));
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(profilesManager.get(targetAci, version)).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder()
final byte[] expectedEtag = ProfileGrpcHelper.etag(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)))));
final GetProfileRequest.Builder builder = GetProfileRequest.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()));
.setEtag(ByteString.copyFrom(expectedEtag));
if (v2Profile.paymentAddressHash() != null) {
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
}
final GetProfileRequest request = builder.build();
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());
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
assertTrue(response.hasEtagMatched());
assertTrue(response.getEtagMatched());
}
@ParameterizedTest
@MethodSource
void getVersionedProfileAccountOrProfileNotFound(final boolean missingAccount, final boolean missingProfile) {
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
void getProfileAccountOrProfileNotFound(final boolean missingAccount, final boolean missingProfile) {
final GetProfileRequest request = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -864,11 +788,11 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(accountsManager.getByServiceIdentifier(any())).thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
assertTrue(response.hasNotFound());
}
private static Stream<Arguments> getVersionedProfileAccountOrProfileNotFound() {
private static Stream<Arguments> getProfileAccountOrProfileNotFound() {
return Stream.of(
Arguments.of(true, false),
Arguments.of(false, true)
@@ -876,10 +800,10 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
}
@Test
void getVersionedProfileRatelimited() {
void getProfileRatelimited() {
final Duration retryAfterDuration = MockUtils.updateRateLimiterResponseToFail(rateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(7));
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())))
@@ -887,12 +811,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build();
assertRateLimitExceeded(retryAfterDuration, () -> 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<ProfileGrpcServic
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getProfile(request));
}
@Test