mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 11:46:53 +00:00
Profiles gRPC: initial v2 implementation
This commit is contained in:
1 parent
1b11c3efc2
commit
1e3b2c8ce8
38 files changed
+3163
-1063
No files matched your search
+56
-56
@@ -106,7 +106,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
|
||||
@@ -232,8 +232,8 @@ class ProfileControllerTest {
|
||||
final byte[] about = TestRandomUtil.nextBytes(156);
|
||||
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
|
||||
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty());
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfile(
|
||||
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")))).thenReturn(Optional.empty());
|
||||
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")))).thenReturn(Optional.of(new VersionedProfileV1(
|
||||
versionHex("validversion"), name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes())));
|
||||
|
||||
when(profilesManager.deleteAvatar(anyString())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -467,10 +467,10 @@ class ProfileControllerTest {
|
||||
name, null, null,
|
||||
null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(versionHex("someversion")));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
|
||||
|
||||
verifyNoMoreInteractions(profilesManager);
|
||||
|
||||
@@ -516,10 +516,10 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion")));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("anotherversion")));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
|
||||
verifyNoMoreInteractions(profilesManager);
|
||||
|
||||
@@ -546,10 +546,10 @@ class ProfileControllerTest {
|
||||
name, null, null,
|
||||
null, true, false, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar");
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
@@ -575,10 +575,10 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar"));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
@@ -605,10 +605,10 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, never()).deleteAvatar(anyString());
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
@@ -633,10 +633,10 @@ class ProfileControllerTest {
|
||||
null, null,
|
||||
null, false, true, Optional.of(List.of()), null), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(versionHex("validversion")));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).deleteAvatar(eq("profiles/validavatar"));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
@@ -663,10 +663,10 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID), eq(version));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID), eq(version));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, never()).deleteAvatar(anyString());
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
@@ -694,10 +694,10 @@ class ProfileControllerTest {
|
||||
null, null, null, true, false, Optional.of(List.of()), null),
|
||||
MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).deleteAvatar("profiles/validavatar");
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
@@ -731,14 +731,14 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
|
||||
verifyNoMoreInteractions(profilesManager);
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
|
||||
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo(version);
|
||||
@@ -771,14 +771,14 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
|
||||
verifyNoMoreInteractions(profilesManager);
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
|
||||
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo(version);
|
||||
@@ -813,7 +813,7 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
verify(profilesManager, never()).set(any(), any());
|
||||
verify(profilesManager, never()).setV1(any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -831,9 +831,9 @@ class ProfileControllerTest {
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any()))
|
||||
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), any()))
|
||||
.thenReturn(Optional.of(
|
||||
new VersionedProfile("1", name, null, null, null,
|
||||
new VersionedProfileV1("1", name, null, null, null,
|
||||
existingPaymentAddressOnProfile ? TestRandomUtil.nextBytes(582) : null,
|
||||
phoneNumberSharing,
|
||||
commitment.serialize())));
|
||||
@@ -852,14 +852,14 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
|
||||
verifyNoMoreInteractions(profilesManager);
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
final VersionedProfileV1 profile = profileArgumentCaptor.getValue();
|
||||
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo(version);
|
||||
@@ -871,7 +871,7 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
verify(profilesManager, never()).set(any(), any());
|
||||
verify(profilesManager, never()).setV1(any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -895,10 +895,10 @@ class ProfileControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
final ArgumentCaptor<VersionedProfileV1> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(profilesManager, times(1)).getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version));
|
||||
verify(profilesManager, times(1)).setV1(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
|
||||
verifyNoMoreInteractions(profilesManager);
|
||||
|
||||
@@ -919,7 +919,7 @@ class ProfileControllerTest {
|
||||
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
|
||||
|
||||
final String version = versionHex("validversion");
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfile(
|
||||
when(profilesManager.getV1(eq(AuthHelper.VALID_UUID_TWO), eq(version))).thenReturn(Optional.of(new VersionedProfileV1(
|
||||
version, name, "profiles/validavatar", emoji, about, null, phoneNumberSharing, "validcommitment".getBytes())));
|
||||
|
||||
final VersionedProfileResponse profile = resources.getJerseyTest()
|
||||
@@ -970,8 +970,8 @@ class ProfileControllerTest {
|
||||
void testGetProfileReturnsNoPaymentAddressIfCurrentVersionMismatch() {
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final String version = versionHex("validversion");
|
||||
when(profilesManager.get(AuthHelper.VALID_UUID_TWO, version)).thenReturn(
|
||||
Optional.of(new VersionedProfile(null, null, null, null, null, paymentAddress, null, null)));
|
||||
when(profilesManager.getV1(AuthHelper.VALID_UUID_TWO, version)).thenReturn(
|
||||
Optional.of(new VersionedProfileV1(version, null, null, null, null, paymentAddress, null, null)));
|
||||
|
||||
{
|
||||
final VersionedProfileResponse profile = resources.getJerseyTest()
|
||||
@@ -1016,7 +1016,7 @@ class ProfileControllerTest {
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("version")));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.empty());
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final ExpiringProfileKeyCredentialProfileResponse profile = resources.getJerseyTest()
|
||||
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, versionHex("version-that-does-not-exist"), "credential-request"))
|
||||
@@ -1211,7 +1211,7 @@ class ProfileControllerTest {
|
||||
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
|
||||
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
|
||||
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
|
||||
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
|
||||
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
@@ -1233,7 +1233,7 @@ class ProfileControllerTest {
|
||||
serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(AuthHelper.VALID_UUID), profileKeyCommitment, expiration);
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
|
||||
when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
|
||||
when(zkProfileOperations.issueExpiringProfileKeyCredential(eq(credentialRequest), eq(new ServiceId.Aci(AuthHelper.VALID_UUID)), eq(profileKeyCommitment), any()))
|
||||
.thenReturn(credentialResponse);
|
||||
|
||||
@@ -1279,7 +1279,7 @@ class ProfileControllerTest {
|
||||
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
|
||||
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
|
||||
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
|
||||
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
|
||||
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
@@ -1294,7 +1294,7 @@ class ProfileControllerTest {
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
|
||||
when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
|
||||
when(zkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any()))
|
||||
.thenThrow(new VerificationFailedException());
|
||||
|
||||
@@ -1324,7 +1324,7 @@ class ProfileControllerTest {
|
||||
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
|
||||
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
|
||||
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
|
||||
final VersionedProfileV1 versionedProfile = mock(VersionedProfileV1.class);
|
||||
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
final String avatar = "avatar";
|
||||
when(versionedProfile.avatar()).thenReturn(avatar);
|
||||
@@ -1341,7 +1341,7 @@ class ProfileControllerTest {
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex("the-current-version")));
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
|
||||
when(profilesManager.getV1(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, version,
|
||||
|
||||
@@ -10,23 +10,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
import com.google.protobuf.Any;
|
||||
import com.google.protobuf.Message;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import com.google.rpc.RetryInfo;
|
||||
import io.grpc.BindableService;
|
||||
import io.grpc.ServerInterceptors;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusException;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
|
||||
public final class GrpcTestUtils {
|
||||
|
||||
@@ -34,9 +26,11 @@ public final class GrpcTestUtils {
|
||||
// noop
|
||||
}
|
||||
|
||||
public static void assertStatusException(final Status expected, final Executable serviceCall) {
|
||||
public static StatusRuntimeException assertStatusException(final Status expected, final Executable serviceCall) {
|
||||
final StatusRuntimeException exception = Assertions.assertThrows(StatusRuntimeException.class, serviceCall);
|
||||
assertEquals(expected.getCode(), exception.getStatus().getCode());
|
||||
|
||||
return exception;
|
||||
}
|
||||
|
||||
public static void assertStatusException(final Status expected, final String expectedReason, final Executable serviceCall) {
|
||||
@@ -45,16 +39,16 @@ public final class GrpcTestUtils {
|
||||
assertEquals(expectedReason, extractErrorInfo(exception).getReason());
|
||||
}
|
||||
|
||||
public static void assertStatusInvalidArgument(final Executable serviceCall) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
|
||||
public static StatusRuntimeException assertStatusInvalidArgument(final Executable serviceCall) {
|
||||
return assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
|
||||
}
|
||||
|
||||
public static void assertStatusUnauthenticated(final Executable serviceCall) {
|
||||
assertStatusException(Status.UNAUTHENTICATED, serviceCall);
|
||||
public static StatusRuntimeException assertStatusUnauthenticated(final Executable serviceCall) {
|
||||
return assertStatusException(Status.UNAUTHENTICATED, serviceCall);
|
||||
}
|
||||
|
||||
public static void assertStatusPermissionDenied(final Executable serviceCall) {
|
||||
assertStatusException(Status.PERMISSION_DENIED, serviceCall);
|
||||
public static StatusRuntimeException assertStatusPermissionDenied(final Executable serviceCall) {
|
||||
return assertStatusException(Status.PERMISSION_DENIED, serviceCall);
|
||||
}
|
||||
|
||||
public static void assertRateLimitExceeded(
|
||||
@@ -68,8 +62,8 @@ public final class GrpcTestUtils {
|
||||
final ErrorInfo errorInfo = extractErrorInfo(exception);
|
||||
final RetryInfo retryInfo = extractDetail(RetryInfo.class, exception);
|
||||
final Duration actual = Duration.ofSeconds(retryInfo.getRetryDelay().getSeconds(), retryInfo.getRetryDelay().getNanos());
|
||||
assertEquals(errorInfo.getDomain(), GrpcExceptions.DOMAIN);
|
||||
assertEquals(errorInfo.getReason(), "RESOURCE_EXHAUSTED");
|
||||
assertEquals(GrpcExceptions.DOMAIN, errorInfo.getDomain());
|
||||
assertEquals("RESOURCE_EXHAUSTED", errorInfo.getReason());
|
||||
assertEquals(expectedRetryAfter, actual);
|
||||
|
||||
for (final Object mock: mocksToCheckForNoInteraction) {
|
||||
|
||||
+281
-86
@@ -7,9 +7,16 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -20,12 +27,15 @@ import com.google.protobuf.ByteString;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
@@ -34,24 +44,28 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileV1Response;
|
||||
import org.signal.chat.profile.ProfileAnonymousGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
|
||||
@@ -60,6 +74,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
@@ -71,6 +86,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
@@ -78,7 +94,7 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileAnonymousGrpcService, ProfileAnonymousGrpc.ProfileAnonymousBlockingStub> {
|
||||
|
||||
private final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
|
||||
private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
|
||||
|
||||
@Mock
|
||||
private Account account;
|
||||
@@ -92,17 +108,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
@Mock
|
||||
private ProfileBadgeConverter profileBadgeConverter;
|
||||
|
||||
private ServerZkProfileOperations zkProfileOperations;
|
||||
|
||||
@Override
|
||||
protected ProfileAnonymousGrpcService createServiceBeforeEachTest() {
|
||||
getMockRequestAttributesInterceptor().setRequestAttributes(new RequestAttributes(InetAddresses.forString("127.0.0.1"),
|
||||
"Signal-Android/1.2.3",
|
||||
"en-us"));
|
||||
|
||||
zkProfileOperations = spy(new ServerZkProfileOperations(SERVER_SECRET_PARAMS));
|
||||
|
||||
return new ProfileAnonymousGrpcService(
|
||||
accountsManager,
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
SERVER_SECRET_PARAMS
|
||||
zkProfileOperations,
|
||||
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, Clock.systemUTC())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -134,6 +155,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
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()
|
||||
@@ -146,14 +168,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetUnversionedProfileResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
|
||||
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
|
||||
|
||||
final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey);
|
||||
final GetUnversionedProfileResponse expectedResponse = GetUnversionedProfileResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
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(ProfileGrpcHelper.buildBadges(badges))
|
||||
.build()
|
||||
)
|
||||
.build();
|
||||
|
||||
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
|
||||
@@ -199,17 +225,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetUnversionedProfileResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
|
||||
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
|
||||
|
||||
final GetUnversionedProfileResponse expectedResponse = GetUnversionedProfileResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.build();
|
||||
final GetUnversionedProfileResult expectedResult = GetUnversionedProfileResult.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.build();
|
||||
|
||||
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
|
||||
assertEquals(expectedResponse, response);
|
||||
assertTrue(response.hasResult());
|
||||
assertEquals(expectedResult, response.getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -243,7 +270,14 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))))
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
|
||||
if (IdentityType.IDENTITY_TYPE_PNI.equals(identityType)) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
|
||||
} else {
|
||||
|
||||
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
|
||||
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> getUnversionedProfileIncorrectUnidentifiedAccessKey() {
|
||||
@@ -254,9 +288,13 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUnversionedProfileExpiredGroupSendEndorsement() throws Exception {
|
||||
@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);
|
||||
@@ -268,7 +306,10 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier)))
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
|
||||
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(
|
||||
request);
|
||||
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -281,7 +322,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(authorizedServiceIdentifier), expiration);
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
|
||||
Optional.empty());
|
||||
Optional.of(mock(Account.class)));
|
||||
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
|
||||
.setGroupSendToken(ByteString.copyFrom(token))
|
||||
.setRequest(GetUnversionedProfileRequest.newBuilder()
|
||||
@@ -289,7 +330,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
ServiceIdentifierUtil.toGrpcServiceIdentifier(targetServiceIdentifier)))
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
|
||||
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
|
||||
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -307,13 +350,16 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier)))
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.NOT_FOUND, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
|
||||
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(
|
||||
request);
|
||||
|
||||
assertTrue(response.hasNotFound());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfile(final String requestVersion,
|
||||
@Nullable final String accountVersion,
|
||||
void getVersionedProfile(final byte[] requestVersion,
|
||||
@Nullable final byte[] accountVersion,
|
||||
final boolean expectResponseHasPaymentAddress) {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
@@ -324,14 +370,14 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
|
||||
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
|
||||
|
||||
final VersionedProfile profile = new VersionedProfile(accountVersion, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, new byte[0]);
|
||||
final Optional<VersionedProfileV1> profile = Optional.of(new VersionedProfileV1(HexFormat.of().formatHex(requestVersion), name, avatar, emoji, about, paymentAddress, phoneNumberSharing, new byte[0]));
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v)));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(profile);
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
@@ -340,34 +386,131 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion(requestVersion)
|
||||
.setVersion(ByteString.copyFrom(requestVersion))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
|
||||
final GetVersionedProfileResponse.Builder expectedResponseBuilder = GetVersionedProfileResponse.newBuilder()
|
||||
.setName(ByteString.copyFrom(name))
|
||||
.setAbout(ByteString.copyFrom(about))
|
||||
.setAboutEmoji(ByteString.copyFrom(emoji))
|
||||
.setAvatar(avatar)
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing));
|
||||
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
|
||||
.setV1Response(GetVersionedProfileV1Response.newBuilder()
|
||||
.setName(ByteString.copyFrom(name))
|
||||
.setAbout(ByteString.copyFrom(about))
|
||||
.setAboutEmoji(ByteString.copyFrom(emoji))
|
||||
.setAvatar(avatar)
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
|
||||
);
|
||||
|
||||
if (expectResponseHasPaymentAddress) {
|
||||
expectedResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
|
||||
expectedResultBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
|
||||
.setData(ByteString.copyFrom(paymentAddress))
|
||||
.setEtag(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress)))
|
||||
.build());
|
||||
}
|
||||
|
||||
assertEquals(expectedResponseBuilder.build(), response);
|
||||
assertEquals(expectedResultBuilder.build(), response.getResult());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> getVersionedProfile() {
|
||||
return Stream.of(
|
||||
Arguments.of("version1", "version1", true),
|
||||
Arguments.of("version1", null, true),
|
||||
Arguments.of("version1", "version2", false)
|
||||
private static Collection<Arguments> getVersionedProfile() {
|
||||
final byte[] version1 = TestRandomUtil.nextBytes(32);
|
||||
final byte[] version2 = TestRandomUtil.nextBytes(32);
|
||||
return List.of(
|
||||
Arguments.argumentSet("current profile version matches", version1, version1, true),
|
||||
Arguments.argumentSet("current profile version absent",version1, null, true),
|
||||
Arguments.argumentSet("current profile version mismatch",version1, version2, false)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileV2() {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
final byte[] data = TestRandomUtil.nextBytes(128);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
assertTrue(response.hasResult());
|
||||
|
||||
final GetVersionedProfileResult result = response.getResult();
|
||||
assertTrue(result.hasDataEtag());
|
||||
assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData());
|
||||
assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtag());
|
||||
assertTrue(result.hasPaymentAddressDataEtag());
|
||||
assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData());
|
||||
assertEquals(ByteString.copyFrom(Objects.requireNonNull(v2Profile.paymentAddressHash())), result.getPaymentAddressDataEtag().getEtag());
|
||||
assertFalse(result.getDataEtagMatched());
|
||||
assertFalse(result.getPaymentAddressEtagMatched());
|
||||
assertFalse(result.hasV1Response());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileV2EtagMatched() {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
final byte[] data = TestRandomUtil.nextBytes(128);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.setDataEtag(ByteString.copyFrom(v2Profile.dataHash()));
|
||||
|
||||
if (v2Profile.paymentAddressHash() != null) {
|
||||
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
|
||||
}
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
.setRequest(builder.build())
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
assertTrue(response.hasResult());
|
||||
|
||||
final GetVersionedProfileResult result = response.getResult();
|
||||
assertTrue(result.getDataEtagMatched());
|
||||
assertTrue(result.getPaymentAddressEtagMatched());
|
||||
assertFalse(result.hasDataEtag());
|
||||
assertFalse(result.hasPaymentAddressDataEtag());
|
||||
assertFalse(result.hasV1Response());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileVersionNotFound() {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
@@ -376,7 +519,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.empty());
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
@@ -385,17 +528,19 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.NOT_FOUND, () -> unauthenticatedServiceStub().getVersionedProfile(request));
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
|
||||
request);
|
||||
|
||||
assertTrue(response.hasNotFound());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey,
|
||||
final boolean accountNotFound) {
|
||||
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
@@ -409,14 +554,23 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build());
|
||||
|
||||
if (!missingUnidentifiedAccessKey) {
|
||||
|
||||
if (missingUnidentifiedAccessKey) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()));
|
||||
} else {
|
||||
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
|
||||
requestBuilder.build());
|
||||
|
||||
assertEquals(accountNotFound, response.hasNotFound());
|
||||
assertNotEquals(accountNotFound, response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()));
|
||||
|
||||
}
|
||||
private static Stream<Arguments> getVersionedProfileUnauthenticated() {
|
||||
return Stream.of(
|
||||
@@ -436,7 +590,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
@@ -444,7 +598,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
}
|
||||
|
||||
@Test
|
||||
void getExpiringProfileKeyCredential() throws InvalidInputException, VerificationFailedException {
|
||||
void getExpiringProfileKeyCredential() throws Exception {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
final UUID targetUuid = UUID.randomUUID();
|
||||
|
||||
@@ -456,19 +610,16 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
|
||||
|
||||
final VersionedProfile profile = mock(VersionedProfile.class);
|
||||
final VersionedProfileV1 profile = mock(VersionedProfileV1.class);
|
||||
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
|
||||
when(account.getUuid()).thenReturn(targetUuid);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
|
||||
when(profilesManager.getV1(targetUuid, HexFormat.of().formatHex(profileKeyBytes))).thenReturn(Optional.of(profile));
|
||||
|
||||
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
|
||||
|
||||
final Instant expiration = Instant.now().plus(org.whispersystems.textsecuregcm.util.ProfileHelper.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION)
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
|
||||
.setRequest(GetExpiringProfileKeyCredentialRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
@@ -477,15 +628,20 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom(credentialRequest.serialize()))
|
||||
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(profileKeyBytes))
|
||||
.build())
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
.build();
|
||||
|
||||
final GetExpiringProfileKeyCredentialResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(request);
|
||||
final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(request);
|
||||
|
||||
final Instant expectedExpiration = Instant.now().plus(org.whispersystems.textsecuregcm.util.ProfileHelper.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION)
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
verify(zkProfileOperations).issueExpiringProfileKeyCredential(eq(credentialRequest), eq(ServiceId.Aci.parseFromString(targetUuid.toString())), eq(profileKeyCommitment), eq(expectedExpiration));
|
||||
|
||||
assertThatNoException().isThrownBy(() ->
|
||||
clientZkProfile.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, new ExpiringProfileKeyCredentialResponse(response.getProfileKeyCredential().toByteArray())));
|
||||
clientZkProfile.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext,
|
||||
new ExpiringProfileKeyCredentialResponse(response.getResult().getProfileKeyCredential().toByteArray())));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -507,14 +663,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
|
||||
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build());
|
||||
|
||||
if (!missingUnidentifiedAccessKey) {
|
||||
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
}
|
||||
if (missingUnidentifiedAccessKey) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(requestBuilder.build()));
|
||||
|
||||
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(requestBuilder.build()));
|
||||
} else {
|
||||
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
|
||||
final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(
|
||||
requestBuilder.build());
|
||||
|
||||
assertEquals(missingAccount, response.hasNotFound());
|
||||
assertNotEquals(missingAccount, response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
verifyNoInteractions(profilesManager);
|
||||
}
|
||||
@@ -522,7 +686,8 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
private static Stream<Arguments> getExpiringProfileKeyCredentialUnauthenticated() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, false),
|
||||
Arguments.of(false, true)
|
||||
Arguments.of(false, true),
|
||||
Arguments.of(true, true)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -532,11 +697,15 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
final UUID targetUuid = UUID.randomUUID();
|
||||
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
|
||||
when(account.getUuid()).thenReturn(targetUuid);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(
|
||||
Optional.of(account));
|
||||
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.empty());
|
||||
when(profilesManager.getV1(targetUuid, versionHex)).thenReturn(Optional.empty());
|
||||
when(profilesManager.get(eq(targetUuid), aryEq(version))).thenReturn(Optional.empty());
|
||||
|
||||
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
@@ -547,26 +716,38 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
|
||||
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.NOT_FOUND, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(request));
|
||||
final GetExpiringProfileKeyCredentialAnonymousResponse response = unauthenticatedServiceStub().getExpiringProfileKeyCredential(
|
||||
request);
|
||||
|
||||
assertTrue(response.hasNotFound());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getExpiringProfileKeyCredentialInvalidArgument(final IdentityType identityType, final CredentialType credentialType,
|
||||
final byte[] credentialRequest,
|
||||
final boolean throwZkVerificationException) throws VerificationFailedException {
|
||||
final UUID targetUuid = UUID.randomUUID();
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
final VersionedProfile profile = mock(VersionedProfile.class);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
|
||||
final VersionedProfileV1 profile = mock(VersionedProfileV1.class);
|
||||
when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8));
|
||||
when(account.getUuid()).thenReturn(targetUuid);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
|
||||
when(profilesManager.getV1(targetUuid, versionHex)).thenReturn(Optional.of(profile));
|
||||
|
||||
if (throwZkVerificationException) {
|
||||
doThrow(VerificationFailedException.class)
|
||||
.when(zkProfileOperations).issueExpiringProfileKeyCredential(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
final GetExpiringProfileKeyCredentialAnonymousRequest request = GetExpiringProfileKeyCredentialAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
@@ -575,23 +756,37 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityType(identityType)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
|
||||
.setCredentialRequest(ByteString.copyFrom(credentialRequest))
|
||||
.setCredentialType(credentialType)
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getExpiringProfileKeyCredential(request));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> getExpiringProfileKeyCredentialInvalidArgument() {
|
||||
private static Stream<Arguments> getExpiringProfileKeyCredentialInvalidArgument() throws Exception {
|
||||
final byte[] invalidCredentialRequest = "invalidRequest".getBytes();
|
||||
|
||||
final UUID targetUuid = UUID.randomUUID();
|
||||
|
||||
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(SERVER_SECRET_PARAMS.getPublicParams());
|
||||
|
||||
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
|
||||
|
||||
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
|
||||
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid));
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
|
||||
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
|
||||
|
||||
final byte[] validCredentialRequest = credentialRequest.serialize();
|
||||
|
||||
return Stream.of(
|
||||
// Credential type unspecified
|
||||
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, false),
|
||||
// Illegal identity type
|
||||
Arguments.of(IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, false),
|
||||
// Artificially fails zero knowledge verification
|
||||
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, true)
|
||||
Arguments.argumentSet("Credential type unspecified", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, validCredentialRequest, false),
|
||||
Arguments.argumentSet("Illegal identity type", IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, validCredentialRequest, false),
|
||||
Arguments.argumentSet("Invalid credential request", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, invalidCredentialRequest, false),
|
||||
Arguments.argumentSet("ZK verification failure", IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, validCredentialRequest, true)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+359
-264
@@ -6,15 +6,15 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.ArgumentMatchers.refEq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -24,25 +24,29 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusInvalidArgument;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.rpc.BadRequest;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -55,31 +59,26 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileV1Response;
|
||||
import org.signal.chat.profile.ProfileGrpc;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.test.PlaintextProfileData;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerPublicParams;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
@@ -99,10 +98,12 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
@@ -111,10 +112,17 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcService, ProfileGrpc.ProfileBlockingStub> {
|
||||
|
||||
private static final String VERSION = "someVersion";
|
||||
private static final byte[] VERSION = TestRandomUtil.nextBytes(32);
|
||||
|
||||
private static final byte[] VALID_DATA = new byte[128];
|
||||
|
||||
private static final byte[] VALID_NAME = new byte[81];
|
||||
|
||||
private static final SetProfileV1Request V1_REQUEST = SetProfileV1Request.newBuilder()
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(TestRandomUtil.nextBytes(29)))
|
||||
.build();
|
||||
|
||||
@Mock
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@@ -125,7 +133,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
private DynamicPaymentsConfiguration dynamicPaymentsConfiguration;
|
||||
|
||||
@Mock
|
||||
private VersionedProfile profile;
|
||||
private VersionedProfileV1 profile;
|
||||
|
||||
@Mock
|
||||
private Account account;
|
||||
@@ -136,9 +144,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
@Mock
|
||||
private ProfileBadgeConverter profileBadgeConverter;
|
||||
|
||||
@Mock
|
||||
private ServerZkProfileOperations serverZkProfileOperations;
|
||||
|
||||
private Clock clock;
|
||||
|
||||
@Override
|
||||
@@ -180,14 +185,15 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(account.getIdentifier(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(AUTHENTICATED_ACI);
|
||||
when(account.getNumber()).thenReturn(phoneNumber);
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
|
||||
when(profile.paymentAddress()).thenReturn(null);
|
||||
when(profile.avatar()).thenReturn("");
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(accountsManager.update(any(UUID.class), any())).thenReturn(null);
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI))).thenReturn(Optional.of(account));
|
||||
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.of(profile));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
|
||||
@@ -206,13 +212,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
policyGenerator,
|
||||
policySigner,
|
||||
profileBadgeConverter,
|
||||
rateLimiters,
|
||||
serverZkProfileOperations
|
||||
rateLimiters
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfile() throws InvalidInputException {
|
||||
void setProfile() throws Exception {
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
final byte[] validAboutEmoji = new byte[60];
|
||||
final byte[] validAbout = new byte[540];
|
||||
@@ -220,32 +225,60 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final byte[] validPhoneNumberSharing = new byte[29];
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setAboutEmoji(ByteString.copyFrom(validAboutEmoji))
|
||||
.setAbout(ByteString.copyFrom(validAbout))
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setCommitment(ByteString.copyFrom(commitment)) // after v1 -> v2 migration, commitment can be null if expectedDataHash is present
|
||||
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(validPhoneNumberSharing))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.setV1Request(V1_REQUEST.toBuilder()
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setAboutEmoji(ByteString.copyFrom(validAboutEmoji))
|
||||
.setAbout(ByteString.copyFrom(validAbout))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(validPhoneNumberSharing))
|
||||
)
|
||||
.build();
|
||||
|
||||
authenticatedServiceStub().setProfile(request);
|
||||
|
||||
final ArgumentCaptor<VersionedProfileV1> profileV1ArgumentCaptor = ArgumentCaptor.forClass(VersionedProfileV1.class);
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
verify(profilesManager).set(eq(account.getUuid()), profileArgumentCaptor.capture());
|
||||
verify(profilesManager).set(eq(account.getUuid()), profileV1ArgumentCaptor.capture(), profileArgumentCaptor.capture(), isNull());
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
|
||||
assertThat(profile.commitment()).isEqualTo(commitment);
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo(VERSION);
|
||||
assertThat(profile.name()).isEqualTo(VALID_NAME);
|
||||
assertThat(profile.aboutEmoji()).isEqualTo(validAboutEmoji);
|
||||
assertThat(profile.about()).isEqualTo(validAbout);
|
||||
assertThat(profile.data()).isEqualTo(VALID_DATA);
|
||||
assertThat(profile.dataHash()).hasSize(32);
|
||||
assertThat(profile.commitment()).isEqualTo(commitment);
|
||||
assertThat(profile.paymentAddress()).isEqualTo(validPaymentAddress);
|
||||
assertThat(profile.phoneNumberSharing()).isEqualTo(validPhoneNumberSharing);
|
||||
assertThat(profile.paymentAddressHash()).hasSize(32);
|
||||
|
||||
final VersionedProfileV1 v1Profile = profileV1ArgumentCaptor.getValue();
|
||||
|
||||
assertThat(v1Profile.commitment()).isEqualTo(commitment);
|
||||
assertThat(v1Profile.avatar()).isNull();
|
||||
assertThat(v1Profile.version()).isEqualTo(HexFormat.of().formatHex(VERSION));
|
||||
assertThat(v1Profile.name()).isEqualTo(VALID_NAME);
|
||||
assertThat(v1Profile.aboutEmoji()).isEqualTo(validAboutEmoji);
|
||||
assertThat(v1Profile.about()).isEqualTo(validAbout);
|
||||
assertThat(v1Profile.paymentAddress()).isEqualTo(validPaymentAddress);
|
||||
assertThat(v1Profile.phoneNumberSharing()).isEqualTo(validPhoneNumberSharing);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfileWithoutCapability() {
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(false);
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setExpectedCurrentDataHash(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setV1Request(V1_REQUEST)
|
||||
.build();
|
||||
|
||||
final SetProfileResponse response = authenticatedServiceStub().setProfile(request);
|
||||
|
||||
assertTrue(response.hasProfilesV2CapabilityRequired());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -256,22 +289,25 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(avatarChange)
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.setV1Request(V1_REQUEST.toBuilder().setAvatarChange(avatarChange).build())
|
||||
.build();
|
||||
|
||||
when(profile.avatar()).thenReturn(currentAvatar);
|
||||
|
||||
when(profilesManager.get(any(), anyString())).thenReturn(hasPreviousProfile ? Optional.of(profile) : Optional.empty());
|
||||
when(profilesManager.getV1(any(), anyString())).thenReturn(hasPreviousProfile ? Optional.of(profile) : Optional.empty());
|
||||
|
||||
final SetProfileResponse response = authenticatedServiceStub().setProfile(request);
|
||||
|
||||
assertTrue(response.hasResult());
|
||||
final SetProfileResult result = response.getResult();
|
||||
|
||||
if (expectHasS3UploadPath) {
|
||||
assertTrue(response.getAttributes().getPath().startsWith("profiles/"));
|
||||
assertTrue(result.getV1AvatarUploadForm().getPath().startsWith("profiles/"));
|
||||
} else {
|
||||
assertEquals(response.getAttributes().getPath(), "");
|
||||
assertEquals("", result.getV1AvatarUploadForm().getPath());
|
||||
}
|
||||
|
||||
if (expectDeleteS3Object) {
|
||||
@@ -300,8 +336,19 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setProfileInvalidRequestData(final SetProfileRequest request) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setProfile(request));
|
||||
void setProfileInvalidRequestData(final SetProfileRequest request, final String invalidFieldOrMessageFragment, final boolean assertFieldViolation) {
|
||||
assertStatusInvalidArgument(() -> authenticatedServiceStub().setProfile(request));
|
||||
// com.google.rpc.Status.parseFrom(exception.getTrailers().valueAsBytes(0)).getDetailsList().get(1).unpack(BadRequest.class).getFieldViolationsList().getFirst().getField()
|
||||
final StatusRuntimeException e = assertStatusInvalidArgument(() -> authenticatedServiceStub().setProfile(request));
|
||||
if (assertFieldViolation) {
|
||||
final List<BadRequest.FieldViolation> fieldViolations = GrpcTestUtils.extractDetail(BadRequest.class, e)
|
||||
.getFieldViolationsList();
|
||||
|
||||
assertEquals(1, fieldViolations.size());
|
||||
assertEquals(invalidFieldOrMessageFragment, fieldViolations.getFirst().getField());
|
||||
} else {
|
||||
assertThat(e.getMessage()).contains(invalidFieldOrMessageFragment);
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setProfileInvalidRequestData() throws InvalidInputException{
|
||||
@@ -309,40 +356,49 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final byte[] invalidValue = new byte[42];
|
||||
|
||||
final SetProfileRequest prototypeRequest = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.setV1Request(V1_REQUEST)
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing version
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
Arguments.argumentSet("Missing version", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearVersion()
|
||||
.build()),
|
||||
// Missing name
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearName()
|
||||
.build()),
|
||||
// Invalid name length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setName(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid about emoji length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setAboutEmoji(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid about length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setAbout(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid payment address
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.build(), "version", true),
|
||||
Arguments.argumentSet("Invalid current data hash", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setExpectedCurrentDataHash(ByteString.copyFrom(invalidValue))
|
||||
.build(), "expected_current_data_hash", true),
|
||||
Arguments.argumentSet("Invalid current version", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setExpectedCurrentVersion(ByteString.copyFrom(new byte[1]))
|
||||
.build(), "expected_current_version", true),
|
||||
Arguments.argumentSet("Missing name", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setV1Request(prototypeRequest.getV1Request().toBuilder().clearName())
|
||||
.build(), "name", true),
|
||||
Arguments.argumentSet("Invalid name length", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setV1Request(prototypeRequest.getV1Request().toBuilder()
|
||||
.setName(ByteString.copyFrom(invalidValue))
|
||||
.build())
|
||||
.build(), "name", true),
|
||||
Arguments.argumentSet("Invalid about emoji length", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setV1Request(prototypeRequest.getV1Request().toBuilder()
|
||||
.setAboutEmoji(ByteString.copyFrom(invalidValue)))
|
||||
.build(), "about_emoji", true),
|
||||
Arguments.argumentSet("Invalid about length", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setV1Request(prototypeRequest.getV1Request().toBuilder()
|
||||
.setAbout(ByteString.copyFrom(invalidValue)))
|
||||
.build(), "about", true),
|
||||
Arguments.argumentSet("Invalid payment address", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setPaymentAddress(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Missing profile commitment
|
||||
Arguments.of(SetProfileRequest.newBuilder()
|
||||
.build(), "payment_address", true),
|
||||
Arguments.argumentSet("Missing v1 request", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearV1Request()
|
||||
.build(), "v1Request", true),
|
||||
|
||||
// this is an invalid request but not a field validation
|
||||
Arguments.argumentSet("Missing profile commitment", SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearCommitment()
|
||||
.build())
|
||||
.build(), "commitment", false)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -358,42 +414,43 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
}
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.setV1Request(V1_REQUEST)
|
||||
.build();
|
||||
final String disallowedCountryCode = String.format("+%d", disallowedPhoneNumber.getCountryCode());
|
||||
when(dynamicPaymentsConfiguration.getDisallowedPrefixes()).thenReturn(List.of(disallowedCountryCode));
|
||||
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
|
||||
disallowedPhoneNumber,
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164));
|
||||
when(profilesManager.get(any(), anyString())).thenReturn(Optional.of(profile));
|
||||
when(profilesManager.getV1(any(), anyString())).thenReturn(Optional.of(profile));
|
||||
|
||||
final SetProfileResponse response = authenticatedServiceStub().setProfile(request);
|
||||
|
||||
if (hasExistingPaymentAddress) {
|
||||
assertDoesNotThrow(() -> authenticatedServiceStub().setProfile(request),
|
||||
"Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address");
|
||||
assertTrue(response.hasResult(), "Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address");
|
||||
} else {
|
||||
assertStatusException(Status.PERMISSION_DENIED, () -> authenticatedServiceStub().setProfile(request));
|
||||
assertTrue(response.hasPaymentsForbiddenInRegion());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfileBadges() throws InvalidInputException {
|
||||
void setProfileBadges() throws Exception {
|
||||
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.addAllBadgeIds(List.of("TEST3"))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.setV1Request(V1_REQUEST)
|
||||
.build();
|
||||
|
||||
final int accountsManagerUpdateRetryCount = 2;
|
||||
AccountsHelper.setupMockUpdateWithRetries(accountsManager, accountsManagerUpdateRetryCount);
|
||||
setUpMockUpdateWithRetries(accountsManager, accountsManagerUpdateRetryCount);
|
||||
// set up two invocations -- one for each AccountsManager#update try
|
||||
when(account.getBadges())
|
||||
.thenReturn(List.of(new AccountBadge("TEST3", Instant.ofEpochSecond(41), false)))
|
||||
@@ -415,6 +472,36 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
badgeCaptor.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfileBadgesEmptyListClearsAll() throws InvalidInputException {
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.setV1Request(V1_REQUEST)
|
||||
.build();
|
||||
|
||||
final List<AccountBadge> existingBadges = List.of(
|
||||
new AccountBadge("TEST1", Instant.ofEpochSecond(41), true),
|
||||
new AccountBadge("TEST2", Instant.ofEpochSecond(41), true));
|
||||
when(account.getBadges()).thenReturn(existingBadges);
|
||||
|
||||
setUpMockUpdateWithRetries(accountsManager, 1);
|
||||
|
||||
authenticatedServiceStub().setProfile(request);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
final ArgumentCaptor<List<AccountBadge>> badgeCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(account).setBadges(refEq(clock), badgeCaptor.capture());
|
||||
|
||||
assertEquals(List.of(
|
||||
new AccountBadge("TEST1", Instant.ofEpochSecond(41), false),
|
||||
new AccountBadge("TEST2", Instant.ofEpochSecond(41), false)),
|
||||
badgeCaptor.getValue());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"})
|
||||
void getUnversionedProfile(final IdentityType identityType) throws Exception {
|
||||
@@ -456,28 +543,29 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request);
|
||||
|
||||
final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey);
|
||||
final GetUnversionedProfileResponse prototypeExpectedResponse = GetUnversionedProfileResponse.newBuilder()
|
||||
final GetUnversionedProfileResult prototypeExpectedResult = GetUnversionedProfileResult.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(true)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.build();
|
||||
|
||||
final GetUnversionedProfileResponse expectedResponse;
|
||||
final GetUnversionedProfileResult expectedResponse;
|
||||
if (identityType == IdentityType.IDENTITY_TYPE_PNI) {
|
||||
expectedResponse = GetUnversionedProfileResponse.newBuilder(prototypeExpectedResponse)
|
||||
expectedResponse = GetUnversionedProfileResult.newBuilder(prototypeExpectedResult)
|
||||
.clearUnidentifiedAccess()
|
||||
.clearBadges()
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.build();
|
||||
} else {
|
||||
expectedResponse = prototypeExpectedResponse;
|
||||
expectedResponse = prototypeExpectedResult;
|
||||
}
|
||||
|
||||
verify(rateLimiter).validate(AUTHENTICATED_ACI);
|
||||
verify(accountsManager).getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
assertTrue(response.hasResult());
|
||||
assertEquals(expectedResponse, response.getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -491,7 +579,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.build())
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getUnversionedProfile(request));
|
||||
final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request);
|
||||
assertTrue(response.hasNotFound());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -514,7 +603,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfile(final String requestVersion, @Nullable final String accountVersion, final boolean expectResponseHasPaymentAddress) {
|
||||
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);
|
||||
@@ -522,44 +611,141 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
|
||||
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
|
||||
|
||||
final VersionedProfile profile = new VersionedProfile(accountVersion, name, avatar, emoji, about, paymentAddress,
|
||||
phoneNumberSharing, new byte[0]);
|
||||
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()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion(requestVersion)
|
||||
.setVersion(ByteString.copyFrom(requestVersion))
|
||||
.build();
|
||||
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion).map(v -> HexFormat.of().formatHex(v)));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.of(profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(profile);
|
||||
|
||||
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
|
||||
|
||||
final GetVersionedProfileResponse.Builder expectedResponseBuilder = GetVersionedProfileResponse.newBuilder()
|
||||
.setName(ByteString.copyFrom(name))
|
||||
.setAbout(ByteString.copyFrom(about))
|
||||
.setAboutEmoji(ByteString.copyFrom(emoji))
|
||||
.setAvatar(avatar)
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing));
|
||||
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
|
||||
.setV1Response(GetVersionedProfileV1Response.newBuilder()
|
||||
.setName(ByteString.copyFrom(name))
|
||||
.setAbout(ByteString.copyFrom(about))
|
||||
.setAboutEmoji(ByteString.copyFrom(emoji))
|
||||
.setAvatar(avatar)
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
|
||||
.build());
|
||||
|
||||
if (expectResponseHasPaymentAddress) {
|
||||
expectedResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
|
||||
expectedResultBuilder.setPaymentAddressDataEtag(
|
||||
DataEtag.newBuilder().setData(ByteString.copyFrom(paymentAddress))
|
||||
.setEtag(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress)))
|
||||
.build());
|
||||
|
||||
}
|
||||
|
||||
assertEquals(expectedResponseBuilder.build(), response);
|
||||
assertTrue(response.hasResult());
|
||||
assertEquals(expectedResultBuilder.build(), response.getResult());
|
||||
}
|
||||
private static Stream<Arguments> getVersionedProfile() {
|
||||
return Stream.of(
|
||||
Arguments.of("version1", "version1", true),
|
||||
Arguments.of("version1", null, true),
|
||||
Arguments.of("version1", "version2", false)
|
||||
private static Collection<Arguments> getVersionedProfile() {
|
||||
final byte[] version1 = TestRandomUtil.nextBytes(32);
|
||||
final byte[] version2 = TestRandomUtil.nextBytes(32);
|
||||
return List.of(
|
||||
Arguments.argumentSet("current profile version matches", version1, version1, true),
|
||||
Arguments.argumentSet("current profile version absent",version1, null, true),
|
||||
Arguments.argumentSet("current profile version mismatch",version1, version2, false)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileV2() {
|
||||
final byte[] data = TestRandomUtil.nextBytes(128);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
|
||||
final UUID targetAci = UUID.randomUUID();
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
|
||||
final Account targetAccount = mock(Account.class);
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci)))
|
||||
.thenReturn(Optional.of(targetAccount));
|
||||
when(targetAccount.getUuid()).thenReturn(targetAci);
|
||||
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
|
||||
when(profilesManager.get(eq(targetAci), aryEq(version))).thenReturn(Optional.of(v2Profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci)))
|
||||
.build())
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
|
||||
assertTrue(response.hasResult());
|
||||
final GetVersionedProfileResult result = response.getResult();
|
||||
|
||||
assertTrue(result.hasDataEtag());
|
||||
assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData());
|
||||
assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtag());
|
||||
assertTrue(result.hasPaymentAddressDataEtag());
|
||||
assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData());
|
||||
assertEquals(ByteString.copyFrom(v2Profile.paymentAddressHash()), result.getPaymentAddressDataEtag().getEtag());
|
||||
assertFalse(result.getDataEtagMatched());
|
||||
assertFalse(result.getPaymentAddressEtagMatched());
|
||||
assertFalse(result.hasV1Response());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileV2EtagMatched() {
|
||||
final byte[] data = TestRandomUtil.nextBytes(128);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
|
||||
final UUID targetAci = UUID.randomUUID();
|
||||
final Account targetAccount = mock(Account.class);
|
||||
when(targetAccount.getUuid()).thenReturn(targetAci);
|
||||
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(targetAccount));
|
||||
|
||||
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(versionHex));
|
||||
when(profilesManager.get(targetAci, version)).thenReturn(Optional.of(v2Profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci)))
|
||||
.build())
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.setDataEtag(ByteString.copyFrom(v2Profile.dataHash()));
|
||||
|
||||
if (v2Profile.paymentAddressHash() != null) {
|
||||
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
|
||||
}
|
||||
|
||||
final GetVersionedProfileRequest request = builder.build();
|
||||
|
||||
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
|
||||
assertTrue(response.hasResult());
|
||||
final GetVersionedProfileResult result = response.getResult();
|
||||
|
||||
assertTrue(result.getDataEtagMatched());
|
||||
assertTrue(result.getPaymentAddressEtagMatched());
|
||||
assertFalse(result.hasDataEtag());
|
||||
assertFalse(result.hasPaymentAddressDataEtag());
|
||||
assertFalse(result.hasV1Response());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfileAccountOrProfileNotFound(final boolean missingAccount, final boolean missingProfile) {
|
||||
@@ -568,12 +754,13 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion("versionWithNoProfile")
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build();
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
|
||||
when(profilesManager.get(any(), any())).thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
|
||||
|
||||
assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getVersionedProfile(request));
|
||||
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
|
||||
assertTrue(response.hasNotFound());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> getVersionedProfileAccountOrProfileNotFound() {
|
||||
@@ -592,7 +779,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build();
|
||||
|
||||
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getVersionedProfile(request), accountsManager, profilesManager);
|
||||
@@ -605,155 +792,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion("someVersion")
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getExpiringProfileKeyCredential() throws InvalidInputException, VerificationFailedException {
|
||||
final UUID targetUuid = UUID.randomUUID();
|
||||
|
||||
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
|
||||
final ServerPublicParams serverPublicParams = serverSecretParams.getPublicParams();
|
||||
|
||||
final ServerZkProfileOperations serverZkProfile = new ServerZkProfileOperations(serverSecretParams);
|
||||
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams);
|
||||
|
||||
final byte[] profileKeyBytes = TestRandomUtil.nextBytes(32);
|
||||
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
|
||||
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(targetUuid));
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
|
||||
|
||||
when(account.getUuid()).thenReturn(targetUuid);
|
||||
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
|
||||
|
||||
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
|
||||
|
||||
final Instant expiration = Instant.now().plus(org.whispersystems.textsecuregcm.util.ProfileHelper.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION)
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse credentialResponse =
|
||||
serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration);
|
||||
|
||||
when(serverZkProfileOperations.issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration))
|
||||
.thenReturn(credentialResponse);
|
||||
|
||||
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom(credentialRequest.serialize()))
|
||||
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
|
||||
.setVersion("someVersion")
|
||||
.build();
|
||||
|
||||
final GetExpiringProfileKeyCredentialResponse response = authenticatedServiceStub().getExpiringProfileKeyCredential(request);
|
||||
|
||||
assertArrayEquals(credentialResponse.serialize(), response.getProfileKeyCredential().toByteArray());
|
||||
|
||||
verify(serverZkProfileOperations).issueExpiringProfileKeyCredential(credentialRequest, new ServiceId.Aci(targetUuid), profileKeyCommitment, expiration);
|
||||
|
||||
final ClientZkProfileOperations clientZkProfileCipher = new ClientZkProfileOperations(serverPublicParams);
|
||||
assertThatNoException().isThrownBy(() ->
|
||||
clientZkProfileCipher.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, new ExpiringProfileKeyCredentialResponse(response.getProfileKeyCredential().toByteArray())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getExpiringProfileKeyCredentialRateLimited() {
|
||||
final Duration retryAfterDuration = MockUtils.updateRateLimiterResponseToFail(
|
||||
rateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(5));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
|
||||
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
|
||||
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
|
||||
.setVersion("someVersion")
|
||||
.build();
|
||||
|
||||
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request), profilesManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getExpiringProfileKeyCredentialAccountOrProfileNotFound(final boolean missingAccount,
|
||||
final boolean missingProfile) {
|
||||
final UUID targetUuid = UUID.randomUUID();
|
||||
|
||||
when(account.getUuid()).thenReturn(targetUuid);
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid)))
|
||||
.thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
|
||||
when(profilesManager.get(targetUuid, "someVersion"))
|
||||
.thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
|
||||
|
||||
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
|
||||
.setCredentialType(CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY)
|
||||
.setVersion("someVersion")
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.NOT_FOUND, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> getExpiringProfileKeyCredentialAccountOrProfileNotFound() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, false),
|
||||
Arguments.of(false, true)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getExpiringProfileKeyCredentialInvalidArgument(final IdentityType identityType, final CredentialType credentialType,
|
||||
final boolean throwZkVerificationException) throws VerificationFailedException {
|
||||
final UUID targetUuid = UUID.randomUUID();
|
||||
|
||||
if (throwZkVerificationException) {
|
||||
when(serverZkProfileOperations.issueExpiringProfileKeyCredential(any(), any(), any(), any())).thenThrow(new VerificationFailedException());
|
||||
}
|
||||
|
||||
when(account.getUuid()).thenReturn(targetUuid);
|
||||
when(profile.commitment()).thenReturn("commitment".getBytes(StandardCharsets.UTF_8));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetUuid))).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(targetUuid, "someVersion")).thenReturn(Optional.of(profile));
|
||||
|
||||
final GetExpiringProfileKeyCredentialRequest request = GetExpiringProfileKeyCredentialRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(identityType)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
|
||||
.build())
|
||||
.setCredentialRequest(ByteString.copyFrom("credentialRequest".getBytes(StandardCharsets.UTF_8)))
|
||||
.setCredentialType(credentialType)
|
||||
.setVersion("someVersion")
|
||||
.build();
|
||||
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getExpiringProfileKeyCredential(request));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> getExpiringProfileKeyCredentialInvalidArgument() {
|
||||
return Stream.of(
|
||||
// Credential type unspecified
|
||||
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_UNSPECIFIED, false),
|
||||
// Illegal identity type
|
||||
Arguments.of(IdentityType.IDENTITY_TYPE_PNI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, false),
|
||||
// Artificially fails zero knowledge verification
|
||||
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY, true)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
|
||||
return serverInterceptors.stream()
|
||||
@@ -762,4 +806,55 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 16, 32})
|
||||
void testProfileSerialized(int aboutEmojiLength) {
|
||||
|
||||
// This test demonstrates the calculation for the (require.size).max = 909 + 28
|
||||
// in profiles.proto, as well as how padding calculation results in a constant size.
|
||||
//
|
||||
// This should be largely integrated into libsignal in the future.
|
||||
|
||||
// in gRPC, field + varint length encoding has:
|
||||
// field number: 1 byte per field < number 16
|
||||
// varint: 1 byte for length < 128, 2 bytes for < 16,384
|
||||
final int serializedSize =
|
||||
1 + 257 + 2 +
|
||||
1 + 512 + 2 +
|
||||
1 + aboutEmojiLength + 1 +
|
||||
1 + 64 + 1 +
|
||||
1 + 1 +
|
||||
1 + (64 - (257 + 512 + aboutEmojiLength + 64 + 1) % 64) + 1;
|
||||
|
||||
assertEquals(909, serializedSize);
|
||||
|
||||
final PlaintextProfileData data = PlaintextProfileData.newBuilder()
|
||||
.setNameBytes(ByteString.copyFrom(new byte[257]))
|
||||
.setAboutBytes(ByteString.copyFrom(new byte[512]))
|
||||
.setAboutEmojiBytes(ByteString.copyFrom(new byte[aboutEmojiLength]))
|
||||
.setAvatarBytes(ByteString.copyFrom(new byte[64]))
|
||||
.setPhoneNumberSharing(true)
|
||||
.setPadding(ByteString.copyFrom(new byte[64 - (257 + 512 + aboutEmojiLength + 64 + 1) % 64]))
|
||||
.build();
|
||||
|
||||
assertEquals(serializedSize, data.getSerializedSize());
|
||||
}
|
||||
|
||||
static void setUpMockUpdateWithRetries(final AccountsManager accountsManager, final int retryCount) {
|
||||
try {
|
||||
when(accountsManager.updateCurrentProfileVersion(any(), any(), any(), any()))
|
||||
.thenAnswer(a -> {
|
||||
final Account account = accountsManager.getByAccountIdentifier(a.getArgument(0, UUID.class)).orElseThrow();
|
||||
for (int i = 0; i < retryCount; i++) {
|
||||
//noinspection unchecked
|
||||
a.getArgument(3, Consumer.class).accept(account);
|
||||
}
|
||||
|
||||
return account;
|
||||
});
|
||||
} catch (final WriteConflictException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
-1
@@ -16,6 +16,7 @@ import io.grpc.StatusRuntimeException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
@@ -29,8 +30,11 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.require.Auth;
|
||||
import org.signal.chat.rpc.Color;
|
||||
import org.signal.chat.rpc.NestedMessage;
|
||||
@@ -43,6 +47,7 @@ import org.signal.chat.rpc.ValidationsRequest;
|
||||
import org.signal.chat.rpc.ValidationsResponse;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ValidatingInterceptorTest {
|
||||
|
||||
@@ -122,6 +127,51 @@ public class ValidatingInterceptorTest {
|
||||
.build()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
public void serviceIdentifierIdentityTypeFieldValidator(final boolean messagePresent) {
|
||||
|
||||
final ValidationsRequest.Builder builder = builderWithValidDefaults();
|
||||
|
||||
if (messagePresent) {
|
||||
builder.setAciServiceIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
.build())
|
||||
.setPniServiceIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
|
||||
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
.build());
|
||||
} else {
|
||||
builder.clearAciServiceIdentifier()
|
||||
.clearPniServiceIdentifier();
|
||||
}
|
||||
|
||||
assertDoesNotThrow(() -> stub.validationsEndpoint(builder.build()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_UNSPECIFIED", "IDENTITY_TYPE_PNI"})
|
||||
public void testServiceIdentifierIdentityTypeAciValidationFailure(final IdentityType identityType) {
|
||||
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
|
||||
.setAciServiceIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(identityType)
|
||||
.setUuid(UUIDUtil.toByteString(UUID.randomUUID())))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_UNSPECIFIED", "IDENTITY_TYPE_ACI"})
|
||||
public void testServiceIdentifierIdentityTypePniValidationFailure(final IdentityType identityType) {
|
||||
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint(builderWithValidDefaults()
|
||||
.setPniServiceIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(identityType)
|
||||
.setUuid(UUIDUtil.toByteString(UUID.randomUUID())))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 2, 3, 4, 6, 1000})
|
||||
public void testExactlySizeValidationFailure(final int size) throws Exception {
|
||||
@@ -470,7 +520,15 @@ public class ValidatingInterceptorTest {
|
||||
.setNested(NestedMessage.getDefaultInstance())
|
||||
.addRepeatedNested(NestedMessage.getDefaultInstance())
|
||||
.putMapNested("test", NestedMessage.getDefaultInstance())
|
||||
.setBase64Url("123aBc_-");
|
||||
.setBase64Url("123aBc_-")
|
||||
.setAciServiceIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
.build())
|
||||
.setPniServiceIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
|
||||
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
.build());
|
||||
}
|
||||
|
||||
private static void assertStatusException(final Status expected, final Executable serviceCall) {
|
||||
|
||||
+45
@@ -44,9 +44,12 @@ import java.security.InvalidKeyException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -1446,6 +1449,48 @@ class AccountsManagerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void updateCurrentProfileVersion(final byte[] currentVersion, final byte[] expectedVersion, final byte[] newVersion, final boolean expectException) throws Exception {
|
||||
final Account account = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
final UUID accountIdentifier = account.getIdentifier(IdentityType.ACI);
|
||||
addRetrievableAccount(account);
|
||||
|
||||
account.setCurrentProfileVersion(HexFormat.of().formatHex(currentVersion));
|
||||
|
||||
final AccountBadge badge = new AccountBadge("test", CLOCK.instant().plusSeconds(60), true);
|
||||
|
||||
assertTrue(account.getBadges().isEmpty());
|
||||
|
||||
if (expectException) {
|
||||
assertThrows(WriteConflictException.class, () -> accountsManager.updateCurrentProfileVersion(accountIdentifier, newVersion, HexFormat.of().formatHex(expectedVersion), _ -> {}));
|
||||
} else {
|
||||
final Account updatedAccount = accountsManager.updateCurrentProfileVersion(accountIdentifier, newVersion,
|
||||
HexFormat.of().formatHex(expectedVersion), a -> {
|
||||
|
||||
a.setBadges(CLOCK, new ArrayList<>(List.of(badge)));
|
||||
});
|
||||
|
||||
assertArrayEquals(newVersion, HexFormat.of().parseHex(updatedAccount.getCurrentProfileVersion().orElseThrow()));
|
||||
assertEquals(List.of(badge), updatedAccount.getBadges());
|
||||
}
|
||||
}
|
||||
|
||||
static Collection<Arguments> updateCurrentProfileVersion() {
|
||||
|
||||
final byte[] empty = new byte[0];
|
||||
final byte[] version1 = TestRandomUtil.nextBytes(16);
|
||||
final byte[] version2 = Arrays.copyOf(version1, version1.length);
|
||||
version2[0] = (byte) (version2[0] + 1);
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("no current version - matches", empty, empty, version1, false),
|
||||
Arguments.argumentSet("no current version - conflict", empty, version1, version1, true),
|
||||
Arguments.argumentSet("current version - empty conflict", version1, empty, version2, true),
|
||||
Arguments.argumentSet("current version - matches", version1, version1, version2, false)
|
||||
);
|
||||
}
|
||||
|
||||
private void addRetrievableAccount(final Account account) {
|
||||
when(accounts.getByAccountIdentifier(account.getIdentifier(IdentityType.ACI)))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
+14
@@ -258,6 +258,20 @@ public final class DynamoDbExtensionSchema {
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
PROFILES_V2("profiles_v2_test",
|
||||
ProfilesV2.KEY_ACCOUNT_UUID,
|
||||
ProfilesV2.KEY_VERSION,
|
||||
List.of(
|
||||
AttributeDefinition.builder()
|
||||
.attributeName(ProfilesV2.KEY_ACCOUNT_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build(),
|
||||
AttributeDefinition.builder()
|
||||
.attributeName(ProfilesV2.KEY_VERSION)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
PUSH_CHALLENGES("push_challenge_test",
|
||||
PushChallengeDynamoDb.KEY_ACCOUNT_UUID,
|
||||
null,
|
||||
|
||||
+365
-143
@@ -7,11 +7,13 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -22,238 +24,203 @@ import static org.mockito.Mockito.when;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class ProfilesManagerTest {
|
||||
|
||||
private Profiles profiles;
|
||||
private RedisAdvancedClusterCommands<byte[], byte[]> binaryCommands;
|
||||
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> binaryAsyncCommands;
|
||||
private Profiles profilesV1;
|
||||
private ProfilesV2 profilesV2;
|
||||
private RedisAdvancedClusterCommands<byte[], byte[]> commands;
|
||||
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands;
|
||||
private S3AsyncClient s3Client;
|
||||
private ClusterLuaScript setLuaScript;
|
||||
|
||||
private ProfilesManager profilesManager;
|
||||
|
||||
private static final String BUCKET = "bucket";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
void setUp() throws Exception {
|
||||
//noinspection unchecked
|
||||
binaryCommands = mock(RedisAdvancedClusterCommands.class);
|
||||
commands = mock(RedisAdvancedClusterCommands.class);
|
||||
//noinspection unchecked
|
||||
binaryAsyncCommands = mock(RedisAdvancedClusterAsyncCommands.class);
|
||||
asyncCommands = mock(RedisAdvancedClusterAsyncCommands.class);
|
||||
final FaultTolerantRedisClusterClient cacheCluster = RedisClusterHelper.builder()
|
||||
.binaryCommands(binaryCommands)
|
||||
.binaryAsyncCommands(binaryAsyncCommands)
|
||||
.binaryCommands(commands)
|
||||
.binaryAsyncCommands(asyncCommands)
|
||||
.build();
|
||||
|
||||
profiles = mock(Profiles.class);
|
||||
profilesV1 = mock(Profiles.class);
|
||||
profilesV2 = mock(ProfilesV2.class);
|
||||
s3Client = mock(S3AsyncClient.class);
|
||||
setLuaScript = mock(ClusterLuaScript.class);
|
||||
|
||||
profilesManager = new ProfilesManager(profiles, cacheCluster, mock(ScheduledExecutorService.class), s3Client, BUCKET);
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, cacheCluster, mock(ScheduledExecutorService.class),
|
||||
s3Client, BUCKET, setLuaScript);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProfileInCache() throws InvalidInputException {
|
||||
public void testGetV1ProfileInCache() throws InvalidInputException {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())))
|
||||
when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes())))
|
||||
.thenReturn(String.format(
|
||||
"{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
|
||||
"{\"version\": \"%s\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
|
||||
versionHex,
|
||||
ProfileTestHelper.encodeToBase64(name),
|
||||
ProfileTestHelper.encodeToBase64(commitment)).getBytes());
|
||||
|
||||
Optional<VersionedProfile> profile = profilesManager.get(uuid, "someversion");
|
||||
Optional<VersionedProfileV1> profile = profilesManager.getV1(uuid, versionHex);
|
||||
|
||||
assertTrue(profile.isPresent());
|
||||
assertArrayEquals(profile.get().name(), name);
|
||||
assertEquals("someavatar", profile.get().avatar());
|
||||
assertArrayEquals(profile.get().commitment(), commitment);
|
||||
|
||||
verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
|
||||
verifyNoMoreInteractions(binaryCommands);
|
||||
verifyNoMoreInteractions(profiles);
|
||||
verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes()));
|
||||
verifyNoMoreInteractions(commands);
|
||||
verifyNoMoreInteractions(profilesV1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProfileAsyncInCache() throws InvalidInputException {
|
||||
public void testGetV1ProfileNotInCache() throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
|
||||
when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes())))
|
||||
.thenReturn(MockRedisFuture.completedFuture(String.format("{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
|
||||
ProfileTestHelper.encodeToBase64(name),
|
||||
ProfileTestHelper.encodeToBase64(commitment)).getBytes()));
|
||||
|
||||
Optional<VersionedProfile> profile = profilesManager.getAsync(uuid, "someversion").join();
|
||||
|
||||
assertTrue(profile.isPresent());
|
||||
assertArrayEquals(profile.get().name(), name);
|
||||
assertEquals("someavatar", profile.get().avatar());
|
||||
assertArrayEquals(profile.get().commitment(), commitment);
|
||||
|
||||
verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
|
||||
verifyNoMoreInteractions(binaryAsyncCommands);
|
||||
verifyNoMoreInteractions(profiles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProfileNotInCache() {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null,
|
||||
null, null, "somecommitment".getBytes());
|
||||
|
||||
when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))).thenReturn(null);
|
||||
when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile));
|
||||
when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes()))).thenReturn(null);
|
||||
when(profilesV1.get(eq(uuid), eq(versionHex))).thenReturn(Optional.of(profile));
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesManager.get(uuid, "someversion");
|
||||
Optional<VersionedProfileV1> retrieved = profilesManager.getV1(uuid, versionHex);
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
assertSame(retrieved.get(), profile);
|
||||
assertEquals(retrieved.get(), profile);
|
||||
|
||||
verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
|
||||
verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class));
|
||||
verifyNoMoreInteractions(binaryCommands);
|
||||
final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
|
||||
|
||||
verify(profiles, times(1)).get(eq(uuid), eq("someversion"));
|
||||
verifyNoMoreInteractions(profiles);
|
||||
}
|
||||
verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()));
|
||||
verify(setLuaScript, times(1)).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
|
||||
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
|
||||
argThat(args ->
|
||||
Arrays.equals(args.get(0), versionHex.getBytes())
|
||||
&& Arrays.equals(args.get(1), v1ProfileBytes)
|
||||
&& args.get(2).length == 0));
|
||||
|
||||
@Test
|
||||
public void testGetProfileAsyncNotInCache() {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, null, "somecommitment".getBytes());
|
||||
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(versionHex.getBytes()));
|
||||
verifyNoMoreInteractions(commands);
|
||||
verifyNoMoreInteractions(setLuaScript);
|
||||
|
||||
when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()))).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class))).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
when(profiles.getAsync(eq(uuid), eq("someversion"))).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesManager.getAsync(uuid, "someversion").join();
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
assertSame(retrieved.get(), profile);
|
||||
|
||||
verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()));
|
||||
verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class));
|
||||
verifyNoMoreInteractions(binaryAsyncCommands);
|
||||
|
||||
verify(profiles, times(1)).getAsync(eq(uuid), eq("someversion"));
|
||||
verifyNoMoreInteractions(profiles);
|
||||
verify(profilesV1, times(1)).get(eq(uuid), eq(versionHex));
|
||||
verifyNoMoreInteractions(profilesV1);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
public void testGetProfileBrokenCache(final boolean failUpdateCache) {
|
||||
public void testGetV1ProfileBrokenCache(final boolean failUpdateCache) {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null,
|
||||
null, null, "somecommitment".getBytes());
|
||||
|
||||
when(binaryCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()))).thenThrow(new RedisException("Connection lost"));
|
||||
when(commands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()))).thenThrow(new RedisException("Connection lost"));
|
||||
if (failUpdateCache) {
|
||||
when(binaryCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class)))
|
||||
when(commands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()), any(byte[].class)))
|
||||
.thenThrow(new RedisException("Connection lost"));
|
||||
}
|
||||
when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile));
|
||||
when(profilesV1.get(eq(uuid), eq(versionHex))).thenReturn(Optional.of(profile));
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesManager.get(uuid, "someversion");
|
||||
Optional<VersionedProfileV1> retrieved = profilesManager.getV1(uuid, versionHex);
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
assertSame(retrieved.get(), profile);
|
||||
assertEquals(retrieved.get(), profile);
|
||||
|
||||
verify(binaryCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()));
|
||||
verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class));
|
||||
verifyNoMoreInteractions(binaryCommands);
|
||||
verify(commands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq(versionHex.getBytes()));
|
||||
verify(setLuaScript, times(1)).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
|
||||
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
|
||||
argThat(args ->
|
||||
Arrays.equals(args.get(0), versionHex.getBytes())
|
||||
&& args.get(1).length > 0
|
||||
&& args.get(2).length == 0));
|
||||
verifyNoMoreInteractions(commands);
|
||||
verifyNoMoreInteractions(setLuaScript);
|
||||
|
||||
verify(profiles, times(1)).get(eq(uuid), eq("someversion"));
|
||||
verifyNoMoreInteractions(profiles);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
public void testGetProfileAsyncBrokenCache(final boolean failUpdateCache) {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, null, "somecommitment".getBytes());
|
||||
|
||||
when(binaryAsyncCommands.hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()))).thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost")));
|
||||
when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class)))
|
||||
.thenReturn(failUpdateCache
|
||||
? MockRedisFuture.failedFuture(new RedisException("Connection lost"))
|
||||
: MockRedisFuture.completedFuture(null));
|
||||
when(profiles.getAsync(eq(uuid), eq("someversion"))).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesManager.getAsync(uuid, "someversion").join();
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
assertSame(retrieved.get(), profile);
|
||||
|
||||
verify(binaryAsyncCommands, times(1)).hget(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()));
|
||||
verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class));
|
||||
verifyNoMoreInteractions(binaryAsyncCommands);
|
||||
|
||||
verify(profiles, times(1)).getAsync(eq(uuid), eq("someversion"));
|
||||
verifyNoMoreInteractions(profiles);
|
||||
verify(profilesV1, times(1)).get(eq(uuid), eq(versionHex));
|
||||
verifyNoMoreInteractions(profilesV1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSet() {
|
||||
public void testSetV1() throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
final VersionedProfileV1 profile = new VersionedProfileV1(versionHex, name, "someavatar", null, null,
|
||||
null, null, "somecommitment".getBytes());
|
||||
|
||||
profilesManager.set(uuid, profile);
|
||||
profilesManager.setV1(uuid, profile);
|
||||
|
||||
verify(binaryCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), aryEq("someversion".getBytes()), any(byte[].class));
|
||||
verifyNoMoreInteractions(binaryCommands);
|
||||
final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
|
||||
|
||||
verify(profiles, times(1)).set(eq(uuid), eq(profile));
|
||||
verifyNoMoreInteractions(profiles);
|
||||
}
|
||||
verify(setLuaScript, times(1)).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
|
||||
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
|
||||
argThat(args ->
|
||||
Arrays.equals(args.get(0), versionHex.getBytes())
|
||||
&& Arrays.equals(args.get(1), v1ProfileBytes)
|
||||
&& args.get(2).length == 0
|
||||
&& args.get(3).length == 0));
|
||||
verifyNoMoreInteractions(setLuaScript);
|
||||
|
||||
@Test
|
||||
public void testSetAsync() {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, null, "somecommitment".getBytes());
|
||||
|
||||
when(binaryAsyncCommands.hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any(byte[].class))).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
when(profiles.setAsync(eq(uuid), eq(profile))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
profilesManager.setAsync(uuid, profile).join();
|
||||
|
||||
verify(binaryAsyncCommands, times(1)).hset(eq(ProfilesManager.getCacheKeyV1(uuid)), eq("someversion".getBytes()), any());
|
||||
verifyNoMoreInteractions(binaryAsyncCommands);
|
||||
|
||||
verify(profiles, times(1)).setAsync(eq(uuid), eq(profile));
|
||||
verifyNoMoreInteractions(profiles);
|
||||
verify(profilesV1, times(1)).set(eq(uuid), eq(profile));
|
||||
verifyNoMoreInteractions(profilesV1);
|
||||
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid)));
|
||||
verify(profilesV2).deleteAll(uuid);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -263,16 +230,18 @@ public class ProfilesManagerTest {
|
||||
|
||||
final String avatarOne = "avatar1";
|
||||
final String avatarTwo = "avatar2";
|
||||
when(profiles.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(List.of(avatarOne, avatarTwo)));
|
||||
when(binaryAsyncCommands.del(ProfilesManager.getCacheKeyV1(uuid))).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
when(profilesV1.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(List.of(avatarOne, avatarTwo)));
|
||||
when(profilesV2.deleteAll(uuid)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(asyncCommands.del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid))).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
when(s3Client.deleteObject(any(DeleteObjectRequest.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(null))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("some error")));
|
||||
|
||||
profilesManager.deleteAll(uuid, includeAvatar).join();
|
||||
|
||||
verify(profiles).deleteAll(uuid);
|
||||
verify(binaryAsyncCommands).del(ProfilesManager.getCacheKeyV1(uuid));
|
||||
verify(profilesV1).deleteAll(uuid);
|
||||
verify(profilesV2).deleteAll(uuid);
|
||||
verify(asyncCommands).del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid));
|
||||
if (includeAvatar) {
|
||||
verify(s3Client).deleteObject(DeleteObjectRequest.builder()
|
||||
.bucket(BUCKET)
|
||||
@@ -286,4 +255,257 @@ public class ProfilesManagerTest {
|
||||
verifyNoInteractions(s3Client);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProfileInCache() {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final byte[] data = TestRandomUtil.nextBytes(128);
|
||||
final byte[] dataHash = TestRandomUtil.nextBytes(32);
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(32);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(64);
|
||||
final byte[] paymentAddressHash = TestRandomUtil.nextBytes(32);
|
||||
|
||||
when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenReturn(String.format(
|
||||
"""
|
||||
{
|
||||
"version":"%s",
|
||||
"data":"%s",
|
||||
"dataHash":"%s",
|
||||
"paymentAddress":"%s",
|
||||
"paymentAddressHash":"%s",
|
||||
"commitment":"%s"
|
||||
}
|
||||
""",
|
||||
ProfileTestHelper.encodeToBase64(version),
|
||||
ProfileTestHelper.encodeToBase64(data),
|
||||
ProfileTestHelper.encodeToBase64(dataHash),
|
||||
ProfileTestHelper.encodeToBase64(paymentAddress),
|
||||
ProfileTestHelper.encodeToBase64(paymentAddressHash),
|
||||
ProfileTestHelper.encodeToBase64(commitment)).getBytes());
|
||||
|
||||
Optional<VersionedProfile> profile = profilesManager.get(uuid, version);
|
||||
|
||||
assertTrue(profile.isPresent());
|
||||
assertArrayEquals(profile.get().data(), data);
|
||||
assertArrayEquals(profile.get().dataHash(), dataHash);
|
||||
assertArrayEquals(profile.get().commitment(), commitment);
|
||||
assertArrayEquals(profile.get().paymentAddress(), paymentAddress);
|
||||
assertArrayEquals(profile.get().paymentAddressHash(), paymentAddressHash);
|
||||
|
||||
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version));
|
||||
verifyNoMoreInteractions(commands);
|
||||
verifyNoMoreInteractions(profilesV2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProfileNotInCache() throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final VersionedProfile profile = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
|
||||
|
||||
when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenReturn(null);
|
||||
when(profilesV2.get(eq(uuid), aryEq(version))).thenReturn(Optional.of(profile));
|
||||
|
||||
final Optional<VersionedProfile> retrieved = profilesManager.get(uuid, version);
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
assertEquals(retrieved.get(), profile);
|
||||
|
||||
final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
|
||||
|
||||
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version));
|
||||
verify(setLuaScript, times(1)).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
|
||||
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
|
||||
argThat(args ->
|
||||
args.get(0).length == 0
|
||||
&& args.get(1).length == 0
|
||||
&& Arrays.equals(args.get(2), version)
|
||||
&& Arrays.equals(args.get(3), v2ProfileBytes)));
|
||||
verifyNoMoreInteractions(commands);
|
||||
|
||||
verify(profilesV2, times(1)).get(eq(uuid), aryEq(version));
|
||||
verifyNoMoreInteractions(profilesV2);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
public void testGetProfileBrokenCache(final boolean failUpdateCache) throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final VersionedProfile profile = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
|
||||
|
||||
when(commands.hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version))).thenThrow(new RedisException("Connection lost"));
|
||||
if (failUpdateCache) {
|
||||
when(commands.hset(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version), any(byte[].class)))
|
||||
.thenThrow(new RedisException("Connection lost"));
|
||||
}
|
||||
when(profilesV2.get(eq(uuid), aryEq(version))).thenReturn(Optional.of(profile));
|
||||
|
||||
final Optional<VersionedProfile> retrieved = profilesManager.get(uuid, version);
|
||||
|
||||
assertTrue(retrieved.isPresent());
|
||||
assertEquals(retrieved.get(), profile);
|
||||
|
||||
final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profile);
|
||||
|
||||
verify(commands, times(1)).hget(aryEq(ProfilesManager.getCacheKeyV2(uuid)), aryEq(version));
|
||||
verify(setLuaScript, times(1)).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
|
||||
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
|
||||
argThat(args ->
|
||||
args.get(0).length == 0
|
||||
&& args.get(1).length == 0
|
||||
&& Arrays.equals(args.get(2), version)
|
||||
&& Arrays.equals(args.get(3), v2ProfileBytes))); verifyNoMoreInteractions(commands);
|
||||
|
||||
verify(profilesV2, times(1)).get(eq(uuid), aryEq(version));
|
||||
verifyNoMoreInteractions(profilesV2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSet() throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment);
|
||||
|
||||
final byte[] expectedCurrentDataHash = TestRandomUtil.nextBytes(32);
|
||||
final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
|
||||
TestRandomUtil.nextBytes(32), commitment);
|
||||
|
||||
final TransactWriteItem v1Item = TransactWriteItem.builder().build();
|
||||
when(profilesV1.getTransactWriteItem(eq(uuid), eq(profileV1))).thenReturn(v1Item);
|
||||
|
||||
profilesManager.set(uuid, profileV1, profileV2, expectedCurrentDataHash);
|
||||
|
||||
final byte[] v1ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profileV1);
|
||||
final byte[] v2ProfileBytes = SystemMapper.jsonMapper().writeValueAsBytes(profileV2);
|
||||
|
||||
verify(setLuaScript, times(1)).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))
|
||||
&& Arrays.equals(keys.get(1), ProfilesManager.getCacheKeyV2(uuid))),
|
||||
argThat(args ->
|
||||
Arrays.equals(args.get(0), versionHex.getBytes())
|
||||
&& Arrays.equals(args.get(1), v1ProfileBytes)
|
||||
&& Arrays.equals(args.get(2), version)
|
||||
&& Arrays.equals(args.get(3), v2ProfileBytes)));
|
||||
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid)));
|
||||
verifyNoMoreInteractions(commands);
|
||||
verifyNoMoreInteractions(setLuaScript);
|
||||
|
||||
verify(profilesV1).getTransactWriteItem(eq(uuid), eq(profileV1));
|
||||
verifyNoMoreInteractions(profilesV1);
|
||||
|
||||
verify(profilesV2).set(eq(uuid), aryEq(version), aryEq(profileV2.data()), aryEq(profileV2.dataHash()), aryEq(profileV2.commitment()), aryEq(profileV2.paymentAddress()), aryEq(profileV2.paymentAddressHash()), aryEq(expectedCurrentDataHash), eq(v1Item));
|
||||
verifyNoMoreInteractions(profilesV2);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void testSetExceptionCleansUpCache(final Class<? extends Exception> exceptionClass) throws WriteConflictException, InvalidInputException {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment);
|
||||
|
||||
final byte[] wrongHash = TestRandomUtil.nextBytes(32);
|
||||
final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
|
||||
TestRandomUtil.nextBytes(32), commitment);
|
||||
|
||||
final TransactWriteItem v1Item = TransactWriteItem.builder().build();
|
||||
when(profilesV1.getTransactWriteItem(eq(uuid), eq(profileV1))).thenReturn(v1Item);
|
||||
|
||||
when(asyncCommands.del(ProfilesManager.getCacheKeyV1(uuid), ProfilesManager.getCacheKeyV2(uuid))).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
|
||||
doThrow(exceptionClass).when(profilesV2).set(eq(uuid), aryEq(version), aryEq(profileV2.data()), aryEq(profileV2.dataHash()), aryEq(profileV2.commitment()),
|
||||
aryEq(profileV2.paymentAddress()), aryEq(profileV2.paymentAddressHash()), aryEq(wrongHash), eq(v1Item));
|
||||
|
||||
assertThrows(exceptionClass, () -> profilesManager.set(uuid, profileV1, profileV2, wrongHash));
|
||||
|
||||
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)), aryEq(ProfilesManager.getCacheKeyV2(uuid)));
|
||||
}
|
||||
|
||||
static Collection<Arguments> testSetExceptionCleansUpCache() {
|
||||
return List.of(
|
||||
Arguments.of(WriteConflictException.class),
|
||||
Arguments.of(DynamoDbException.class)
|
||||
);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Redis {
|
||||
|
||||
@RegisterExtension
|
||||
private static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
|
||||
s3Client, BUCKET);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testSetGet(@Nullable final VersionedProfileV1 v1Profile, @Nullable final VersionedProfile v2Profile) {
|
||||
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
|
||||
profilesManager.redisSet(uuid, v2Profile, v1Profile);
|
||||
|
||||
if (v1Profile != null) {
|
||||
|
||||
final Optional<VersionedProfileV1> v1Actual = profilesManager.getV1(uuid, v1Profile.version());
|
||||
|
||||
assertTrue(v1Actual.isPresent());
|
||||
assertEquals(v1Profile, v1Actual.get());
|
||||
}
|
||||
|
||||
if (v2Profile != null) {
|
||||
final Optional<VersionedProfile> v2Actual = profilesManager.get(uuid, v2Profile.version());
|
||||
|
||||
assertTrue(v2Actual.isPresent());
|
||||
assertEquals(v2Profile, v2Actual.get());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static Collection<Arguments> testSetGet() throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final String versionHex = HexFormat.of().formatHex(version);
|
||||
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
final VersionedProfileV1 profileV1 = new VersionedProfileV1(versionHex, name, null, null, null, null, null, commitment);
|
||||
|
||||
final VersionedProfile profileV2 = new VersionedProfile(version, TestRandomUtil.nextBytes(128),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(64),
|
||||
TestRandomUtil.nextBytes(32), commitment);
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("only v1", profileV1, null),
|
||||
Arguments.argumentSet("only v2", null, profileV2),
|
||||
Arguments.argumentSet("both", profileV1, profileV2)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class ProfilesTest {
|
||||
@@ -36,7 +37,7 @@ public class ProfilesTest {
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.PROFILES);
|
||||
|
||||
private Profiles profiles;
|
||||
private VersionedProfile validProfile;
|
||||
private VersionedProfileV1 validProfile;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws InvalidInputException {
|
||||
@@ -51,28 +52,14 @@ public class ProfilesTest {
|
||||
final String avatar = "profiles/" + ProfileTestHelper.generateRandomBase64FromByteArray(16);
|
||||
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
|
||||
|
||||
validProfile = new VersionedProfile(version, name, avatar, validAboutEmoji, validAbout, null, phoneNumberSharing, commitment);
|
||||
validProfile = new VersionedProfileV1(version, name, avatar, validAboutEmoji, validAbout, null, phoneNumberSharing, commitment);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetGet() {
|
||||
profiles.set(ACI, validProfile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetGetAsync() {
|
||||
profiles.setAsync(ACI, validProfile).join();
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.getAsync(ACI, validProfile.version()).join();
|
||||
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, validProfile.version());
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
|
||||
@@ -97,12 +84,12 @@ public class ProfilesTest {
|
||||
final byte[] phoneNumberSharing = TestRandomUtil.nextBytes(29);
|
||||
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
VersionedProfile updatedProfile = new VersionedProfile(version, name, differentAvatar,
|
||||
VersionedProfileV1 updatedProfile = new VersionedProfileV1(version, name, differentAvatar,
|
||||
differentEmoji, differentAbout, paymentAddress, phoneNumberSharing, commitment);
|
||||
|
||||
profiles.set(ACI, updatedProfile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
|
||||
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, version);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().name()).isEqualTo(updatedProfile.name());
|
||||
@@ -118,11 +105,11 @@ public class ProfilesTest {
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
VersionedProfile profile = new VersionedProfile(version, name, null, null, null, null, null,
|
||||
VersionedProfileV1 profile = new VersionedProfileV1(version, name, null, null, null, null, null,
|
||||
commitment);
|
||||
profiles.set(ACI, profile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
|
||||
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, version);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().name()).isEqualTo(profile.name());
|
||||
@@ -136,7 +123,7 @@ public class ProfilesTest {
|
||||
void testSetReplace() throws InvalidInputException {
|
||||
profiles.set(ACI, validProfile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
|
||||
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, validProfile.version());
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
|
||||
@@ -153,7 +140,7 @@ public class ProfilesTest {
|
||||
final byte[] differentPhoneNumberSharing = TestRandomUtil.nextBytes(29);
|
||||
final byte[] differentCommitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
VersionedProfile updated = new VersionedProfile(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null,
|
||||
VersionedProfileV1 updated = new VersionedProfileV1(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null,
|
||||
differentPhoneNumberSharing, differentCommitment);
|
||||
profiles.set(ACI, updated);
|
||||
|
||||
@@ -187,14 +174,14 @@ public class ProfilesTest {
|
||||
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
|
||||
VersionedProfileV1 profileOne = new VersionedProfileV1(versionOne, nameOne, avatarOne, null, null,
|
||||
null, null, commitmentOne);
|
||||
VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
|
||||
VersionedProfileV1 profileTwo = new VersionedProfileV1(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
|
||||
|
||||
profiles.set(ACI, profileOne);
|
||||
profiles.set(ACI, profileTwo);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, versionOne);
|
||||
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, versionOne);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().name()).isEqualTo(profileOne.name());
|
||||
@@ -218,7 +205,7 @@ public class ProfilesTest {
|
||||
profiles.set(ACI, validProfile);
|
||||
final String missingVersion = "missingVersion";
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, missingVersion);
|
||||
Optional<VersionedProfileV1> retrieved = profiles.get(ACI, missingVersion);
|
||||
assertThat(retrieved.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@@ -242,10 +229,10 @@ public class ProfilesTest {
|
||||
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] commitmentThree = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
|
||||
VersionedProfileV1 profileOne = new VersionedProfileV1(versionOne, nameOne, avatarOne, null, null,
|
||||
null, null, commitmentOne);
|
||||
VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
|
||||
VersionedProfile profileThree = new VersionedProfile(versionThree, nameTwo, null, aboutEmoji, about, null, null,
|
||||
VersionedProfileV1 profileTwo = new VersionedProfileV1(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, null, commitmentTwo);
|
||||
VersionedProfileV1 profileThree = new VersionedProfileV1(versionThree, nameTwo, null, aboutEmoji, about, null, null,
|
||||
commitmentThree);
|
||||
|
||||
profiles.set(ACI, profileOne);
|
||||
@@ -255,7 +242,7 @@ public class ProfilesTest {
|
||||
final List<String> avatars = profiles.deleteAll(ACI).join();
|
||||
|
||||
for (String version : List.of(versionOne, versionTwo, versionThree)) {
|
||||
final Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
|
||||
final Optional<VersionedProfileV1> retrieved = profiles.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@@ -263,9 +250,23 @@ public class ProfilesTest {
|
||||
assertThat(avatars.containsAll(List.of(avatarOne, avatarTwo))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetTransactWriteItem() {
|
||||
final TransactWriteItem transactWriteItem = profiles.getTransactWriteItem(ACI, validProfile);
|
||||
|
||||
assertThat(transactWriteItem).isNotNull()
|
||||
.extracting(TransactWriteItem::update).isNotNull();
|
||||
|
||||
assertThat(transactWriteItem.update().tableName()).isEqualTo(Tables.PROFILES.tableName());
|
||||
assertThat(transactWriteItem.update().key()).isNotNull();
|
||||
assertThat(transactWriteItem.update().updateExpression()).isEqualTo(Profiles.buildUpdateExpression(validProfile));
|
||||
assertThat(transactWriteItem.update().expressionAttributeValues())
|
||||
.isEqualTo(Profiles.buildUpdateExpressionAttributeValues(validProfile));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void buildUpdateExpression(final VersionedProfile profile, final String expectedUpdateExpression) {
|
||||
void buildUpdateExpression(final VersionedProfileV1 profile, final String expectedUpdateExpression) {
|
||||
assertEquals(expectedUpdateExpression, Profiles.buildUpdateExpression(profile));
|
||||
}
|
||||
|
||||
@@ -281,38 +282,38 @@ public class ProfilesTest {
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji, #paymentAddress = :paymentAddress, #phoneNumberSharing = :phoneNumberSharing"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji, #paymentAddress = :paymentAddress REMOVE #phoneNumberSharing"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, about, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, about, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji REMOVE #paymentAddress, #phoneNumberSharing"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, null, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #aboutEmoji = :aboutEmoji REMOVE #about, #paymentAddress, #phoneNumberSharing"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, null, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, null, null, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar REMOVE #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, null, null, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, null, null, null, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name REMOVE #avatar, #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, null, null, null, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, null, null, null, null, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment) REMOVE #name, #avatar, #about, #aboutEmoji, #paymentAddress, #phoneNumberSharing")
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void buildUpdateExpressionAttributeValues(final VersionedProfile profile, final Map<String, AttributeValue> expectedAttributeValues) {
|
||||
void buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile, final Map<String, AttributeValue> expectedAttributeValues) {
|
||||
assertEquals(expectedAttributeValues, Profiles.buildUpdateExpressionAttributeValues(profile));
|
||||
}
|
||||
|
||||
@@ -328,7 +329,7 @@ public class ProfilesTest {
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, phoneNumberSharing, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromByteArray(name),
|
||||
@@ -339,7 +340,7 @@ public class ProfilesTest {
|
||||
":phoneNumberSharing", AttributeValues.fromByteArray(phoneNumberSharing))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, about, paymentAddress, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromByteArray(name),
|
||||
@@ -349,7 +350,7 @@ public class ProfilesTest {
|
||||
":paymentAddress", AttributeValues.fromByteArray(paymentAddress))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, about, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, about, null, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromByteArray(name),
|
||||
@@ -358,7 +359,7 @@ public class ProfilesTest {
|
||||
":about", AttributeValues.fromByteArray(about))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, emoji, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, emoji, null, null, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name",AttributeValues.fromByteArray(name),
|
||||
@@ -366,20 +367,20 @@ public class ProfilesTest {
|
||||
":aboutEmoji", AttributeValues.fromByteArray(emoji))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, avatar, null, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, avatar, null, null, null, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromByteArray(name),
|
||||
":avatar", AttributeValues.fromString(avatar))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, name, null, null, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, name, null, null, null, null, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromByteArray(name))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile(version, null, null, null, null, null, null, commitment),
|
||||
new VersionedProfileV1(version, null, null, null, null, null, null, commitment),
|
||||
Map.of(":commitment", AttributeValues.fromByteArray(commitment)))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class ProfilesV2Test {
|
||||
private static final UUID ACI = UUID.randomUUID();
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.PROFILES_V2);
|
||||
|
||||
private ProfilesV2 profilesV2;
|
||||
private byte[] version;
|
||||
private byte[] data;
|
||||
private byte[] commitment;
|
||||
private byte[] paymentAddress;
|
||||
|
||||
private VersionedProfile profile;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws InvalidInputException {
|
||||
profilesV2 = new ProfilesV2(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
Tables.PROFILES_V2.tableName());
|
||||
|
||||
commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
version = TestRandomUtil.nextBytes(32);
|
||||
data = TestRandomUtil.nextBytes(256);
|
||||
paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
|
||||
profile = new VersionedProfile(version, data, paymentAddress, commitment);
|
||||
}
|
||||
|
||||
/// Generates a no-op transaction write item for tests that don’t need a real one
|
||||
private TransactWriteItem getAdditionalTransactWriteItem() {
|
||||
return TransactWriteItem.builder()
|
||||
.conditionCheck(builder -> builder
|
||||
.tableName(Tables.PROFILES_V2.tableName())
|
||||
.key(Map.of(
|
||||
ProfilesV2.KEY_ACCOUNT_UUID, AttributeValues.b(UUID.randomUUID()),
|
||||
ProfilesV2.KEY_VERSION, AttributeValue.builder().b(SdkBytes.fromByteArray("not-a-real-version".getBytes())).build()))
|
||||
.conditionExpression("attribute_not_exists(#uuid)")
|
||||
.expressionAttributeNames(Map.of("#uuid", ProfilesV2.KEY_ACCOUNT_UUID)))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetFirstWrite() throws WriteConflictException {
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem());
|
||||
|
||||
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(data);
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(commitment);
|
||||
assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress);
|
||||
assertThat(retrieved.get().dataHash()).isNotNull();
|
||||
assertThat(retrieved.get().paymentAddressHash()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetWithoutPaymentAddress() throws WriteConflictException {
|
||||
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), null, null, null, getAdditionalTransactWriteItem());
|
||||
|
||||
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(data);
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(commitment);
|
||||
assertThat(retrieved.get().paymentAddress()).isNull();
|
||||
assertThat(retrieved.get().paymentAddressHash()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInitialSetRequiresCommitment() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), null, profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConditionalUpdateSuccess() throws WriteConflictException {
|
||||
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), null, getAdditionalTransactWriteItem());
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
|
||||
// Update with correct expected hash
|
||||
final byte[] newData = TestRandomUtil.nextBytes(256);
|
||||
profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
|
||||
|
||||
retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(newData);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConditionalUpdateFailure() throws WriteConflictException {
|
||||
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
|
||||
|
||||
final byte[] wrongHash = TestRandomUtil.nextBytes(32);
|
||||
|
||||
assertThrows(WriteConflictException.class, () -> {
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(), wrongHash, getAdditionalTransactWriteItem());
|
||||
});
|
||||
|
||||
// Verify data is unchanged
|
||||
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(data);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommitmentImmutability() throws InvalidInputException, WriteConflictException {
|
||||
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
|
||||
// Try to update with a different commitment
|
||||
final byte[] newData = TestRandomUtil.nextBytes(256);
|
||||
final byte[] differentCommitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), differentCommitment, profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(),
|
||||
getAdditionalTransactWriteItem()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateWithNullCommitmentSucceeds() throws WriteConflictException {
|
||||
profilesV2.set(ACI,profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
final byte[] originalCommitment = retrieved.get().commitment();
|
||||
|
||||
final byte[] newData = TestRandomUtil.nextBytes(256);
|
||||
profilesV2.set(ACI, profile.version(), newData, VersionedProfile.hash(newData), null, profile.paymentAddress(), profile.paymentAddressHash(), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
|
||||
|
||||
retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(newData);
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(originalCommitment);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultipleVersions() throws InvalidInputException, WriteConflictException {
|
||||
final byte[] versionOne = TestRandomUtil.nextBytes(32);
|
||||
final byte[] versionTwo = TestRandomUtil.nextBytes(32);
|
||||
|
||||
final byte[] dataOne = TestRandomUtil.nextBytes(256);
|
||||
final byte[] dataTwo = TestRandomUtil.nextBytes(256);
|
||||
|
||||
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
profilesV2.set(ACI, versionOne, dataOne, VersionedProfile.hash(dataOne), commitmentOne, paymentAddress,
|
||||
VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
|
||||
profilesV2.set(ACI, versionTwo, dataTwo, VersionedProfile.hash(dataTwo), commitmentTwo, null, null,null, getAdditionalTransactWriteItem());
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, versionOne);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(dataOne);
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(commitmentOne);
|
||||
assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress);
|
||||
|
||||
retrieved = profilesV2.get(ACI, versionTwo);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(dataTwo);
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(commitmentTwo);
|
||||
assertThat(retrieved.get().paymentAddress()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMissing() throws WriteConflictException {
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
|
||||
final byte[] missingVersion = TestRandomUtil.nextBytes(32);
|
||||
|
||||
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, missingVersion);
|
||||
assertThat(retrieved.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteAll() throws InvalidInputException, WriteConflictException {
|
||||
final byte[] versionOne = TestRandomUtil.nextBytes(32);
|
||||
final byte[] versionTwo = TestRandomUtil.nextBytes(32);
|
||||
final byte[] versionThree = TestRandomUtil.nextBytes(32);
|
||||
|
||||
final byte[] dataOne = TestRandomUtil.nextBytes(256);
|
||||
final byte[] dataTwo = TestRandomUtil.nextBytes(256);
|
||||
final byte[] dataThree = TestRandomUtil.nextBytes(256);
|
||||
|
||||
final byte[] commitmentOne = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] commitmentTwo = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] commitmentThree = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
profilesV2.set(ACI, versionOne, dataOne, VersionedProfile.hash(dataOne), commitmentOne, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
|
||||
profilesV2.set(ACI, versionTwo, dataTwo, VersionedProfile.hash(dataTwo), commitmentTwo, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
|
||||
profilesV2.set(ACI, versionThree, dataThree, VersionedProfile.hash(dataThree), commitmentThree, null, null,null, getAdditionalTransactWriteItem());
|
||||
|
||||
profilesV2.deleteAll(ACI).join();
|
||||
|
||||
for (byte[] v : List.of(versionOne, versionTwo, versionThree)) {
|
||||
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, v);
|
||||
assertThat(retrieved.isPresent()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdatePaymentAddress() throws WriteConflictException {
|
||||
|
||||
profilesV2.set(ACI, profile.version(), profile.data(), profile.dataHash(), profile.commitment(), profile.paymentAddress(), profile.paymentAddressHash(),null, getAdditionalTransactWriteItem());
|
||||
|
||||
Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().paymentAddress()).isEqualTo(paymentAddress);
|
||||
|
||||
// Update to remove payment address
|
||||
final byte[] newData = TestRandomUtil.nextBytes(256);
|
||||
profilesV2.set(ACI, version, newData, VersionedProfile.hash(newData), commitment, null, null, retrieved.get().dataHash(), getAdditionalTransactWriteItem());
|
||||
|
||||
retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().data()).isEqualTo(newData);
|
||||
assertThat(retrieved.get().paymentAddress()).isNull();
|
||||
assertThat(retrieved.get().paymentAddressHash()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetWithAdditionalTransactWriteItemConflict() throws WriteConflictException {
|
||||
|
||||
profilesV2.set(ACI, version, data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), null, getAdditionalTransactWriteItem());
|
||||
|
||||
final Optional<VersionedProfile> retrieved = profilesV2.get(ACI, version);
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
|
||||
// write an update
|
||||
final byte[] updatedData = TestRandomUtil.nextBytes(256);
|
||||
profilesV2.set(ACI, version, updatedData, VersionedProfile.hash(updatedData), null, paymentAddress, VersionedProfile.hash(paymentAddress), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
|
||||
|
||||
// attempt a second update with a stale hash
|
||||
assertThrows(WriteConflictException.class, () -> {
|
||||
final byte[] conflictedData = TestRandomUtil.nextBytes(256);
|
||||
profilesV2.set(ACI, version, conflictedData, VersionedProfile.hash(conflictedData), null, paymentAddress, VersionedProfile.hash(paymentAddress), retrieved.get().dataHash(), getAdditionalTransactWriteItem());
|
||||
});
|
||||
|
||||
// still has updatedData
|
||||
final Optional<VersionedProfile> retrievedV2 = profilesV2.get(ACI, version);
|
||||
assertThat(retrievedV2.isPresent()).isTrue();
|
||||
assertThat(retrievedV2.get().data()).isEqualTo(updatedData);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void testGetTransactWriteItem(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean hasCommitment,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean hasExpectedDataHash) {
|
||||
final byte[] commitment = hasCommitment ? profile.commitment() : null;
|
||||
final byte[] expectedDataHash = hasExpectedDataHash ? TestRandomUtil.nextBytes(32) : null;
|
||||
|
||||
final TransactWriteItem transactWriteItem = profilesV2.getTransactWriteItem(
|
||||
ACI, profile.version(), profile.data(), profile.dataHash(), commitment, profile.paymentAddress(), profile.paymentAddressHash(), expectedDataHash);
|
||||
|
||||
assertThat(transactWriteItem).isNotNull();
|
||||
assertThat(transactWriteItem.update()).isNotNull();
|
||||
assertThat(transactWriteItem.update().tableName()).isEqualTo(Tables.PROFILES_V2.tableName());
|
||||
assertThat(transactWriteItem.update().key()).isNotNull();
|
||||
assertThat(transactWriteItem.update().updateExpression()).isEqualTo(ProfilesV2.buildUpdateExpression(commitment != null, paymentAddress != null));
|
||||
assertThat(transactWriteItem.update().conditionExpression()).isEqualTo(ProfilesV2.buildConditionExpression(commitment != null, expectedDataHash != null));
|
||||
assertThat(transactWriteItem.update().expressionAttributeValues())
|
||||
.isEqualTo(ProfilesV2.buildUpdateExpressionAttributeValues(data, profile.dataHash(), commitment, paymentAddress, profile.paymentAddressHash(), expectedDataHash));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testBuildUpdateExpression(final byte[] commitment, final byte[] paymentAddress, final String expectedUpdateExpression) {
|
||||
assertEquals(expectedUpdateExpression, ProfilesV2.buildUpdateExpression(commitment != null, paymentAddress != null));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testBuildUpdateExpression() {
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(32);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("with commitment and payment address",
|
||||
commitment,
|
||||
paymentAddress,
|
||||
"SET #data = :data, #dataHash = :dataHash, #commitment = if_not_exists(#commitment, :commitment), #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash"),
|
||||
Arguments.argumentSet("with commitment, without payment address",
|
||||
commitment,
|
||||
null,
|
||||
"SET #data = :data, #dataHash = :dataHash, #commitment = if_not_exists(#commitment, :commitment) REMOVE #paymentAddress, #paymentAddressHash"),
|
||||
Arguments.argumentSet("without commitment, with payment address",
|
||||
null,
|
||||
paymentAddress,
|
||||
"SET #data = :data, #dataHash = :dataHash, #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash"),
|
||||
Arguments.argumentSet("without commitment or payment address",
|
||||
null,
|
||||
null,
|
||||
"SET #data = :data, #dataHash = :dataHash REMOVE #paymentAddress, #paymentAddressHash")
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testBuildConditionExpression(final byte[] commitment, final byte[] expectedCurrentDataHash, final String expectedConditionExpression) {
|
||||
assertEquals(expectedConditionExpression, ProfilesV2.buildConditionExpression(commitment != null, expectedCurrentDataHash != null));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testBuildConditionExpression() {
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] dataHash = TestRandomUtil.nextBytes(32);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("initial write",
|
||||
commitment,
|
||||
null,
|
||||
"(attribute_not_exists(#commitment) OR #commitment = :commitment) AND attribute_not_exists(#dataHash)"),
|
||||
Arguments.argumentSet("update with commitment",
|
||||
commitment,
|
||||
dataHash,
|
||||
"(attribute_not_exists(#commitment) OR #commitment = :commitment) AND #dataHash = :expectedDataHash"),
|
||||
Arguments.argumentSet("update without commitment",
|
||||
null,
|
||||
dataHash,
|
||||
"size(#commitment) = :commitment_length AND #dataHash = :expectedDataHash")
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testBuildUpdateExpressionAttributeValues(
|
||||
final byte[] data,
|
||||
final byte[] dataHash,
|
||||
final byte[] commitment,
|
||||
final byte[] paymentAddress,
|
||||
final byte[] paymentAddressHash,
|
||||
final byte[] expectedCurrentDataHash,
|
||||
final int expectedMapSize) {
|
||||
|
||||
final Map<String, AttributeValue> result = ProfilesV2.buildUpdateExpressionAttributeValues(
|
||||
data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash);
|
||||
|
||||
assertEquals(expectedMapSize, result.size());
|
||||
assertThat(result.containsKey(":data")).isTrue();
|
||||
assertThat(result.containsKey(":dataHash")).isTrue();
|
||||
|
||||
if (commitment != null) {
|
||||
assertThat(result.containsKey(":commitment")).isTrue();
|
||||
} else {
|
||||
assertThat(result.containsKey(":commitment_length")).isTrue();
|
||||
}
|
||||
|
||||
if (expectedCurrentDataHash != null) {
|
||||
assertThat(result.containsKey(":expectedDataHash")).isTrue();
|
||||
}
|
||||
|
||||
if (paymentAddress != null) {
|
||||
assertThat(result.containsKey(":paymentAddress")).isTrue();
|
||||
assertThat(result.containsKey(":paymentAddressHash")).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testBuildUpdateExpressionAttributeValues() throws InvalidInputException {
|
||||
final byte[] data = TestRandomUtil.nextBytes(256);
|
||||
final byte[] commitment = new ProfileKey(TestRandomUtil.nextBytes(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] dataHash = TestRandomUtil.nextBytes(32);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("all fields present",
|
||||
data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), dataHash, 6),
|
||||
Arguments.argumentSet("no payment address",
|
||||
data, VersionedProfile.hash(data), commitment, null, null, dataHash, 4),
|
||||
Arguments.argumentSet("no commitment",
|
||||
data, VersionedProfile.hash(data), null, paymentAddress, VersionedProfile.hash(paymentAddress), dataHash, 6),
|
||||
Arguments.argumentSet("only data fields",
|
||||
data, VersionedProfile.hash(data), null, null, null, dataHash, 4)
|
||||
);
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testSetWithTransactionCanceledException(final Optional<List<String>> maybeCodes, final Class<? extends Exception> expectedException) throws InvalidInputException {
|
||||
final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class);
|
||||
final ProfilesV2 profilesV2 = new ProfilesV2(dynamoDbClient, mock(DynamoDbAsyncClient.class), Tables.PROFILES_V2.tableName());
|
||||
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] version = TestRandomUtil.nextBytes(32);
|
||||
final byte[] data = TestRandomUtil.nextBytes(256);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
final byte[] expectedHash = TestRandomUtil.nextBytes(32);
|
||||
|
||||
final TransactionCanceledException.Builder exceptionBuilder = TransactionCanceledException.builder();
|
||||
maybeCodes.ifPresent(codes -> {
|
||||
final CancellationReason[] cancellationReasons = codes.stream().map(code ->
|
||||
CancellationReason.builder().code(code).build())
|
||||
.toArray(CancellationReason[]::new);
|
||||
|
||||
exceptionBuilder.cancellationReasons(cancellationReasons);
|
||||
});
|
||||
final TransactionCanceledException exception = exceptionBuilder.build();
|
||||
|
||||
when(dynamoDbClient.transactWriteItems(any(TransactWriteItemsRequest.class)))
|
||||
.thenThrow(exception);
|
||||
|
||||
assertThrows(expectedException, () ->
|
||||
profilesV2.set(uuid, version, data, VersionedProfile.hash(data), commitment, paymentAddress, VersionedProfile.hash(paymentAddress), expectedHash, getAdditionalTransactWriteItem()));
|
||||
}
|
||||
|
||||
static Collection<Arguments> testSetWithTransactionCanceledException() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ConditionalCheckFailed")), WriteConflictException.class),
|
||||
Arguments.argumentSet("TransactionConflict throws WriteConflictException", Optional.of(List.of("TransactionConflict")), WriteConflictException.class),
|
||||
Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ConditionalCheckFailed", "ThrottlingError")), WriteConflictException.class),
|
||||
Arguments.argumentSet("ConditionalCheckFailed throws WriteConflictException", Optional.of(List.of("ThrottlingError", "ConditionalCheckFailed")), WriteConflictException.class),
|
||||
Arguments.argumentSet("ThrottlingError throws TransactionCanceledException", Optional.of(List.of("ThrottlingError")), TransactionCanceledException.class),
|
||||
Arguments.argumentSet("No code throws TransactionCanceledException", Optional.empty(), TransactionCanceledException.class)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user