Port AttachmentController to gRPC

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-03-17 13:18:18 -05:00
1 parent 82a3bba7ec
commit 81f2499889
10 files changed
+295 -32

No files matched your search

@@ -142,6 +142,7 @@ import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
import org.whispersystems.textsecuregcm.grpc.AttachmentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.BackupsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.BackupsGrpcService;
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
@@ -969,7 +970,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager))
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.attachments;
import java.security.SecureRandom;
import java.util.Base64;
public class AttachmentUtil {
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
private AttachmentUtil() {}
public static String generateAttachmentKey(final SecureRandom secureRandom) {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
return Base64.getUrlEncoder().encodeToString(bytes);
}
}
@@ -46,6 +46,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
@@ -177,9 +178,7 @@ public class BackupManager {
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
final String attachmentKey = AttachmentUtil.generateAttachmentKey(secureRandom);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}
@@ -15,7 +15,6 @@ import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Map;
import javax.annotation.Nonnull;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
@@ -26,6 +25,7 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
/**
@@ -36,8 +36,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
@Tag(name = "Attachments")
public class AttachmentControllerV4 {
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter rateLimiter;
@@ -77,16 +75,11 @@ public class AttachmentControllerV4 {
public AttachmentDescriptorV3 getAttachmentUploadForm(@Auth AuthenticatedDevice auth)
throws RateLimitExceededException {
rateLimiter.validate(auth.accountIdentifier());
final String key = generateAttachmentKey();
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), CDN3_EXPERIMENT_NAME);
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), AttachmentUtil.CDN3_EXPERIMENT_NAME);
int cdn = useCdn3 ? 3 : 2;
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key);
return new AttachmentDescriptorV3(cdn, key, descriptor.headers(), descriptor.signedUploadLocation());
}
private String generateAttachmentKey() {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
return Base64.getUrlEncoder().encodeToString(bytes);
}
}
@@ -0,0 +1,61 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import java.security.SecureRandom;
import java.util.Map;
import org.signal.chat.attachments.GetUploadFormRequest;
import org.signal.chat.attachments.GetUploadFormResponse;
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
import org.signal.chat.common.UploadForm;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter rateLimiter;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private final SecureRandom secureRandom;
public AttachmentsGrpcService(
final ExperimentEnrollmentManager experimentEnrollmentManager,
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator) {
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.rateLimiter = rateLimiters.getAttachmentLimiter();
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
3, tusAttachmentGenerator);
}
@Override
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request) throws RateLimitExceededException {
final AuthenticatedDevice auth = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiter.validate(auth.accountIdentifier());
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(),
AttachmentUtil.CDN3_EXPERIMENT_NAME);
final int cdn = useCdn3 ? 3 : 2;
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key);
return GetUploadFormResponse.newBuilder().setUploadForm(UploadForm.newBuilder()
.setCdn(cdn)
.setKey(key)
.putAllHeaders(descriptor.headers())
.setSignedUploadLocation(descriptor.signedUploadLocation()))
.build();
}
}
@@ -0,0 +1,25 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.attachments;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
service Attachments {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Retrieve an upload form that can be used to perform a resumable upload
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
}
message GetUploadFormRequest {}
message GetUploadFormResponse {
common.UploadForm upload_form = 1;
}
@@ -367,23 +367,8 @@ message GetUploadFormRequest {
}
}
message GetUploadFormResponse {
message UploadForm {
// Indicates the CDN type. 3 indicates resumable uploads using TUS
uint32 cdn = 1;
// The location within the specified cdn where the finished upload can be found
string key = 2;
// A map of headers to include with all upload requests. Potentially contains
// time-limited upload credentials
map<string, string> headers = 3;
// The URL to upload to with the appropriate protocol
string signed_upload_location = 4;
}
oneof outcome {
UploadForm upload_form = 1;
common.UploadForm upload_form = 1;
// The provided backup auth credential presentation could not be
// authenticated. Either, the presentation could not be verified, or
@@ -97,3 +97,19 @@ message ZkCredential {
bytes credential = 2 [(require.nonEmpty) = true];
}
// An upload location and credentials which may be used to upload an object
// to an external CDN
message UploadForm {
// Indicates the CDN type. 3 indicates resumable uploads using TUS
uint32 cdn = 1;
// The location within the specified cdn where the finished upload can be found
string key = 2;
// A map of headers to include with all upload requests. Potentially contains
// time-limited upload credentials
map<string, string> headers = 3;
// The URL to upload to with the appropriate protocol
string signed_upload_location = 4;
}
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -58,8 +59,8 @@ class AttachmentControllerV4Test {
private static final String CDN3_ENABLED_CREDS = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD);
private static final String CDN3_DISABLED_CREDS = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO);
private static final ExperimentEnrollmentManager EXPERIMENT_MANAGER = MockUtils.buildMock(ExperimentEnrollmentManager.class, mgr -> {
when(mgr.isEnrolled(AuthHelper.VALID_UUID, AttachmentControllerV4.CDN3_EXPERIMENT_NAME)).thenReturn(true);
when(mgr.isEnrolled(AuthHelper.VALID_UUID_TWO, AttachmentControllerV4.CDN3_EXPERIMENT_NAME)).thenReturn(false);
when(mgr.isEnrolled(AuthHelper.VALID_UUID, AttachmentUtil.CDN3_EXPERIMENT_NAME)).thenReturn(true);
when(mgr.isEnrolled(AuthHelper.VALID_UUID_TWO, AttachmentUtil.CDN3_EXPERIMENT_NAME)).thenReturn(false);
});
private static final byte[] TUS_SECRET = TestRandomUtil.nextBytes(32);
@@ -0,0 +1,161 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.signal.chat.attachments.AttachmentsGrpc;
import org.signal.chat.attachments.GetUploadFormRequest;
import org.signal.chat.attachments.GetUploadFormResponse;
import org.signal.chat.common.UploadForm;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class AttachmentsGrpcServiceTest extends
SimpleBaseGrpcTest<AttachmentsGrpcService, AttachmentsGrpc.AttachmentsBlockingStub> {
private static final byte[] TUS_SECRET = TestRandomUtil.nextBytes(32);
private static final String TUS_URL = "https://example.com/uploads";
@Mock
private ExperimentEnrollmentManager experimentEnrollmentManager;
@Mock
private RateLimiter rateLimiter;
@Override
protected AttachmentsGrpcService createServiceBeforeEachTest() {
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final String gcsPrivateKeyPem = "-----BEGIN PRIVATE KEY-----\n" +
Base64.getMimeEncoder().encodeToString(keyPair.getPrivate().getEncoded()) + "\n" +
"-----END PRIVATE KEY-----";
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
"some-cdn.signal.org", "signal@example.com", 1000, "/attach-here", gcsPrivateKeyPem);
final TusAttachmentGenerator tusAttachmentGenerator =
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL));
return new AttachmentsGrpcService(
experimentEnrollmentManager,
MockUtils.buildMock(RateLimiters.class, rateLimiters ->
when(rateLimiters.getAttachmentLimiter()).thenReturn(rateLimiter)),
gcsAttachmentGenerator,
tusAttachmentGenerator);
} catch (NoSuchAlgorithmException | IOException | InvalidKeyException | InvalidKeySpecException e) {
throw new AssertionError(e);
}
}
@Test
void getUploadFormCdn3() {
when(experimentEnrollmentManager.isEnrolled(AUTHENTICATED_ACI, AttachmentUtil.CDN3_EXPERIMENT_NAME))
.thenReturn(true);
final GetUploadFormResponse response = authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().build());
final UploadForm uploadForm = response.getUploadForm();
assertThat(uploadForm.getCdn()).isEqualTo(3);
assertThat(uploadForm.getKey()).isNotBlank();
assertThat(uploadForm.getSignedUploadLocation()).isEqualTo(TUS_URL + "/attachments");
final String filenameb64 = uploadForm.getHeadersMap().get("Upload-Metadata").split(" ")[1];
final String filename = new String(Base64.getDecoder().decode(filenameb64));
assertThat(uploadForm.getKey()).isEqualTo(filename);
}
@Test
void getUploadFormCdn2() throws MalformedURLException {
when(experimentEnrollmentManager.isEnrolled(AUTHENTICATED_ACI, AttachmentUtil.CDN3_EXPERIMENT_NAME))
.thenReturn(false);
final GetUploadFormResponse response = authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().build());
final UploadForm uploadForm = response.getUploadForm();
assertThat(uploadForm.getCdn()).isEqualTo(2);
assertThat(uploadForm.getKey()).isNotBlank();
assertThat(uploadForm.getHeadersMap()).containsExactlyInAnyOrderEntriesOf(Map.of(
"host", "some-cdn.signal.org",
"x-goog-resumable", "start",
"x-goog-content-length-range", "1,1000"));
assertThat(uploadForm.getSignedUploadLocation()).isNotEmpty();
final URL signedUploadLocation = URI.create(uploadForm.getSignedUploadLocation()).toURL();
assertThat(signedUploadLocation.getHost()).isEqualTo("some-cdn.signal.org");
assertThat(signedUploadLocation.getPath()).startsWith("/attach-here/");
final Map<String, String> queryParamMap = Arrays.stream(signedUploadLocation.getQuery().split("&"))
.map(queryTerm -> queryTerm.split("=", 2))
.collect(Collectors.toMap(
arr -> URLDecoder.decode(arr[0], StandardCharsets.UTF_8),
arr -> URLDecoder.decode(arr[1], StandardCharsets.UTF_8)));
assertThat(queryParamMap).hasSize(6);
assertThat(queryParamMap).containsAllEntriesOf(Map.of(
"X-Goog-Algorithm", "GOOG4-RSA-SHA256",
"X-Goog-Expires", "90000",
"X-Goog-SignedHeaders", "host;x-goog-content-length-range;x-goog-resumable"));
assertThat(queryParamMap)
.extractingByKey("X-Goog-Date", Assertions.as(InstanceOfAssertFactories.STRING))
.isNotEmpty();
assertThat(queryParamMap)
.extractingByKey("X-Goog-Signature", Assertions.as(InstanceOfAssertFactories.STRING))
.isNotEmpty();
final String credential = queryParamMap.get("X-Goog-Credential");
final String[] credentialParts = credential.split("/");
assertThat(credentialParts).hasSize(5);
assertThat(credentialParts[0]).isEqualTo("signal@example.com");
assertThat(credentialParts[2]).isEqualTo("auto");
assertThat(credentialParts[3]).isEqualTo("storage");
assertThat(credentialParts[4]).isEqualTo("goog4_request");
}
@Test
void getUploadFormRateLimited() throws RateLimitExceededException {
final Duration retryAfter = Duration.ofMinutes(5);
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimiter).validate(any(UUID.class));
assertRateLimitExceeded(retryAfter, () ->
authenticatedServiceStub().getUploadForm(GetUploadFormRequest.newBuilder().build()));
}
}