mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 11:46:53 +00:00
Add avatars to profiles gRPC
This commit is contained in:
1 parent
f588390bdb
commit
feb00c6ba6
27 files changed
+1173
-84
No files matched your search
+8
-7
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
@@ -61,6 +60,8 @@ import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
@@ -707,15 +708,15 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
|
||||
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) throws Exception {
|
||||
|
||||
final byte[] publicKey = TestRandomUtil.nextBytes(33);
|
||||
final ZkCredentialPublicKey publicKey = ZkCredentialKeyPair.generate().getPublicKey();
|
||||
final long rotationId = ThreadLocalRandom.current().nextLong(1, Long.MAX_VALUE);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
|
||||
if (matchesCurrentZkCredentialKey) {
|
||||
when(account.getZkCredentialKey()).thenReturn(publicKey);
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.of(publicKey));
|
||||
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
|
||||
}
|
||||
|
||||
@@ -724,7 +725,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
final SetZkCredentialKeyResponse response = assertDoesNotThrow(() ->
|
||||
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
|
||||
.setPublicKey(ByteString.copyFrom(publicKey))
|
||||
.setPublicKey(ByteString.copyFrom(publicKey.serialize()))
|
||||
.build()));
|
||||
|
||||
if (matchesCurrentZkCredentialKey) {
|
||||
@@ -736,13 +737,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
final int updateMethodCalls = matchesCurrentZkCredentialKey ? 0 : 1;
|
||||
|
||||
verify(accountsManager, times(updateMethodCalls)).update(eq(AUTHENTICATED_ACI), any());
|
||||
verify(account, times(updateMethodCalls)).setZkCredentialKey(aryEq(publicKey));
|
||||
verify(account, times(updateMethodCalls)).setZkCredentialKey(publicKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setZkCredentialKeyRateLimited() throws Exception {
|
||||
|
||||
final byte[] publicKey = TestRandomUtil.nextBytes(33);
|
||||
final byte[] publicKey = ZkCredentialKeyPair.generate().getPublicKey().serialize();
|
||||
final Duration retryDuration = Duration.ofDays(1);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
|
||||
+218
-9
@@ -13,6 +13,8 @@ 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.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -20,12 +22,15 @@ import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
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.protobuf.ByteString;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import com.google.rpc.BadRequest;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -38,6 +43,7 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -50,6 +56,12 @@ import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.DeleteAvatarRequest;
|
||||
import org.signal.chat.profile.DeleteAvatarResponse;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLRequest;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLResponse;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormRequest;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
|
||||
@@ -66,8 +78,13 @@ 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.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
@@ -78,9 +95,13 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -89,6 +110,8 @@ 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.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -108,8 +131,15 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
@Mock
|
||||
private ProfileBadgeConverter profileBadgeConverter;
|
||||
|
||||
@Mock
|
||||
private RateLimiter profileAvatarBytesRateLimiter;
|
||||
|
||||
private ServerZkProfileOperations zkProfileOperations;
|
||||
|
||||
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
|
||||
|
||||
private MutableClock clock;
|
||||
|
||||
@Override
|
||||
protected ProfileAnonymousGrpcService createServiceBeforeEachTest() {
|
||||
getMockRequestAttributesInterceptor().setRequestAttributes(new RequestAttributes(InetAddresses.forString("127.0.0.1"),
|
||||
@@ -118,12 +148,21 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
|
||||
zkProfileOperations = spy(new ServerZkProfileOperations(SERVER_SECRET_PARAMS));
|
||||
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
when(rateLimiters.getProfileAvatarBytesLimiter()).thenReturn(profileAvatarBytesRateLimiter);
|
||||
|
||||
clock = new MutableClock();
|
||||
|
||||
return new ProfileAnonymousGrpcService(
|
||||
accountsManager,
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey", "accessSecret"),
|
||||
genericServerSecretParams,
|
||||
rateLimiters,
|
||||
clock,
|
||||
zkProfileOperations,
|
||||
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, Clock.systemUTC())
|
||||
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, clock)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -788,12 +827,182 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
|
||||
return serverInterceptors.stream()
|
||||
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
|
||||
// updated error model
|
||||
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
|
||||
.toList();
|
||||
@Test
|
||||
void getAvatarUploadForm() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(100)
|
||||
.build();
|
||||
|
||||
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
|
||||
|
||||
assertTrue(response.hasAvatarUploadForm());
|
||||
|
||||
final String avatarPath = response.getAvatarUploadForm().getKey();
|
||||
assertFalse(avatarPath.isEmpty());
|
||||
|
||||
verify(profilesManager).setAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()), eq(avatarPath));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarUploadFormInvalidUploadLength() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(Math.toIntExact(ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES + 1))
|
||||
.build();
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().getAvatarUploadForm(request));
|
||||
|
||||
final List<BadRequest.FieldViolation> fieldViolations = GrpcTestUtils.extractDetail(BadRequest.class, statusRuntimeException)
|
||||
.getFieldViolationsList();
|
||||
|
||||
assertEquals(1, fieldViolations.size());
|
||||
assertEquals("upload_length", fieldViolations.getFirst().getField());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarUploadFormInvalidCredentialsPresentation() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(100)
|
||||
.build();
|
||||
|
||||
// trigger a verification failure by advancing the clock beyond validity
|
||||
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
|
||||
|
||||
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
|
||||
|
||||
assertTrue(response.hasInvalidCredentialsPresentation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarUploadFormRateLimited() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final Duration retryDuration = Duration.ofMinutes(20);
|
||||
doThrow(new RateLimitExceededException(retryDuration))
|
||||
.when(profileAvatarBytesRateLimiter).validate(anyString(), anyLong());
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(100)
|
||||
.build();
|
||||
|
||||
assertRateLimitExceeded(retryDuration,
|
||||
() -> authenticatedServiceStub().getAvatarUploadForm(request),
|
||||
profilesManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtl() throws Exception {
|
||||
final String path = "somePath";
|
||||
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.of(path));
|
||||
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
|
||||
|
||||
assertTrue(response.hasPath());
|
||||
|
||||
assertEquals(path, response.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlNoActiveAvatar() throws Exception {
|
||||
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.empty());
|
||||
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
|
||||
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
|
||||
|
||||
assertTrue(response.hasNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlInvalidCredentialsPresentation() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
// trigger a verification failure by advancing the clock beyond validity
|
||||
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
|
||||
|
||||
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
|
||||
|
||||
assertTrue(response.hasInvalidCredentialsPresentation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatar() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
|
||||
|
||||
assertTrue(response.hasSuccess());
|
||||
|
||||
verify(profilesManager).deleteAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatarInvalidCredentialsPresentation() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
// trigger a verification failure by advancing the clock beyond validity
|
||||
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
|
||||
|
||||
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
|
||||
|
||||
assertTrue(response.hasInvalidCredentialsPresentation());
|
||||
}
|
||||
|
||||
static AvatarUploadCredentialPresentation getAvatarUploadCredentialPresentation(final GenericServerSecretParams serverSecretParams, final Clock clock) throws VerificationFailedException {
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(UUID.randomUUID());
|
||||
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
|
||||
final long rotationId = ThreadLocalRandom.current().nextLong();
|
||||
|
||||
final AvatarUploadCredentialRequestContext context = AvatarUploadCredentialRequestContext.create(
|
||||
aci,
|
||||
zkCredentialKeyPair, rotationId);
|
||||
|
||||
final AvatarUploadCredentialResponse avatarUploadCredentialResponse = context.getRequest()
|
||||
.issueCredential(aci, zkCredentialKeyPair.getPublicKey(), rotationId, clock.instant().truncatedTo(ChronoUnit.DAYS), serverSecretParams);
|
||||
|
||||
return context.receiveResponse(avatarUploadCredentialResponse, clock.instant(),
|
||||
serverSecretParams.getPublicParams()).present(serverSecretParams.getPublicParams());
|
||||
}
|
||||
}
|
||||
+85
-10
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -31,7 +32,6 @@ 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 io.grpc.StatusRuntimeException;
|
||||
import java.time.Clock;
|
||||
@@ -60,6 +60,8 @@ import org.mockito.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
@@ -77,7 +79,12 @@ 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.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
@@ -106,6 +113,7 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -122,6 +130,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(TestRandomUtil.nextBytes(29)))
|
||||
.build();
|
||||
|
||||
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
|
||||
|
||||
@Mock
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@@ -143,11 +153,11 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
@Mock
|
||||
private ProfileBadgeConverter profileBadgeConverter;
|
||||
|
||||
private Clock clock;
|
||||
private MutableClock clock;
|
||||
|
||||
@Override
|
||||
protected ProfileGrpcService createServiceBeforeEachTest() {
|
||||
clock = Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC"));
|
||||
clock = new MutableClock(Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC")));
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
@@ -208,6 +218,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
dynamicConfigurationManager,
|
||||
badgesConfiguration,
|
||||
policyGenerator,
|
||||
genericServerSecretParams,
|
||||
profileBadgeConverter,
|
||||
rateLimiters
|
||||
);
|
||||
@@ -893,13 +904,77 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
|
||||
return serverInterceptors.stream()
|
||||
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
|
||||
// updated error model
|
||||
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
|
||||
.toList();
|
||||
@Test
|
||||
void getAvatarCredential() {
|
||||
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
|
||||
final long rotationId = 617L;
|
||||
|
||||
// this test needs a valid clock
|
||||
clock.setTimeMillis(Instant.now().toEpochMilli());
|
||||
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
|
||||
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
|
||||
|
||||
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
|
||||
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, rotationId);
|
||||
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
|
||||
|
||||
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
|
||||
GetAvatarCredentialsRequest.newBuilder()
|
||||
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasAvatarCredentials());
|
||||
|
||||
assertDoesNotThrow(() -> avatarUploadCredentialRequestContext.receiveResponse(
|
||||
new AvatarUploadCredentialResponse(response.getAvatarCredentials().toByteArray()),
|
||||
genericServerSecretParams.getPublicParams()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarCredentialAccountNotFound() {
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.empty());
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
|
||||
() -> authenticatedServiceStub().getAvatarCredentials(GetAvatarCredentialsRequest.getDefaultInstance()));
|
||||
assertEquals("account not found", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarCredentialMissingZkCredentialKey() {
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.empty());
|
||||
|
||||
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
|
||||
GetAvatarCredentialsRequest.getDefaultInstance());
|
||||
|
||||
assertTrue(response.hasMissingZkCredentialKey());
|
||||
|
||||
assertEquals("account requires ZK credential key", response.getMissingZkCredentialKey().getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarCredentialInvalidCredentialRequest() {
|
||||
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
|
||||
final long rotationId = 617L;
|
||||
final long incorrectRotationId = rotationId + 1;
|
||||
|
||||
// this test needs a valid clock
|
||||
clock.setTimeMillis(Instant.now().toEpochMilli());
|
||||
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
|
||||
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
|
||||
|
||||
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
|
||||
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, incorrectRotationId);
|
||||
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().getAvatarCredentials(
|
||||
GetAvatarCredentialsRequest.newBuilder()
|
||||
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
|
||||
.build()));
|
||||
|
||||
assertEquals("invalid credential request", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
@@ -23,6 +23,7 @@ import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil.assertFailsWithCause;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
@@ -49,7 +50,6 @@ import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
@@ -59,6 +59,7 @@ 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.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
@@ -471,7 +472,7 @@ class AccountsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReclaimAccountPreservesFields() {
|
||||
void testReclaimAccountPreservesFields() throws Exception {
|
||||
final String e164 = "+14151112222";
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
final Account existingAccount =
|
||||
@@ -479,7 +480,7 @@ class AccountsTest {
|
||||
|
||||
// the backup credential request and share-set are always preserved across account reclaims
|
||||
existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
|
||||
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
|
||||
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
|
||||
createAccount(existingAccount);
|
||||
final Account secondAccount =
|
||||
generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
|
||||
@@ -491,11 +492,11 @@ class AccountsTest {
|
||||
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElseThrow());
|
||||
assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow())
|
||||
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow());
|
||||
assertThat(reclaimed.getZkCredentialKey()).isEqualTo(existingAccount.getZkCredentialKey());
|
||||
assertThat(reclaimed.getZkCredentialKey()).hasValue(existingAccount.getZkCredentialKey().orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReclaimAccount() throws UsernameHashNotAvailableException {
|
||||
void testReclaimAccount() throws Exception {
|
||||
final String e164 = "+14151112222";
|
||||
final Device device = generateDevice(DEVICE_ID_1);
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
@@ -506,7 +507,7 @@ class AccountsTest {
|
||||
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
|
||||
existingAccount.setBackupVoucher(bv);
|
||||
// ZK credential keys should be carried over across re-registration
|
||||
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
|
||||
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
|
||||
|
||||
createAccount(existingAccount);
|
||||
|
||||
|
||||
+9
@@ -275,6 +275,15 @@ public final class DynamoDbExtensionSchema {
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
PROFILE_AVATARS("profileAvatars_test",
|
||||
ProfileAvatars.KEY_IDENTITY,
|
||||
null,
|
||||
List.of(AttributeDefinition.builder()
|
||||
.attributeName(ProfileAvatars.KEY_IDENTITY)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
PROFILES_V2("profilesV2_test",
|
||||
ProfilesV2.KEY_ACCOUNT_UUID,
|
||||
ProfilesV2.KEY_VERSION,
|
||||
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
|
||||
class ProfileAvatarsTest {
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS);
|
||||
|
||||
private ProfileAvatars profileAvatars;
|
||||
|
||||
private static final Duration EXPIRATION = Duration.ofDays(1);
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now().truncatedTo(ChronoUnit.SECONDS));
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
profileAvatars = new ProfileAvatars(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName(), EXPIRATION, CLOCK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSet() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
final String avatarUrl1 = "avatar";
|
||||
|
||||
{
|
||||
final Optional<String> previousAvatar = profileAvatars.setAvatarUrl(identity, avatarUrl1);
|
||||
assertTrue(previousAvatar.isEmpty());
|
||||
}
|
||||
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(avatarUrl1, response.item().get(ProfileAvatars.ATTR_URL).s());
|
||||
assertEquals(CLOCK.instant().plus(EXPIRATION),
|
||||
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
|
||||
}
|
||||
|
||||
final String avatarUrl2 = "avatar2";
|
||||
|
||||
{
|
||||
final Optional<String> previousAvatar = profileAvatars.setAvatarUrl(identity, avatarUrl2);
|
||||
assertEquals(Optional.of(avatarUrl1), previousAvatar);
|
||||
}
|
||||
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(avatarUrl2, response.item().get(ProfileAvatars.ATTR_URL).s());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateTtl() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
final String avatarUrl = "avatar";
|
||||
|
||||
profileAvatars.setAvatarUrl(identity, avatarUrl);
|
||||
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(CLOCK.instant().plus(EXPIRATION),
|
||||
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
|
||||
}
|
||||
final Instant later = CLOCK.instant().plus(Duration.ofDays(30));
|
||||
CLOCK.pin(later);
|
||||
|
||||
profileAvatars.updateAvatarTtl(identity);
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(later.plus(EXPIRATION),
|
||||
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateTtlNotPresent() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
|
||||
assertTrue(profileAvatars.updateAvatarTtl(identity).isEmpty());
|
||||
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertFalse(response.hasItem(), "item should not be created as a side effect");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDelete() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
|
||||
assertTrue(profileAvatars.deleteAvatarUrl(identity).isEmpty());
|
||||
|
||||
final String avatarUrl = "avatar";
|
||||
|
||||
profileAvatars.setAvatarUrl(identity, avatarUrl);
|
||||
|
||||
final Optional<String> deletedUrl = profileAvatars.deleteAvatarUrl(identity);
|
||||
assertTrue(deletedUrl.isPresent());
|
||||
assertEquals(avatarUrl, deletedUrl.get());
|
||||
|
||||
assertTrue(profileAvatars.deleteAvatarUrl(identity).isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
+109
-2
@@ -11,10 +11,12 @@ 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.anyString;
|
||||
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.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
@@ -42,6 +44,7 @@ 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.ArgumentCaptor;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
@@ -56,13 +59,18 @@ 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.CopyObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class ProfilesManagerTest {
|
||||
|
||||
private Profiles profilesV1;
|
||||
private ProfilesV2 profilesV2;
|
||||
private ProfileAvatars profileAvatars;
|
||||
private RedisAdvancedClusterCommands<byte[], byte[]> commands;
|
||||
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands;
|
||||
private S3AsyncClient s3Client;
|
||||
@@ -85,10 +93,11 @@ public class ProfilesManagerTest {
|
||||
|
||||
profilesV1 = mock(Profiles.class);
|
||||
profilesV2 = mock(ProfilesV2.class);
|
||||
profileAvatars = mock(ProfileAvatars.class);
|
||||
s3Client = mock(S3AsyncClient.class);
|
||||
setLuaScript = mock(ClusterLuaScript.class);
|
||||
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, cacheCluster, mock(ScheduledExecutorService.class),
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, profileAvatars, cacheCluster, mock(ScheduledExecutorService.class),
|
||||
s3Client, BUCKET, setLuaScript);
|
||||
}
|
||||
|
||||
@@ -449,6 +458,104 @@ public class ProfilesManagerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAvatarForIdentity() {
|
||||
final byte[] identity = new byte[1];
|
||||
final String url1 = "url1";
|
||||
|
||||
when(profileAvatars.setAvatarUrl(any(byte[].class), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
profilesManager.setAvatarForIdentity(identity, url1);
|
||||
|
||||
verify(profileAvatars).setAvatarUrl(identity, url1);
|
||||
verifyNoInteractions(s3Client);
|
||||
|
||||
when(profileAvatars.setAvatarUrl(any(byte[].class), anyString()))
|
||||
.thenReturn(Optional.of(url1));
|
||||
|
||||
final String url2 = "url2";
|
||||
profilesManager.setAvatarForIdentity(identity, url2);
|
||||
|
||||
verify(profileAvatars).setAvatarUrl(identity, url2);
|
||||
verify(s3Client).deleteObject(argThat((DeleteObjectRequest r) -> url1.equals(r.key())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentity() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
assertEquals(Optional.of(avatarPath), profilesManager.extendAvatarTtlForIdentity(new byte[1]));
|
||||
|
||||
final ArgumentCaptor<CopyObjectRequest> copyObjectRequestArgumentCaptor = ArgumentCaptor.forClass(CopyObjectRequest.class);
|
||||
verify(s3Client).copyObject(copyObjectRequestArgumentCaptor.capture());
|
||||
|
||||
assertEquals(avatarPath, copyObjectRequestArgumentCaptor.getValue().sourceKey());
|
||||
assertEquals(avatarPath, copyObjectRequestArgumentCaptor.getValue().destinationKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentityNotFound() {
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.empty());
|
||||
|
||||
assertTrue(profilesManager.extendAvatarTtlForIdentity(new byte[1]).isEmpty());
|
||||
|
||||
verifyNoInteractions(s3Client);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentityS3NoSuchKey() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
when(s3Client.copyObject(any(CopyObjectRequest.class)))
|
||||
.thenReturn(CompletableFuture.failedFuture(NoSuchKeyException.builder().build()));
|
||||
|
||||
assertTrue(profilesManager.extendAvatarTtlForIdentity(new byte[1]).isEmpty());
|
||||
|
||||
verify(s3Client).copyObject(any(CopyObjectRequest.class));
|
||||
verify(profileAvatars).deleteAvatarUrl(any(byte[].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentityS3Retry() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
when(s3Client.copyObject(any(CopyObjectRequest.class)))
|
||||
.thenReturn(CompletableFuture.failedFuture(S3Exception.builder().build()))
|
||||
.thenReturn(CompletableFuture.completedFuture(mock(CopyObjectResponse.class)));
|
||||
|
||||
assertEquals(Optional.of(avatarPath), profilesManager.extendAvatarTtlForIdentity(new byte[1]));
|
||||
|
||||
verify(s3Client, times(2)).copyObject(any(CopyObjectRequest.class));
|
||||
|
||||
verify(profileAvatars, never()).deleteAvatarUrl(any(byte[].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatarForIdentity() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.deleteAvatarUrl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
profilesManager.deleteAvatarForIdentity(new byte[1]);
|
||||
|
||||
final ArgumentCaptor<DeleteObjectRequest> deleteObjectRequestArgumentCaptor = ArgumentCaptor.forClass(
|
||||
DeleteObjectRequest.class);
|
||||
verify(s3Client).deleteObject(deleteObjectRequestArgumentCaptor.capture());
|
||||
assertEquals(avatarPath, deleteObjectRequestArgumentCaptor.getValue().key());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatarForIdentityNotFound() {
|
||||
when(profileAvatars.deleteAvatarUrl(any(byte[].class))).thenReturn(Optional.empty());
|
||||
|
||||
profilesManager.deleteAvatarForIdentity(new byte[1]);
|
||||
|
||||
verifyNoInteractions(s3Client);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Redis {
|
||||
|
||||
@@ -457,7 +564,7 @@ public class ProfilesManagerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, profileAvatars, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
|
||||
s3Client, BUCKET);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user