diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java index 563e0f9b6..7e0032b11 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java @@ -16,11 +16,11 @@ import java.util.HexFormat; import java.util.Optional; import org.bouncycastle.crypto.digests.TupleHash; import org.signal.chat.common.S3UploadForm; +import org.signal.chat.profile.AccountInfo; import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult; +import org.signal.chat.profile.LegacyProfileResult; import org.signal.chat.profile.ProfileResult; import org.signal.chat.profile.ProfileResultOrBuilder; -import org.signal.chat.profile.LegacyProfileResult; -import org.signal.chat.profile.AccountInfo; import org.signal.libsignal.protocol.ServiceId; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.VerificationFailedException; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java index 6e23a58c2..55068948b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcService.java @@ -31,6 +31,8 @@ import org.signal.chat.profile.SetProfileRequest; import org.signal.chat.profile.SetProfileResponse; import org.signal.chat.profile.SetProfileResult; import org.signal.chat.profile.SetProfileV1Request.AvatarChange; +import org.signal.chat.profile.SetV1AvatarRequest; +import org.signal.chat.profile.SetV1AvatarResponse; import org.signal.chat.profile.SimpleProfileGrpc; import org.signal.libsignal.protocol.ServiceId; import org.signal.libsignal.zkgroup.GenericServerSecretParams; @@ -107,7 +109,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier()) - .orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found")); + .orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")); if (!account.hasCapability(DeviceCapability.PROFILES_V2)) { return SetProfileResponse.newBuilder() @@ -224,7 +226,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier()) - .orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found")); + .orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")); if (account.getZkCredentialKey().isEmpty()) { return GetAvatarCredentialsResponse.newBuilder() @@ -275,6 +277,35 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase { .orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()); } + @Override + public SetV1AvatarResponse setV1Avatar(final SetV1AvatarRequest request) { + + final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); + + final String version = request.getVersion(); + final Optional maybeV1Profile = profilesManager.getV1(authenticatedDevice.accountIdentifier(), + version); + + if (maybeV1Profile.isEmpty() && request.getCommitment().isEmpty()) { + throw GrpcExceptions.fieldViolation("commitment", "Commitment is required for new profile versions"); + } + + maybeV1Profile.map(VersionedProfileV1::avatar).filter(a -> a.startsWith("profiles/")) + .ifPresent(profilesManager::deleteAvatar); + + final byte[] commitment = maybeV1Profile.map(VersionedProfileV1::commitment).orElseGet(request.getCommitment()::toByteArray); + + final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName(); + + profilesManager.setV1Avatar(authenticatedDevice.accountIdentifier(), version, updateAvatarObjectName, commitment); + + return SetV1AvatarResponse.newBuilder() + .setForm(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName, + ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, + policyGenerator, clock)) + .build(); + } + private Optional validateRateLimitAndGetAccount(final UUID requesterUuid, final ServiceIdentifier targetIdentifier) throws RateLimitExceededException { rateLimiters.getProfileLimiter().validate(requesterUuid); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java index cd882eef4..33e573be3 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Profiles.java @@ -29,9 +29,11 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; +import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; import software.amazon.awssdk.services.dynamodb.model.Update; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; +import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; public class Profiles { @@ -282,4 +284,28 @@ public class Profiles { .doOnError(ignored -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error"))) .toFuture(); } + + /** + * Upserts the avatar for a v1 profile + */ + public VersionedProfileV1 setAvatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) { + final UpdateItemResponse response = SET_PROFILES_TIMER.record(() -> + dynamoDbClient.updateItem(UpdateItemRequest.builder() + .tableName(tableName) + .key(buildPrimaryKey(accountIdentifier, version)) + .updateExpression("SET #avatar = :avatar, #commitment = if_not_exists(#commitment, :commitment)") + .expressionAttributeNames(Map.of( + "#avatar", ATTR_AVATAR, + "#commitment", ATTR_COMMITMENT + )) + .expressionAttributeValues(Map.of( + ":avatar", AttributeValues.s(avatar), + ":commitment", AttributeValues.b(commitment) + )) + .returnValues(ReturnValue.ALL_NEW) + .build()) + ); + + return fromItem(response.attributes()); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java index 343abeb02..9bf7bdfca 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ProfilesManager.java @@ -338,4 +338,14 @@ public class ProfilesManager { } }); } + + public void setV1Avatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) { + ResilienceUtil.getGeneralRedisRetry(RETRY_NAME) + .executeRunnable(() -> cacheCluster.withBinaryCluster( + connection -> connection.sync().del(getCacheKeyV1(accountIdentifier)))); + + final VersionedProfileV1 versionedProfileV1 = profilesV1.setAvatar(accountIdentifier, version, avatar, commitment); + + redisSet(accountIdentifier, null, versionedProfileV1); + } } diff --git a/service/src/main/proto/org/signal/chat/profile.proto b/service/src/main/proto/org/signal/chat/profile.proto index b12ed1098..384c642bd 100644 --- a/service/src/main/proto/org/signal/chat/profile.proto +++ b/service/src/main/proto/org/signal/chat/profile.proto @@ -31,6 +31,17 @@ service Profile { // // Note: `Accounts.SetZkCredentialKey` is a pre-requisite for this RPC rpc GetAvatarCredentials(GetAvatarCredentialsRequest) returns (GetAvatarCredentialsResponse) {} + + // Returns credentials used by clients to upload a v1 avatar, deleting any current avatar. + // + // This RPC streamlines avatar changes during the v1 -> v2 transition by minimizing uploads: + // 1. SetV1Avatar + // 2. Upload to CDN + // 3. SetProfile with v1 `AVATAR_CHANGE_UNCHANGED` and the v1 avatar in the v2 profile body + // + // Clients that do this will be required to upload current avatars using `ProfilesAnonymous.GetAvatarUploadFormRequest` + // once v1 Profile APIs are no longer supported. + rpc SetV1Avatar(SetV1AvatarRequest) returns (SetV1AvatarResponse) {} } // Provides methods for working with profiles and profile-related data using "unidentified access" @@ -90,6 +101,19 @@ message SetProfileV1Request { bytes phone_number_sharing = 6 [(require.exactlySize) = 29]; } +message SetV1AvatarRequest { + // The profile version. Required. + string version = 1 [(require.exactlySize) = 64]; + + // The profile key commitment. Required if this is a new profile version. + bytes commitment = 2 [(require.exactlySize) = 0, (require.exactlySize) = 97]; +} + +message SetV1AvatarResponse { + // the policy and credential used by clients to upload an avatar to the CDN + common.S3UploadForm form = 1; +} + message SetProfileRequest { // The profile version. Required. @@ -374,6 +398,7 @@ message GetAvatarUploadFormRequest { message GetAvatarUploadFormResponse { oneof response { + // the policy and credential used by clients to upload an avatar to the CDN common.S3UploadForm avatar_upload_form = 1; errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"]; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java index 39a064f19..43c9ab455 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java @@ -8,6 +8,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.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; @@ -41,6 +42,7 @@ import java.util.Collection; import java.util.Collections; import java.util.HexFormat; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -57,6 +59,7 @@ 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.AccountInfo; import org.signal.chat.profile.GetAvatarCredentialsRequest; import org.signal.chat.profile.GetAvatarCredentialsResponse; import org.signal.chat.profile.GetProfileRequest; @@ -64,12 +67,13 @@ import org.signal.chat.profile.GetProfileResponse; import org.signal.chat.profile.LegacyProfileResult; import org.signal.chat.profile.ProfileGrpc; import org.signal.chat.profile.ProfileResult; -import org.signal.chat.profile.AccountInfo; import org.signal.chat.profile.SetProfileRequest; import org.signal.chat.profile.SetProfileResponse; import org.signal.chat.profile.SetProfileResult; import org.signal.chat.profile.SetProfileV1Request; import org.signal.chat.profile.SetProfileV1Request.AvatarChange; +import org.signal.chat.profile.SetV1AvatarRequest; +import org.signal.chat.profile.SetV1AvatarResponse; import org.signal.chat.profile.test.PlaintextProfileData; import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.ServiceId; @@ -195,8 +199,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().setProfile(request)); + assertEquals("invalid credentials", statusRuntimeException.getStatus().getDescription()); + } + @ParameterizedTest @MethodSource void setProfileUpload(final AvatarChange avatarChange, final boolean hasPreviousProfile, @@ -862,7 +881,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().getAvatarCredentials(GetAvatarCredentialsRequest.getDefaultInstance())); - assertEquals("account not found", statusRuntimeException.getStatus().getDescription()); + assertEquals("invalid credentials", statusRuntimeException.getStatus().getDescription()); } @Test @@ -902,6 +921,70 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().setV1Avatar( + SetV1AvatarRequest.newBuilder().setVersion(HexFormat.of().formatHex(TestRandomUtil.nextBytes(32))) + .build())); + + assertNotNull(statusRuntimeException.getStatus().getDescription()); + assertTrue(statusRuntimeException.getStatus().getDescription().toLowerCase(Locale.ROOT).contains("commitment")); + } + @ParameterizedTest @ValueSource(ints = {0, 1, 16, 32}) void testProfileSerialized(int aboutEmojiLength) { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java index 6e476ee8e..5a18cddd3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesManagerTest.java @@ -556,6 +556,33 @@ public class ProfilesManagerTest { verifyNoInteractions(s3Client); } + @Test + void setV1Avatar() { + final UUID uuid = UUID.randomUUID(); + final String version = HexFormat.of().formatHex(TestRandomUtil.nextBytes(32)); + final String avatar = "avatar"; + final byte[] commitment = TestRandomUtil.nextBytes(97); + + final VersionedProfileV1 profile = mock(VersionedProfileV1.class); + when(profile.version()).thenReturn(version); + when(profile.commitment()).thenReturn(commitment); + when(profile.avatar()).thenReturn(avatar); + + when(profilesV1.setAvatar(any(UUID.class), anyString(), anyString(), any(byte[].class))) + .thenReturn(profile); + + profilesManager.setV1Avatar(uuid, version, avatar, commitment); + + verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid))); + verify(profilesV1).setAvatar(uuid, version, avatar, commitment); + verify(setLuaScript).executeBinary( + argThat(keys -> + Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))), + argThat(args -> + Arrays.equals(args.get(0), version.getBytes()))); + verifyNoMoreInteractions(setLuaScript); + } + @Nested class Redis { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java index 1c0fe8b80..7006d8ed6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ProfilesTest.java @@ -6,7 +6,9 @@ package org.whispersystems.textsecuregcm.storage; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.util.List; import java.util.Map; @@ -384,4 +386,41 @@ public class ProfilesTest { Map.of(":commitment", AttributeValues.fromByteArray(commitment))) ); } + + @Test + void setAvatarInsert() { + final String avatar = "avatar"; + final String version = "version"; + final byte[] commitment = TestRandomUtil.nextBytes(97); + + final VersionedProfileV1 profile = profiles.setAvatar(UUID.randomUUID(), version, avatar, + commitment); + + assertEquals(version, profile.version()); + assertEquals(avatar, profile.avatar()); + assertArrayEquals(commitment, profile.commitment()); + assertNull(profile.name()); + } + + @Test + void setAvatarUpdate() { + final String version = "version"; + final byte[] commitment = TestRandomUtil.nextBytes(97); + final byte[] name = TestRandomUtil.nextBytes(81); + final UUID uuid = UUID.randomUUID(); + { + final VersionedProfileV1 initialProfile = new VersionedProfileV1(version, name, null, null, null, null, null, + commitment); + + profiles.set(uuid, initialProfile); + } + final String avatar = "avatar"; + + final VersionedProfileV1 profile = profiles.setAvatar(uuid, version, avatar, commitment); + + assertEquals(version, profile.version()); + assertEquals(avatar, profile.avatar()); + assertArrayEquals(commitment, profile.commitment()); + assertArrayEquals(name, profile.name()); + } }