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

@@ -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