Compare commits

...
Author SHA1 Message Date
Ravi Khadiwala fa145d7889 Use 'response' rather than 'outcome' in backups.proto responses 2026-03-31 11:11:25 -05:00
Ravi Khadiwala edcc61d4ba Add reason annotations to backups.proto 2026-03-31 11:11:25 -05:00
Ravi Khadiwala 34c7106e7e Add reason annotations to account.proto 2026-03-31 11:11:25 -05:00
Ravi Khadiwala ee409af54a Add reason annotations to messages.proto 2026-03-31 11:11:25 -05:00
Ravi Khadiwala 04c4d993a6 Make reason tags upper-case 2026-03-31 11:11:25 -05:00
Ravi Khadiwala 0ee06d83b7 Add byte-based rate-limit to attachments 2026-03-31 11:10:15 -05:00
ravi-signal f9d3cd8d82 Add and enforce uploadLength in backup endpoints 2026-03-31 11:08:08 -05:00
Jon Chambers 771c98fd92 Susbcribe on a separate scheduler for non-SPQR account removal 2026-03-31 11:07:10 -05:00
ravi-signal 82d9107865 Add an attachment uploadLength parameter and enforce it 2026-03-31 11:05:18 -05:00
adel-signal f2b0264fac calling: add dynamic turn configuration for testing new cloudflare TURN endpoints 2026-03-30 11:13:33 -05:00
Jon Chambers 132611f159 Add a command for removing accounts that do not support SPQR 2026-03-30 11:34:02 -04:00
Jon Chambers a741edd80f Add a command for removing linked devices that do not support SPQR 2026-03-30 11:34:02 -04:00
Jon Chambers 8c3dd7aa48 Update to the latest version of the spam filter 2026-03-30 11:30:05 -04:00
Chris Eager b0792dd0a7 Update to the latest version of the spam filter 2026-03-24 15:17:52 -05:00
Jon Chambers d9d6560b47 Add request/response byte counters to the gRPC metrics interceptor 2026-03-24 15:03:10 -04:00
Jon Chambers 8cc0948a34 Use an EnumSet for CAPABILITIES_REQUIRED_FOR_NEW_DEVICES 2026-03-24 15:01:43 -04:00
Jon Chambers 575280da74 Don't allow linked devices that are missing capabilities required at registration time 2026-03-24 15:01:43 -04:00
Jon Chambers 46bfc12869 Check for SPQR capability in third-party clients in remote deprecation filter 2026-03-24 14:29:20 -04:00
Jon Chambers 73ec57e911 Avoid constructing a Metadata.Key for authentication on every server call 2026-03-24 14:29:20 -04:00
ravi-signal fb84066f09 Match KeyController's rate limit key in KeysGrpcService 2026-03-24 13:26:25 -05:00
Ravi Khadiwala 4d24c814cc Check if resolvedRecipients is empty before inserting an MRM 2026-03-24 13:15:57 -05:00
Jon Chambers 9dc807a255 Remove the "unrecognized UA" remote deprecation reason 2026-03-24 14:10:51 -04:00
Jon Chambers 5d59538924 Modernize RemoteDeprecationFilterTest 2026-03-24 14:10:51 -04:00
Jon Chambers 04c102e51f Convert DynamicRemoteDeprecationConfiguration to a record 2026-03-24 14:10:51 -04:00
Jon Chambers 71bc23ed02 Standardize formatting in DynamicRemoteDeprecationConfiguration 2026-03-24 14:10:51 -04:00
64 changed files with 1629 additions and 503 deletions

No files matched your search

@@ -14,7 +14,6 @@ import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.signal.libsignal.protocol.IdentityKey;
@@ -130,7 +129,7 @@ public class TestUser {
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
}
+5
View File
@@ -370,6 +370,11 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
+3 -2
View File
@@ -231,17 +231,18 @@ messageCache: # Redis server configuration for message store cache
cluster:
configurationUri: redis://redis.example.com:6379/
attachments:
maxUploadSizeInBytes: 1024
gcpAttachments: # GCP Storage configuration
domain: example.com
email: user@example.cocm
maxSizeInBytes: 1024
pathPrefix:
rsaSigningKey: secret://gcpAttachments.rsaSigningKey
tus:
uploadUri: https://example.org/upload
userAuthenticationTokenSharedSecret: secret://tus.userAuthenticationTokenSharedSecret
maxSizeInBytes: 1024
apn: # Apple Push Notifications configuration
sandbox: true
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.AttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
@@ -122,6 +123,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private DynamoDbTables dynamoDbTables;
@NotNull
@Valid
@JsonProperty
private AttachmentsConfiguration attachments;
@NotNull
@Valid
@JsonProperty
@@ -412,6 +418,10 @@ public class WhisperServerConfiguration extends Configuration {
return webSocket;
}
public AttachmentsConfiguration getAttachments() {
return attachments;
}
public GcpAttachmentsConfiguration getGcpAttachmentsConfiguration() {
return gcpAttachments;
}
@@ -610,4 +620,5 @@ public class WhisperServerConfiguration extends Configuration {
public HlrLookupConfiguration getHlrLookupConfiguration() {
return hlrLookup;
}
}
@@ -294,6 +294,8 @@ import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredUsernameHoldsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveNonSpqrAccountsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveNonSpqrLinkedDevicesCommand;
import org.whispersystems.textsecuregcm.workers.RemoveOrphanedPreKeyPagesCommand;
import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSenderServiceCommand;
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
@@ -356,6 +358,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new UnlinkDevicesWithIdlePrimaryCommand(Clock.systemUTC()));
bootstrap.addCommand(new NotifyIdleDevicesCommand());
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
bootstrap.addCommand(new RemoveNonSpqrLinkedDevicesCommand());
bootstrap.addCommand(new RemoveNonSpqrAccountsCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
@@ -754,8 +758,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
cloudflareTurnHttpExecutor,
config.getTurnConfiguration().cloudflare().retryConfigurationName(),
cloudflareTurnRetryExecutor,
cloudflareDnsResolver
);
cloudflareDnsResolver,
dynamicConfigurationManager,
experimentEnrollmentManager);
final CardinalityEstimator messageByteLimitCardinalityEstimator = new CardinalityEstimator(
rateLimitersCluster,
@@ -822,7 +827,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
config.getGcpAttachmentsConfiguration().domain(),
config.getGcpAttachmentsConfiguration().email(),
config.getGcpAttachmentsConfiguration().maxSizeInBytes(),
config.getGcpAttachmentsConfiguration().pathPrefix(),
config.getGcpAttachmentsConfiguration().rsaSigningKey().value());
@@ -947,7 +951,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.info("Registered spam filter: {}", filter.getClass().getName());
});
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
final RemoteDeprecationFilter remoteDeprecationFilter =
new RemoteDeprecationFilter(accountsManager, accountAuthenticator, dynamicConfigurationManager);
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
@@ -971,7 +977,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator))
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxUploadSizeInBytes()))
.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!
@@ -990,7 +997,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new PaymentsGrpcService(currencyManager),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
@@ -1093,8 +1100,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
registrationLockVerificationManager, rateLimiters),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics),
experimentEnrollmentManager, config.getAttachments().maxUploadSizeInBytes()),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxUploadSizeInBytes()),
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CallQualitySurveyController(callQualitySurveyManager),
@@ -10,8 +10,6 @@ public interface AttachmentGenerator {
record Descriptor(Map<String, String> headers, String signedUploadLocation) {}
Descriptor generateAttachment(final String key);
long maxUploadSizeInBytes();
Descriptor generateAttachment(final String key, final long uploadLength);
}
@@ -22,28 +22,21 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
@Nonnull
private final CanonicalRequestSigner canonicalRequestSigner;
private final int maxSizeInBytes;
public GcsAttachmentGenerator(@Nonnull String domain, @Nonnull String email,
int maxSizeInBytes, @Nonnull String pathPrefix, @Nonnull String rsaSigningKey)
@Nonnull String pathPrefix, @Nonnull String rsaSigningKey)
throws IOException, InvalidKeyException, InvalidKeySpecException {
this.maxSizeInBytes = maxSizeInBytes;
this.canonicalRequestGenerator = new CanonicalRequestGenerator(domain, email, maxSizeInBytes, pathPrefix);
this.canonicalRequestGenerator = new CanonicalRequestGenerator(domain, email, pathPrefix);
this.canonicalRequestSigner = new CanonicalRequestSigner(rsaSigningKey);
}
@Override
public Descriptor generateAttachment(final String key) {
public Descriptor generateAttachment(final String key, final long uploadLength) {
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final CanonicalRequest canonicalRequest = canonicalRequestGenerator.createFor(key, now);
final CanonicalRequest canonicalRequest = canonicalRequestGenerator.createFor(key, now, uploadLength);
return new Descriptor(getHeaderMap(canonicalRequest), getSignedUploadLocation(canonicalRequest));
}
@Override
public long maxUploadSizeInBytes() {
return this.maxSizeInBytes;
}
private String getSignedUploadLocation(@Nonnull CanonicalRequest canonicalRequest) {
return "https://" + canonicalRequest.getDomain() + canonicalRequest.getResourcePath()
+ '?' + canonicalRequest.getCanonicalQuery()
@@ -19,18 +19,16 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
private final JwtGenerator jwtGenerator;
private final String tusUri;
private final long maxUploadSize;
public TusAttachmentGenerator(final TusConfiguration cfg) {
this.tusUri = cfg.uploadUri();
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
this.maxUploadSize = cfg.maxSizeInBytes();
}
@Override
public Descriptor generateAttachment(final String key) {
public Descriptor generateAttachment(final String key, final long uploadLength) {
final String token = jwtGenerator.generateJwt(ATTACHMENTS, key,
builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, maxUploadSize));
builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadLength));
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
final Map<String, String> headers = Map.of(
@@ -39,9 +37,4 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
);
return new Descriptor(headers, tusUri + "/" + ATTACHMENTS);
}
@Override
public long maxUploadSizeInBytes() {
return maxUploadSize;
}
}
@@ -12,6 +12,4 @@ import org.whispersystems.textsecuregcm.util.ExactlySize;
public record TusConfiguration(
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
@NotEmpty String uploadUri,
@Positive long maxSizeInBytes
){}
@NotEmpty String uploadUri){}
@@ -16,13 +16,17 @@ import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -37,6 +41,8 @@ public class CloudflareTurnCredentialsManager {
private final FaultTolerantHttpClient cloudflareTurnClient;
private final DnsNameResolver dnsNameResolver;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final Duration clientCredentialTtl;
@@ -63,7 +69,9 @@ public class CloudflareTurnCredentialsManager {
final ExecutorService executor,
@Nullable final String retryConfigurationName,
final ScheduledExecutorService retryExecutor,
final DnsNameResolver dnsNameResolver) {
final DnsNameResolver dnsNameResolver,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder("cloudflare-turn", executor)
.withCircuitBreaker(circuitBreakerConfigurationName)
@@ -74,6 +82,8 @@ public class CloudflareTurnCredentialsManager {
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
this.cloudflareTurnHostname = cloudflareTurnHostname;
this.dnsNameResolver = dnsNameResolver;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.experimentEnrollmentManager = experimentEnrollmentManager;
final String credentialsRequestBody;
@@ -95,15 +105,27 @@ public class CloudflareTurnCredentialsManager {
this.clientCredentialTtl = clientCredentialTtl;
}
public TurnToken retrieveFromCloudflare() throws IOException {
public TurnToken retrieveFromCloudflare(UUID accountUuid) throws IOException {
final List<String> cloudflareTurnComposedUrls;
final List<String> turnUrls;
final List<String> turnUrlsWithIps;
final String turnHostname;
if (experimentEnrollmentManager.isEnrolled(accountUuid, "turnBeta")) {
turnUrls = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getUrls();
turnUrlsWithIps = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getUrlsWithIps();
turnHostname = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getHostname();
} else {
turnUrls = this.cloudflareTurnUrls;
turnUrlsWithIps = this.cloudflareTurnUrlsWithIps;
turnHostname = this.cloudflareTurnHostname;
}
try {
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(cloudflareTurnHostname).get().stream()
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(turnHostname).get().stream()
.map(i -> switch (i) {
case Inet6Address i6 -> "[" + i6.getHostAddress() + "]";
default -> i.getHostAddress();
})
.flatMap(i -> cloudflareTurnUrlsWithIps.stream().map(u -> u.formatted(i)))
.flatMap(i -> turnUrlsWithIps.stream().map(u -> u.formatted(i)))
.toList();
} catch (Exception e) {
throw new IOException(e);
@@ -129,9 +151,9 @@ public class CloudflareTurnCredentialsManager {
cloudflareTurnResponse.iceServers().username(),
cloudflareTurnResponse.iceServers().credential(),
clientCredentialTtl.toSeconds(),
cloudflareTurnUrls == null ? Collections.emptyList() : cloudflareTurnUrls,
turnUrls,
cloudflareTurnComposedUrls,
cloudflareTurnHostname
turnHostname
);
}
}
@@ -8,7 +8,6 @@ import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
@@ -22,7 +21,7 @@ public class ProhibitAuthenticationInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
final String authHeaderString = headers.get(Metadata.Key.of(RequireAuthenticationInterceptor.AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
final String authHeaderString = headers.get(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY);
if (authHeaderString != null) {
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.badAuthentication("The service forbids requests with an authentication header"));
@@ -11,7 +11,6 @@ import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.util.Optional;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
@@ -26,7 +25,8 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
*/
public class RequireAuthenticationInterceptor implements ServerInterceptor {
static final String AUTHORIZATION_HEADER = "authorization";
public static final Metadata.Key<String> AUTHORIZATION_METADATA_KEY =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
private final AccountAuthenticator authenticator;
@@ -37,8 +37,7 @@ public class RequireAuthenticationInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
final String authHeaderString = headers.get(
Metadata.Key.of(AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
final String authHeaderString = headers.get(AUTHORIZATION_METADATA_KEY);
if (authHeaderString == null) {
return ServerInterceptorUtil.closeWithStatusException(call,
@@ -155,28 +155,33 @@ public class BackupManager {
* If successful, this also updates the TTL of the backup.
*
* @param backupUser an already ZK authenticated backup user
* @param uploadSize the maximum size of a message backup that can be uploaded with the returned form
* @return the upload form
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
*/
public BackupUploadDescriptor createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupWrongCredentialTypeException {
final AuthenticatedBackupUser backupUser,
final long uploadSize) throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
backupsDb.addMessageBackup(backupUser).join();
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser));
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser), uploadSize);
}
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(final AuthenticatedBackupUser backupUser)
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(
final AuthenticatedBackupUser backupUser,
final long uploadSize)
throws RateLimitExceededException, BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
final String attachmentKey = AttachmentUtil.generateAttachmentKey(secureRandom);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
final AttachmentGenerator.Descriptor descriptor =
tusAttachmentGenerator.generateAttachment(attachmentKey, uploadSize);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}
@@ -194,9 +199,9 @@ public class BackupManager {
final long maxTotalMediaSize =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
// Report that the backup is out of quota if it cannot store a max size media object
// Report that the backup is out of quota if it is within 100MiB of the limit
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
(maxTotalMediaSize - tusAttachmentGenerator.maxUploadSizeInBytes());
(maxTotalMediaSize - 1024 * 1024 * 100);
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
@@ -329,13 +334,14 @@ public class BackupManager {
*/
public CopyQuota getCopyQuota(
final AuthenticatedBackupUser backupUser,
final List<CopyParameters> toCopy)
final List<CopyParameters> toCopy,
final long maximumSourceObjectSize)
throws BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
for (CopyParameters copyParameters : toCopy) {
if (copyParameters.sourceLength() > tusAttachmentGenerator.maxUploadSizeInBytes() || copyParameters.sourceLength() < 0) {
if (copyParameters.sourceLength() > maximumSourceObjectSize || copyParameters.sourceLength() < 0) {
throw new BackupInvalidArgumentException("Invalid sourceObject size");
}
}
@@ -729,10 +735,6 @@ public class BackupManager {
.toFuture();
}
public long maxMessageBackupUploadSize() {
return tusAttachmentGenerator.maxUploadSizeInBytes();
}
interface PresentationSignatureVerifier {
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey) throws BackupFailedZkAuthenticationException;
@@ -21,21 +21,19 @@ public class Cdn3BackupCredentialGenerator {
private final String tusUri;
private final JwtGenerator jwtGenerator;
private final long maxUploadSize;
public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) {
this.tusUri = cfg.uploadUri();
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
this.maxUploadSize = cfg.maxSizeInBytes();
}
public BackupUploadDescriptor generateUpload(final String key) {
public BackupUploadDescriptor generateUpload(final String key, final long uploadSize) {
if (key.isBlank()) {
throw new IllegalArgumentException("Upload descriptors must have non-empty keys");
}
final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, maxUploadSize)
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize)
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write"));
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
@@ -0,0 +1,10 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.Positive;
public record AttachmentsConfiguration(@Positive long maxUploadSizeInBytes) {
}
@@ -14,7 +14,6 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public record GcpAttachmentsConfiguration(@NotBlank String domain,
@NotBlank String email,
@Min(1) int maxSizeInBytes,
String pathPrefix,
@NotNull SecretString rsaSigningKey) {
@SuppressWarnings("unused")
@@ -12,6 +12,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.signal.chat.calling.GetTurnCredentialsResponseOrBuilder;
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
public class DynamicConfiguration {
@@ -30,7 +31,7 @@ public class DynamicConfiguration {
@JsonProperty
@Valid
private DynamicRemoteDeprecationConfiguration remoteDeprecation = new DynamicRemoteDeprecationConfiguration();
private DynamicRemoteDeprecationConfiguration remoteDeprecation = DynamicRemoteDeprecationConfiguration.DEFAULT;
@JsonProperty
@Valid
@@ -76,6 +77,10 @@ public class DynamicConfiguration {
@Valid
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@JsonProperty
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -137,4 +142,8 @@ public class DynamicConfiguration {
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
}
@@ -5,74 +5,52 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.vdurmont.semver4j.Semver;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import jakarta.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public class DynamicRemoteDeprecationConfiguration {
public record DynamicRemoteDeprecationConfiguration(
@NotNull Map<ClientPlatform, Semver> minimumVersions,
@NotNull Map<ClientPlatform, Semver> versionsPendingDeprecation,
@NotNull Map<ClientPlatform, Set<Semver>> blockedVersions,
@NotNull Map<ClientPlatform, Set<Semver>> versionsPendingBlock,
@NotNull Boolean spqrEnforcementPending,
@NotNull Boolean requireSpqr) {
@JsonProperty
private Map<ClientPlatform, Semver> minimumVersions = Collections.emptyMap();
public static DynamicRemoteDeprecationConfiguration DEFAULT = new DynamicRemoteDeprecationConfiguration(
Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyMap(),
false,
false);
@JsonProperty
private Map<ClientPlatform, Semver> versionsPendingDeprecation = Collections.emptyMap();
@JsonProperty
private Map<ClientPlatform, Set<Semver>> blockedVersions = Collections.emptyMap();
@JsonProperty
private Map<ClientPlatform, Set<Semver>> versionsPendingBlock = Collections.emptyMap();
@JsonProperty
private boolean unrecognizedUserAgentAllowed = true;
@VisibleForTesting
public void setMinimumVersions(final Map<ClientPlatform, Semver> minimumVersions) {
this.minimumVersions = minimumVersions;
public DynamicRemoteDeprecationConfiguration {
if (minimumVersions == null) {
minimumVersions = DEFAULT.minimumVersions();
}
public Map<ClientPlatform, Semver> getMinimumVersions() {
return minimumVersions;
if (versionsPendingDeprecation == null) {
versionsPendingDeprecation = DEFAULT.versionsPendingDeprecation();
}
@VisibleForTesting
public void setVersionsPendingDeprecation(final Map<ClientPlatform, Semver> versionsPendingDeprecation) {
this.versionsPendingDeprecation = versionsPendingDeprecation;
if (blockedVersions == null) {
blockedVersions = DEFAULT.blockedVersions();
}
public Map<ClientPlatform, Semver> getVersionsPendingDeprecation() {
return versionsPendingDeprecation;
if (versionsPendingBlock == null) {
versionsPendingBlock = DEFAULT.versionsPendingBlock();
}
@VisibleForTesting
public void setUnrecognizedUserAgentAllowed(final boolean allowUnrecognizedUserAgents) {
this.unrecognizedUserAgentAllowed = allowUnrecognizedUserAgents;
if (spqrEnforcementPending == null) {
spqrEnforcementPending = DEFAULT.spqrEnforcementPending();
}
public boolean isUnrecognizedUserAgentAllowed() {
return unrecognizedUserAgentAllowed;
}
@VisibleForTesting
public void setBlockedVersions(final Map<ClientPlatform, Set<Semver>> blockedVersions) {
this.blockedVersions = blockedVersions;
}
public Map<ClientPlatform, Set<Semver>> getBlockedVersions() {
return blockedVersions;
}
@VisibleForTesting
public void setVersionsPendingBlock(final Map<ClientPlatform, Set<Semver>> versionsPendingBlock) {
this.versionsPendingBlock = versionsPendingBlock;
}
public Map<ClientPlatform, Set<Semver>> getVersionsPendingBlock() {
return versionsPendingBlock;
if (requireSpqr == null) {
requireSpqr = DEFAULT.requireSpqr();
}
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
public class DynamicTurnConfiguration {
@JsonProperty
@NotNull
@Valid
private List<@NotBlank String> urls = Collections.emptyList();
@JsonProperty
@NotNull
@Valid
private List<@NotBlank String> urlsWithIps = Collections.emptyList();
@JsonProperty
@Nullable
private String hostname = null;
public DynamicTurnConfiguration() {}
public List<String> getUrls() {
return urls;
}
public List<String> getUrlsWithIps() {
return urlsWithIps;
}
public @Nullable String getHostname() {
return hostname;
}
}
@@ -102,17 +102,20 @@ public class ArchiveController {
private final BackupAuthManager backupAuthManager;
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
private final long maxAttachmentSize;
public ArchiveController(
final AccountsManager accountsManager,
final BackupAuthManager backupAuthManager,
final BackupManager backupManager,
final BackupMetrics backupMetrics) {
final BackupMetrics backupMetrics,
final long maxAttachmentSize) {
this.accountsManager = accountsManager;
this.backupAuthManager = backupAuthManager;
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
this.maxAttachmentSize = maxAttachmentSize;
}
public record SetBackupIdRequest(
@@ -566,8 +569,11 @@ public class ArchiveController {
@Path("/upload/form")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Fetch message backup upload form",
description = "Retrieve an upload form that can be used to perform a resumable upload of a message backup.")
summary = "Fetch message backup upload form", description = """
Retrieve an upload form that can be used to perform a resumable upload of a message backup.
Uploads with the returned form will be limited to a maximum size of the provided uploadLength.
""")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change.")
@@ -596,7 +602,7 @@ public class ArchiveController {
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final boolean oversize = uploadLength
.map(length -> length > backupManager.maxMessageBackupUploadSize())
.map(length -> length > maxAttachmentSize)
.orElse(false);
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
@@ -604,7 +610,7 @@ public class ArchiveController {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
final BackupUploadDescriptor uploadDescriptor =
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength.orElse(maxAttachmentSize));
return new UploadDescriptorResponse(
uploadDescriptor.cdn(),
uploadDescriptor.key(),
@@ -621,32 +627,42 @@ public class ArchiveController {
Retrieve an upload form that can be used to perform a resumable upload of an attachment. After uploading, the
attachment can be copied into the backup at PUT /archives/media/.
Like the account authenticated version at /attachments, the uploaded object is only temporary.
Like the account authenticated version at /attachments, the uploaded object is only temporary. Uploads with
the returned form will be limited to a maximum size of the provided uploadLength.
""")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change and is governed by `global.attachments.maxBytes`.")
@ApiResponseZkAuth
@ManagedAsync
public UploadDescriptorResponse uploadTemporaryAttachment(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH) final ArchiveController.BackupAuthCredentialPresentationHeader presentation,
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@Parameter(description = "The size of the temporary attachment to upload in bytes")
@QueryParam("uploadLength") final Optional<Long> uploadLength)
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final boolean oversize = uploadLength.map(length -> length > maxAttachmentSize).orElse(false);
if (oversize) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
final BackupUploadDescriptor uploadDescriptor =
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser);
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, uploadLength.orElse(maxAttachmentSize));
return new UploadDescriptorResponse(
uploadDescriptor.cdn(),
uploadDescriptor.key(),
@@ -741,7 +757,7 @@ public class ArchiveController {
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.CopyQuota copyQuota =
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()));
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()), maxAttachmentSize);
final CopyResult copyResult = backupManager.copyToBackup(copyQuota).next()
.blockOptional()
.orElseThrow(() -> new IllegalStateException("Non empty copy request must return result"));
@@ -844,7 +860,7 @@ public class ArchiveController {
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList());
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList(), maxAttachmentSize);
final List<CopyMediaBatchResponse.Entry> copyResults = backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
@@ -7,17 +7,25 @@ package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -25,7 +33,6 @@ 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;
/**
@@ -37,7 +44,9 @@ import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
public class AttachmentControllerV4 {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter rateLimiter;
private final RateLimiter countRateLimiter;
private final RateLimiter bytesRateLimiter;
private final long maxUploadLength;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
@@ -48,9 +57,12 @@ public class AttachmentControllerV4 {
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.rateLimiter = rateLimiters.getAttachmentLimiter();
final ExperimentEnrollmentManager experimentEnrollmentManager,
final long maxUploadLength) {
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.maxUploadLength = maxUploadLength;
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
@@ -66,19 +78,43 @@ public class AttachmentControllerV4 {
description = """
Retrieve an upload form that can be used to perform a resumable upload. The response will include a cdn number
indicating what protocol should be used to perform the upload.
Uploads with the returned form will be limited to a maximum size of the provided uploadLength.
"""
)
@ApiResponse(responseCode = "200", description = "Success, response body includes upload form", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "The provided uploadLength was not valid")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change and is governed by `global.attachments.maxBytes`.")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public AttachmentDescriptorV3 getAttachmentUploadForm(@Auth AuthenticatedDevice auth)
public AttachmentDescriptorV3 getAttachmentUploadForm(
@Auth AuthenticatedDevice auth,
@Parameter(description = "The size of the attachment to upload in bytes")
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength)
throws RateLimitExceededException {
rateLimiter.validate(auth.accountIdentifier());
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
if (uploadLength > maxUploadLength) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
countRateLimiter.validate(auth.accountIdentifier());
if (maybeUploadLength.isPresent()) {
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
// However, just undoing the first modification if the second one fails is close enough for our purposes
try {
bytesRateLimiter.validate(auth.accountIdentifier(), maybeUploadLength.get());
} catch (RateLimitExceededException e) {
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
throw e;
}
}
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);
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key, uploadLength);
return new AttachmentDescriptorV3(cdn, key, descriptor.headers(), descriptor.signedUploadLocation());
}
@@ -60,7 +60,7 @@ public class CallRoutingControllerV2 {
rateLimiters.getCallEndpointLimiter().validate(auth.accountIdentifier());
try {
return new GetCallingRelaysResponse(List.of(cloudflareTurnCredentialsManager.retrieveFromCloudflare()));
return new GetCallingRelaysResponse(List.of(cloudflareTurnCredentialsManager.retrieveFromCloudflare(auth.accountIdentifier())));
} catch (final Exception e) {
CLOUDFLARE_TURN_ERROR_COUNTER.increment();
throw e;
@@ -408,6 +408,10 @@ public class DeviceController {
}
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
if (!capabilities.containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)) {
return true;
}
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
@@ -398,34 +398,38 @@ public class KeysController {
}
private List<Device> parseDeviceId(String deviceId, Account account) {
return parseDeviceId(deviceId)
.map(id -> account.getDevice(id).map(List::of).orElse(List.of()))
.orElseGet(account::getDevices);
}
private Optional<Byte> parseDeviceId(final String deviceId) {
if (deviceId.equals("*")) {
return account.getDevices();
return Optional.empty();
}
try {
byte id = Byte.parseByte(deviceId);
return account.getDevice(id).map(List::of).orElse(List.of());
return Optional.of(Byte.parseByte(deviceId));
} catch (NumberFormatException e) {
throw new WebApplicationException(Response.status(422).build());
}
}
private String getPreKeysLimiterKey(
final Account account,
final AuthenticatedDevice authenticatedDevice,
final ServiceIdentifier targetIdentifier,
final Account targetAccount,
final String targetDeviceId) {
final String targetRegistrationId = targetDeviceId.equals("*")
? "*"
: String.valueOf(
parseDeviceId(targetDeviceId, targetAccount).getFirst().getRegistrationId(targetIdentifier.identityType()));
return String.format("%s.%s__%s.%s.%s",
final Optional<Byte> parsedTargetDeviceId = parseDeviceId(targetDeviceId);
final Optional<Integer> targetRegistrationId = parsedTargetDeviceId
.flatMap(targetAccount::getDevice)
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
return RateLimitKeys.preKeyLimiterKey(
account.getUuid(),
authenticatedDevice.deviceId(),
targetIdentifier.uuid(),
targetDeviceId,
targetRegistrationId
);
targetIdentifier,
parsedTargetDeviceId, targetRegistrationId);
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.util.Optional;
import java.util.UUID;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
/// Helper methods to centrally define rate-limit key formats used in multiple places
public class RateLimitKeys {
/// Key for rate-limiting a device's pre-keys
///
/// @param sourceAci the account identifier of the authenticated device fetching the pre-keys
/// @param sourceDeviceId the deviceId of the authenticated device fetching pre-keys
/// @param targetIdentifier the [ServiceIdentifier] of the target account
/// @param targetDeviceId the deviceId of the target device, empty if fetching all device pre-keys
/// @param targetRegistrationId the registrationId of the target device, empty if fetching all device pre-keys
/// @return the rate-limit key
public static String preKeyLimiterKey(
final UUID sourceAci,
final byte sourceDeviceId,
final ServiceIdentifier targetIdentifier,
final Optional<Byte> targetDeviceId,
final Optional<Integer> targetRegistrationId) {
return String.format("%s.%s__%s.%s.%s",
sourceAci,
sourceDeviceId,
targetIdentifier.uuid(),
targetDeviceId.map(String::valueOf).orElse("*"),
targetRegistrationId.map(String::valueOf).orElse("*"));
}
}
@@ -118,7 +118,7 @@ public class RegistrationController {
if (!(registrationRequest.accountAttributes().getCapabilities() != null
? registrationRequest.accountAttributes().getCapabilities()
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)) {
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)) {
throw new WebApplicationException("Missing required device capability", 499);
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.filters;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import com.vdurmont.semver4j.Semver;
import io.grpc.Metadata;
@@ -23,14 +24,21 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
@@ -44,6 +52,8 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
*/
public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
private final AccountsManager accountsManager;
private final AccountAuthenticator accountAuthenticator;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private static final String DEPRECATED_CLIENT_COUNTER_NAME = name(RemoteDeprecationFilter.class, "deprecated");
@@ -52,9 +62,14 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
private static final String REASON_TAG_NAME = "reason";
private static final String EXPIRED_CLIENT_REASON = "expired";
private static final String BLOCKED_CLIENT_REASON = "blocked";
private static final String UNRECOGNIZED_UA_REASON = "unrecognized_user_agent";
private static final String SPQR_NOT_SUPPORTED_REASON = "spqr";
public RemoteDeprecationFilter(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
public RemoteDeprecationFilter(final AccountsManager accountsManager,
final AccountAuthenticator accountAuthenticator,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.accountsManager = accountsManager;
this.accountAuthenticator = accountAuthenticator;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@@ -69,7 +84,7 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
userAgent = null;
}
if (shouldBlock(userAgent)) {
if (shouldBlock(userAgent, ((HttpServletRequest) request).getHeader(HttpHeaders.AUTHORIZATION))) {
((HttpServletResponse) response).sendError(499);
} else {
chain.doFilter(request, response);
@@ -91,32 +106,41 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
}
}).orElse(null);
if (shouldBlock(userAgent)) {
if (shouldBlock(userAgent, headers.get(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY))) {
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.upgradeRequired());
} else {
return next.startCall(call, headers);
}
}
private boolean shouldBlock(@Nullable final UserAgent userAgent) {
@VisibleForTesting
boolean shouldBlock(@Nullable final UserAgent userAgent, @Nullable final String authHeader) {
final DynamicRemoteDeprecationConfiguration configuration = dynamicConfigurationManager
.getConfiguration().getRemoteDeprecationConfiguration();
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.getMinimumVersions();
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.minimumVersions();
final Map<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = configuration
.getVersionsPendingDeprecation();
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.getBlockedVersions();
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.getVersionsPendingBlock();
boolean shouldBlock = false;
.versionsPendingDeprecation();
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.blockedVersions();
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.versionsPendingBlock();
if (userAgent == null) {
if (configuration.isUnrecognizedUserAgentAllowed()) {
return false;
// In first-party clients, we can enforce SPQR presence via minimum client version. For third-party clients, we
// need to do a more expensive check for the actual capability.
if ((configuration.spqrEnforcementPending() || configuration.requireSpqr()) && isMissingSpqrCapability(authHeader)) {
if (configuration.requireSpqr()) {
recordDeprecation(null, SPQR_NOT_SUPPORTED_REASON);
return true;
}
recordPendingDeprecation(null, SPQR_NOT_SUPPORTED_REASON);
}
recordDeprecation(null, UNRECOGNIZED_UA_REASON);
return true;
return false;
}
boolean shouldBlock = false;
if (blockedVersionsByPlatform.containsKey(userAgent.platform())) {
if (blockedVersionsByPlatform.get(userAgent.platform()).contains(userAgent.version())) {
recordDeprecation(userAgent, BLOCKED_CLIENT_REASON);
@@ -146,15 +170,37 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
return shouldBlock;
}
private void recordDeprecation(final UserAgent userAgent, final String reason) {
/// Tests whether the device identified by the given authentication header (if any) is definitively missing the SPQR
/// capability.
///
/// @return `true` if the authenticated device is definitively missing the SPQR capability or `false` if the
/// capability is present, no credentials are presented, or if authentication failed for any reason
@VisibleForTesting
boolean isMissingSpqrCapability(@Nullable final String authHeader) {
if (authHeader == null) {
return false;
}
final Optional<AuthenticatedDevice> maybeAuthenticatedDevice =
HeaderUtils.basicCredentialsFromAuthHeader(authHeader)
.flatMap(accountAuthenticator::authenticate);
return maybeAuthenticatedDevice
.flatMap(authenticatedDevice -> accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier()))
.flatMap(account -> account.getDevice(maybeAuthenticatedDevice.get().deviceId()))
.map(device -> !device.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET))
.orElse(false);
}
private void recordDeprecation(@Nullable final UserAgent userAgent, final String reason) {
Metrics.counter(DEPRECATED_CLIENT_COUNTER_NAME,
PLATFORM_TAG, userAgent != null ? userAgent.platform().name().toLowerCase() : "unrecognized",
REASON_TAG_NAME, reason).increment();
}
private void recordPendingDeprecation(final UserAgent userAgent, final String reason) {
private void recordPendingDeprecation(@Nullable final UserAgent userAgent, final String reason) {
Metrics.counter(PENDING_DEPRECATION_COUNTER_NAME,
PLATFORM_TAG, userAgent.platform().name().toLowerCase(),
PLATFORM_TAG, userAgent != null ? userAgent.platform().name().toLowerCase() : "unrecognized",
REASON_TAG_NAME, reason).increment();
}
}
@@ -27,9 +27,9 @@ public class CanonicalRequest {
@Nonnull
private final String domain;
private final int maxSizeInBytes;
private final long maxSizeInBytes;
public CanonicalRequest(@Nonnull String canonicalRequest, @Nonnull String resourcePath, @Nonnull String canonicalQuery, @Nonnull String activeDatetime, @Nonnull String credentialScope, @Nonnull String domain, int maxSizeInBytes) {
public CanonicalRequest(@Nonnull String canonicalRequest, @Nonnull String resourcePath, @Nonnull String canonicalQuery, @Nonnull String activeDatetime, @Nonnull String credentialScope, @Nonnull String domain, long maxSizeInBytes) {
this.canonicalRequest = canonicalRequest;
this.resourcePath = resourcePath;
this.canonicalQuery = canonicalQuery;
@@ -69,7 +69,7 @@ public class CanonicalRequest {
return domain;
}
public int getMaxSizeInBytes() {
public long getMaxSizeInBytes() {
return maxSizeInBytes;
}
}
@@ -26,19 +26,16 @@ public class CanonicalRequestGenerator {
@Nonnull
private final String email;
private final int maxSizeBytes;
@Nonnull
private final String pathPrefix;
public CanonicalRequestGenerator(@Nonnull String domain, @Nonnull String email, int maxSizeBytes, @Nonnull String pathPrefix) {
public CanonicalRequestGenerator(@Nonnull String domain, @Nonnull String email, @Nonnull String pathPrefix) {
this.domain = domain;
this.email = email;
this.maxSizeBytes = maxSizeBytes;
this.pathPrefix = pathPrefix;
}
public CanonicalRequest createFor(@Nonnull final String key, @Nonnull final ZonedDateTime now) {
public CanonicalRequest createFor(@Nonnull final String key, @Nonnull final ZonedDateTime now, final long uploadLength) {
final StringBuilder result = new StringBuilder("POST\n");
final StringBuilder resourcePathBuilder = new StringBuilder();
@@ -58,7 +55,7 @@ public class CanonicalRequestGenerator {
result.append(canonicalQuery).append('\n');
result.append("host:").append(domain).append('\n');
result.append("x-goog-content-length-range:1,").append(maxSizeBytes).append('\n');
result.append("x-goog-content-length-range:1,").append(uploadLength).append('\n');
result.append("x-goog-resumable:start\n");
result.append('\n');
@@ -66,7 +63,7 @@ public class CanonicalRequestGenerator {
result.append("UNSIGNED-PAYLOAD");
return new CanonicalRequest(result.toString(), resourcePath, canonicalQuery, activeDatetime, makeCredentialScope(now), domain, maxSizeBytes);
return new CanonicalRequest(result.toString(), resourcePath, canonicalQuery, activeDatetime, makeCredentialScope(now), domain, uploadLength);
}
private String makeCredentialScope(@Nonnull ZonedDateTime now) {
@@ -11,7 +11,9 @@ 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.signal.chat.errors.FailedPrecondition;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
@@ -20,12 +22,13 @@ 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 RateLimiter countRateLimiter;
private final RateLimiter bytesRateLimiter;
private final long maxUploadLength;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private final SecureRandom secureRandom;
@@ -33,9 +36,12 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
final ExperimentEnrollmentManager experimentEnrollmentManager,
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator) {
final TusAttachmentGenerator tusAttachmentGenerator,
final long maxUploadLength) {
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.rateLimiter = rateLimiters.getAttachmentLimiter();
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
this.maxUploadLength = maxUploadLength;
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
@@ -44,13 +50,29 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
@Override
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request) throws RateLimitExceededException {
if (request.getUploadLength() > maxUploadLength) {
return GetUploadFormResponse.newBuilder()
.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance())
.build();
}
final AuthenticatedDevice auth = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiter.validate(auth.accountIdentifier());
countRateLimiter.validate(auth.accountIdentifier());
try {
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
// However, just undoing the first modification if the second one fails is close enough for our purposes
bytesRateLimiter.validate(auth.accountIdentifier(), request.getUploadLength());
} catch (RateLimitExceededException e) {
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
throw e;
}
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);
final AttachmentGenerator.Descriptor descriptor =
this.attachmentGenerators.get(cdn).generateAttachment(key, request.getUploadLength());
return GetUploadFormResponse.newBuilder().setUploadForm(UploadForm.newBuilder()
.setCdn(cdn)
.setKey(key)
@@ -32,6 +32,7 @@ import org.signal.chat.backup.SetPublicKeyRequest;
import org.signal.chat.backup.SetPublicKeyResponse;
import org.signal.chat.backup.SignedPresentation;
import org.signal.chat.backup.SimpleBackupsAnonymousGrpc;
import org.signal.chat.common.UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.libsignal.protocol.InvalidKeyException;
@@ -60,10 +61,12 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
private final long maxAttachmentSize;
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics) {
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics, final long maxAttachmentSize) {
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
this.maxAttachmentSize = maxAttachmentSize;
}
@Override
@@ -178,35 +181,29 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
final GetUploadFormResponse.Builder builder = GetUploadFormResponse.newBuilder();
switch (request.getUploadTypeCase()) {
case MESSAGES -> {
final long uploadLength = request.getMessages().getUploadLength();
final boolean oversize = uploadLength > backupManager.maxMessageBackupUploadSize();
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
if (oversize) {
builder.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance());
} else {
final BackupUploadDescriptor uploadDescriptor = backupManager.createMessageBackupUploadDescriptor(backupUser);
builder.setUploadForm(builder.getUploadFormBuilder()
.setCdn(uploadDescriptor.cdn())
.setKey(uploadDescriptor.key())
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
.putAllHeaders(uploadDescriptor.headers())).build();
}
final long uploadLength = request.getUploadLength();
if (uploadLength > maxAttachmentSize) {
if (request.getUploadTypeCase() == GetUploadFormRequest.UploadTypeCase.MESSAGES) {
backupMetrics.updateMessageBackupSizeDistribution(backupUser, true, Optional.of(uploadLength));
}
case MEDIA -> {
final BackupUploadDescriptor uploadDescriptor = backupManager.createTemporaryAttachmentUploadDescriptor(
backupUser);
builder.setUploadForm(builder.getUploadFormBuilder()
return GetUploadFormResponse.newBuilder().setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance()).build();
}
final BackupUploadDescriptor uploadDescriptor = switch (request.getUploadTypeCase()) {
case MESSAGES -> {
backupMetrics.updateMessageBackupSizeDistribution(backupUser, false, Optional.of(uploadLength));
yield backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength);
}
case MEDIA -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, uploadLength);
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
};
return GetUploadFormResponse.newBuilder()
.setUploadForm(UploadForm.newBuilder()
.setCdn(uploadDescriptor.cdn())
.setKey(uploadDescriptor.key())
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
.putAllHeaders(uploadDescriptor.headers())).build();
}
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
}
return builder.build();
.putAllHeaders(uploadDescriptor.headers()))
.build();
}
@Override
@@ -221,7 +218,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList());
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
.newBuilder()
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import io.grpc.StatusRuntimeException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
@@ -31,6 +32,7 @@ import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.controllers.RateLimitKeys;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
@@ -96,18 +98,28 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
final byte deviceId = request.hasDeviceId()
? DeviceIdUtil.validate(request.getDeviceId())
: KeysGrpcHelper.ALL_DEVICES;
final String rateLimitKey = authenticatedDevice.accountIdentifier() + "." +
authenticatedDevice.deviceId() + "__" +
targetIdentifier.uuid() + "." +
deviceId;
final Optional<Integer> targetRegistrationId = maybeTargetAccount
.filter(_ -> request.hasDeviceId())
.flatMap(targetAccount -> targetAccount.getDevice(deviceId))
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
final String rateLimitKey = RateLimitKeys.preKeyLimiterKey(
authenticatedDevice.accountIdentifier(),
authenticatedDevice.deviceId(),
targetIdentifier,
Optional.ofNullable(request.hasDeviceId() ? deviceId : null),
targetRegistrationId);
rateLimiters.getPreKeysLimiter().validate(rateLimitKey);
return accountsManager.getByServiceIdentifier(targetIdentifier)
return maybeTargetAccount
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager))
.map(accountPreKeyBundles -> GetPreKeysResponse.newBuilder()
.setPreKeys(accountPreKeyBundles)
@@ -295,14 +295,16 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
MessageUtil.resolveRecipients(accountsManager, multiRecipientMessage);
try {
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
resolvedRecipients,
timestamp,
story,
ephemeral,
urgent,
RequestAttributesUtil.getUserAgent().orElse(null))
.join();
if (!resolvedRecipients.isEmpty()) {
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
resolvedRecipients,
timestamp,
story,
ephemeral,
urgent,
RequestAttributesUtil.getUserAgent().orElse(null))
.join();
}
final MultiRecipientSuccess.Builder responseBuilder = MultiRecipientSuccess.newBuilder();
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Descriptors;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.rpc.ErrorInfo;
@@ -26,6 +27,7 @@ import io.micrometer.core.instrument.Timer;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
@@ -46,15 +48,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
private static final String TAG_REASON = "reason";
@VisibleForTesting
static final String DEFAULT_SUCCESS_REASON = "success";
static final String DEFAULT_SUCCESS_REASON = "SUCCESS";
@VisibleForTesting
static final String DEFAULT_ERROR_REASON = "n/a";
static final String DEFAULT_ERROR_REASON = "N/A";
@VisibleForTesting
static final String REQUEST_MESSAGE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestMessage");
@VisibleForTesting
static final String REQUEST_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestBytes");
@VisibleForTesting
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
@VisibleForTesting
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseBytes");
@VisibleForTesting
static final String RPC_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "rpc");
@VisibleForTesting
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
@@ -99,12 +105,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
private final Counter responseMessageCounter;
private final Counter responseBytesCounter;
private final Tags tags;
private @Nullable String reason = null;
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
super(delegate);
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
this.responseBytesCounter = meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags);
this.tags = tags;
}
@@ -117,7 +125,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
}
Tags responseTags = tags.and(Tag.of(TAG_STATUS_CODE, status.getCode().name()));
if (reason != null) {
responseTags = responseTags.and(TAG_REASON, reason);
responseTags = responseTags.and(TAG_REASON, reason.toUpperCase(Locale.ROOT));
}
meterRegistry.counter(RPC_COUNTER_NAME, responseTags).increment();
super.close(status, responseHeaders);
@@ -126,6 +134,11 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void sendMessage(final RespT responseMessage) {
this.responseMessageCounter.increment();
if (responseMessage instanceof GeneratedMessage generatedMessage) {
this.responseBytesCounter.increment(generatedMessage.getSerializedSize());
}
// Extract the annotated reason (if any) from the message
final String messageReason = MetricServerCall.reason(responseMessage);
@@ -171,12 +184,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
private class MetricServerCallListener<ReqT> extends ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {
private final Counter requestCounter;
private final Counter requestBytesCounter;
private final Timer responseTimer;
private final Timer.Sample sample;
MetricServerCallListener(final ServerCall.Listener<ReqT> delegate, final Tags tags) {
super(delegate);
this.requestCounter = meterRegistry.counter(REQUEST_MESSAGE_COUNTER_NAME, tags);
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
this.sample = Timer.start(meterRegistry);
}
@@ -184,6 +199,11 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void onMessage(final ReqT requestMessage) {
this.requestCounter.increment();
if (requestMessage instanceof GeneratedMessage generatedMessage) {
this.requestBytesCounter.increment(generatedMessage.getSerializedSize());
}
super.onMessage(requestMessage);
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.limits;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import reactor.core.publisher.Mono;
public interface RateLimiter {
@@ -78,4 +77,27 @@ public interface RateLimiter {
default CompletionStage<Void> clearAsync(final UUID accountUuid) {
return clearAsync(accountUuid.toString());
}
/// Restore `permitsToRestore` permits to the pool. If the RateLimiter has a maximum bucket size, it is respected even
/// if `permitsToRestore` would exceed the maximum bucket size.
///
/// @param key The key to restore permits for.
/// @param permitsToRestore The number of permits to restore
/// @implNote The default implementation of this method assumes permits can be restored by calling `validate` with a
/// negative permit count. If the `validate` implementation does not support this, the implementor must provide a
/// custom implementation of [this#restorePermits].
default void restorePermits(final String key, int permitsToRestore) {
if (permitsToRestore < 0) {
throw new IllegalArgumentException("permits to restore must be non-negative");
}
try {
validate(key, -1 * permitsToRestore);
} catch (RateLimitExceededException e) {
throw new IllegalStateException("Out of permits when trying to restore permits", e);
}
}
default void restorePermits(final UUID accountUuid, int permitsToRestore) {
restorePermits(accountUuid.toString(), permitsToRestore);
}
}
@@ -8,6 +8,7 @@ import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import io.dropwizard.util.DataSize;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -19,6 +20,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
BACKUP_AUTH_CHECK("backupAuthCheck", new RateLimiterConfig(100, Duration.ofMinutes(15), true)),
PIN("pin", new RateLimiterConfig(10, Duration.ofDays(1), false)),
ATTACHMENT("attachmentCreate", new RateLimiterConfig(50, Duration.ofMillis(1200), true)),
ATTACHMENT_BYTES("attachmentCreateBytes", new RateLimiterConfig(DataSize.gigabytes(1).toBytes(), Duration.ofNanos(1000), true)),
BACKUP_ATTACHMENT("backupAttachmentCreate", new RateLimiterConfig(10_000, Duration.ofSeconds(1), true)),
PRE_KEYS("prekeys", new RateLimiterConfig(6, Duration.ofMinutes(10), false)),
MESSAGES("messages", new RateLimiterConfig(60, Duration.ofSeconds(1), true)),
@@ -115,6 +117,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.ATTACHMENT);
}
public RateLimiter getAttachmentBytesLimiter() {
return forDescriptor(For.ATTACHMENT_BYTES);
}
public RateLimiter getPinLimiter() {
return forDescriptor(For.PIN);
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@@ -36,42 +37,41 @@ public enum DeviceCapability {
ALWAYS_CAPABLE,
}
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_REGISTRATION =
Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::requireForRegistration)
.collect(Collectors.toSet());
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_NEW_DEVICES =
EnumSet.copyOf(Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::requireForNewDevices)
.collect(Collectors.toSet()));
private final String name;
private final AccountCapabilityMode accountCapabilityMode;
private final boolean preventDowngrade;
private final boolean includeInProfile;
private final boolean requireForRegistration;
private final boolean requireForNewDevices;
/**
* Create a DeviceCapability
*
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES.
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server.
* @param requireForRegistration If true, prevent account creation if the account's initial device does not have this
* capability
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES.
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server.
* @param requireForNewDevices If true, prevent device creation if the new device does not have this capability
*/
DeviceCapability(final String name,
final AccountCapabilityMode accountCapabilityMode,
final boolean preventDowngrade,
final boolean includeInProfile,
final boolean requireForRegistration) {
final boolean requireForNewDevices) {
this.name = name;
this.accountCapabilityMode = accountCapabilityMode;
this.preventDowngrade = preventDowngrade;
this.includeInProfile = includeInProfile;
this.requireForRegistration = requireForRegistration;
this.requireForNewDevices = requireForNewDevices;
}
public String getName() {
@@ -90,8 +90,8 @@ public enum DeviceCapability {
return includeInProfile;
}
public boolean requireForRegistration() {
return requireForRegistration;
public boolean requireForNewDevices() {
return requireForNewDevices;
}
public static Optional<DeviceCapability> forName(final String name) {
@@ -0,0 +1,99 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.util.retry.Retry;
import java.time.Duration;
public class RemoveNonSpqrAccountsCommand extends AbstractSinglePassCrawlAccountsCommand {
static final String MAX_ACCOUNTS_ARGUMENT = "maxAccounts";
static final String MAX_CONCURRENCY_ARGUMENT = "maxConcurrency";
static final String DRY_RUN_ARGUMENT = "dryRun";
private static final String REMOVE_ACCOUNT_COUNTER_NAME =
MetricsUtil.name(RemoveNonSpqrAccountsCommand.class, "removeAccount");
private static final Logger logger = LoggerFactory.getLogger(RemoveNonSpqrAccountsCommand.class);
public RemoveNonSpqrAccountsCommand() {
super("remove-non-spqr-accounts", "Removes accounts whose primary devices do not support SPQR");
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--max-accounts")
.type(Integer.class)
.dest(MAX_ACCOUNTS_ARGUMENT)
.required(true)
.help("Max accounts to remove in a single run of this command");
subparser.addArgument("--max-concurrency")
.type(Integer.class)
.dest(MAX_CONCURRENCY_ARGUMENT)
.required(false)
.setDefault(32)
.help("Max concurrency for DynamoDB operations");
subparser.addArgument("--dry-run")
.type(Boolean.class)
.dest(DRY_RUN_ARGUMENT)
.required(false)
.setDefault(true)
.help("If true, don't actually remove accounts");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final int maxAccounts = getNamespace().getInt(MAX_ACCOUNTS_ARGUMENT);
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
final AccountsManager accountsManager = getCommandDependencies().accountsManager();
final Counter removeAccountCounterName =
Metrics.counter(REMOVE_ACCOUNT_COUNTER_NAME, "dryRun", String.valueOf(dryRun));
accounts
.filter(account -> !account.getPrimaryDevice().hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET))
.take(maxAccounts)
.flatMap(account -> {
final Mono<Void> removeAccountMono = dryRun
? Mono.empty()
: Mono.fromRunnable(() -> accountsManager.delete(account, AccountsManager.DeletionReason.ADMIN_DELETED))
.subscribeOn(Schedulers.boundedElastic())
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.onErrorResume(throwable -> {
logger.warn("Failed to remove account: {}",
account.getIdentifier(IdentityType.ACI),
throwable);
return Mono.empty();
})
.then();
return removeAccountMono
.doOnSuccess(_ -> removeAccountCounterName.increment());
}, maxConcurrency)
.then()
.block();
}
}
@@ -0,0 +1,93 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
import reactor.util.retry.Retry;
import java.time.Duration;
public class RemoveNonSpqrLinkedDevicesCommand extends AbstractSinglePassCrawlAccountsCommand {
static final String MAX_CONCURRENCY_ARGUMENT = "maxConcurrency";
static final String DRY_RUN_ARGUMENT = "dryRun";
private static final String REMOVE_DEVICE_COUNTER_NAME =
MetricsUtil.name(RemoveNonSpqrLinkedDevicesCommand.class, "removeLinkedDevice");
private static final Logger logger = LoggerFactory.getLogger(RemoveNonSpqrLinkedDevicesCommand.class);
public RemoveNonSpqrLinkedDevicesCommand() {
super("remove-non-spqr-linked-devices", "Removes linked devices that do not support SPQR");
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--max-concurrency")
.type(Integer.class)
.dest(MAX_CONCURRENCY_ARGUMENT)
.required(false)
.setDefault(32)
.help("Max concurrency for DynamoDB operations");
subparser.addArgument("--dry-run")
.type(Boolean.class)
.dest(DRY_RUN_ARGUMENT)
.required(false)
.setDefault(true)
.help("If true, don't actually remove linked devices");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
final AccountsManager accountsManager = getCommandDependencies().accountsManager();
final Counter removeDeviceCounterName =
Metrics.counter(REMOVE_DEVICE_COUNTER_NAME, "dryRun", String.valueOf(dryRun));
accounts
.flatMap(account -> Flux.fromIterable(account.getDevices())
.filter(device -> !device.isPrimary())
.filter(device -> !device.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET))
.map(device -> Tuples.of(account, device.getId())))
.flatMap(accountAndDeviceId -> {
final Mono<Void> removeDeviceMono = dryRun
? Mono.empty()
: Mono.fromRunnable(() -> accountsManager.removeDevice(accountAndDeviceId.getT1(), accountAndDeviceId.getT2()))
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.onErrorResume(throwable -> {
logger.warn("Failed to remove device: {}:{}",
accountAndDeviceId.getT1().getIdentifier(IdentityType.ACI),
accountAndDeviceId.getT2(),
throwable);
return Mono.empty();
})
.then();
return removeDeviceMono
.doOnSuccess(_ -> removeDeviceCounterName.increment());
}, maxConcurrency)
.then()
.block();
}
}
@@ -7,6 +7,7 @@ package org.signal.chat.account;
import "org/signal/chat/common.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
// Provides methods for working with Signal accounts.
service Accounts {
@@ -115,7 +116,7 @@ message ReserveUsernameHashResponse {
// Indicates that, of all of the candidate hashes provided, none were
// available. Callers may generate a new set of hashes and and retry.
UsernameNotAvailable username_not_available = 2;
UsernameNotAvailable username_not_available = 2 [(tag.reason) = "username_not_available"];
}
}
@@ -146,11 +147,11 @@ message ConfirmUsernameHashResponse {
ConfirmedUsernameHash confirmed_username_hash = 1;
// The provided hash was not reserved for the account.
errors.FailedPrecondition reservation_not_found = 2;
errors.FailedPrecondition reservation_not_found = 2 [(tag.reason) = "reservation_not_found"];
// The reservation has lapsed and the requested username has been claimed by
// another caller.
UsernameNotAvailable username_not_available = 3;
UsernameNotAvailable username_not_available = 3 [(tag.reason) = "username_not_available"];
}
}
@@ -177,7 +178,7 @@ message SetUsernameLinkResponse {
bytes username_link_handle = 1;
// The authenticated account did not have a username set.
errors.FailedPrecondition no_username_set = 2;
errors.FailedPrecondition no_username_set = 2 [(tag.reason) = "no_username_set"];
}
}
@@ -244,7 +245,7 @@ message LookupUsernameHashResponse {
common.ServiceIdentifier service_identifier = 1;
// No account was found for the provided username hash.
errors.NotFound not_found = 2;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
@@ -261,6 +262,6 @@ message LookupUsernameLinkResponse {
// No username was found for the provided link handle.
errors.NotFound not_found = 2;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
@@ -11,6 +11,8 @@ package org.signal.chat.attachments;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/tag.proto";
service Attachments {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
@@ -19,7 +21,19 @@ service Attachments {
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
}
message GetUploadFormRequest {}
message GetUploadFormRequest {
// The length of the attachment for the requested upload form. Uploads
// performed with this form will be limited to the provided length.
uint64 uploadLength = 1 [(require.range) = {min: 1}];
}
message GetUploadFormResponse {
common.UploadForm upload_form = 1;
oneof outcome {
common.UploadForm upload_form = 1;
// The request size was larger than the maximum supported upload size. The
// maximum upload size is subject to change and is governed by
// `global.attachments.maxBytes`
errors.FailedPrecondition exceeds_max_upload_length = 2 [(tag.reason) = "oversize_upload"];
}
}
@@ -84,7 +84,7 @@ message RedeemReceiptRequest {
}
message RedeemReceiptResponse {
oneof outcome {
oneof response {
// The receipt was successfully redeemed
google.protobuf.Empty success = 1;
@@ -217,7 +217,7 @@ message SetPublicKeyRequest {
}
message SetPublicKeyResponse {
oneof outcome {
oneof response {
// The public key was successfully set
google.protobuf.Empty success = 1;
@@ -240,7 +240,7 @@ message GetCdnCredentialsResponse {
message CdnCredentials {
map<string, string> headers = 1;
}
oneof outcome {
oneof response {
// Headers to include with requests to the read from the backup CDN. Includes
// time limited read-only credentials.
CdnCredentials cdn_credentials = 1;
@@ -266,7 +266,7 @@ message GetSvrBCredentialsResponse {
string password = 2;
}
oneof outcome {
oneof response {
SvrBCredentials svrb_credentials = 1;
// The provided backup auth credential presentation could not be
@@ -295,7 +295,7 @@ message GetMessageBackupInfoResponse {
string backup_name = 3;
}
oneof outcome {
oneof response {
MessageBackupInfo backup_info = 1;
// The provided backup auth credential presentation could not be
@@ -319,7 +319,7 @@ message GetMediaBackupInfoResponse {
uint64 used_space = 3;
}
oneof outcome {
oneof response {
MediaBackupInfo backup_info = 1;
// The provided backup auth credential presentation could not be
@@ -334,7 +334,7 @@ message RefreshRequest {
SignedPresentation signed_presentation = 1;
}
message RefreshResponse {
oneof outcome {
oneof response {
// The backup was successfully refreshed
google.protobuf.Empty success = 1;
@@ -349,9 +349,7 @@ message RefreshResponse {
message GetUploadFormRequest {
SignedPresentation signed_presentation = 1;
message MessagesUploadType {
uint64 upload_length = 1;
}
message MessagesUploadType {}
message MediaUploadType {}
oneof upload_type {
// Retrieve an upload form that can be used to perform a resumable upload of
@@ -365,9 +363,13 @@ message GetUploadFormRequest {
// Behaves identically to the account authenticated version at /attachments.
MediaUploadType media = 3;
}
// The length of the attachment for the requested upload form. Uploads
// performed with this form will be limited to the provided length.
uint64 uploadLength = 4 [(require.range) = {min: 1}];
}
message GetUploadFormResponse {
oneof outcome {
oneof response {
common.UploadForm upload_form = 1;
// The provided backup auth credential presentation could not be
@@ -377,7 +379,8 @@ message GetUploadFormResponse {
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
// The request size was larger than the maximum supported upload size. The
// maximum upload size is subject to change.
// maximum upload size is subject to change and is governed by
// `global.attachments.maxBytes`
errors.FailedPrecondition exceeds_max_upload_length = 3 [(tag.reason) = "oversize_upload"];
}
}
@@ -422,7 +425,7 @@ message CopyMediaResponse {
// The 15-byte media_id from the corresponding CopyMediaItem in the request
bytes media_id = 1;
oneof outcome {
oneof response {
// The media item was successfully copied into the backup
CopySuccess success = 2;
@@ -433,13 +436,13 @@ message CopyMediaResponse {
errors.FailedZkAuthentication failed_authentication = 3 [(tag.reason) = "failed_authentication"];
// The source object was not found
SourceNotFound source_not_found = 4;
SourceNotFound source_not_found = 4 [(tag.reason) = "source_not_found"];
// The provided object length was incorrect
WrongSourceLength wrong_source_length = 5;
WrongSourceLength wrong_source_length = 5 [(tag.reason) = "wrong_source_length"];
// All media capacity has been consumed. Free some space to continue.
OutOfSpace out_of_space = 6;
OutOfSpace out_of_space = 6 [(tag.reason) = "out_of_space"];
}
}
@@ -482,7 +485,7 @@ message ListMediaResponse {
optional string cursor = 4;
}
oneof outcome {
oneof response {
ListResult list_result = 1;
// The provided backup auth credential presentation could not be
@@ -497,7 +500,7 @@ message DeleteAllRequest {
SignedPresentation signed_presentation = 1;
}
message DeleteAllResponse {
oneof outcome {
oneof response {
// The backup was successfully scheduled for deletion
google.protobuf.Empty success = 1;
@@ -524,7 +527,7 @@ message DeleteMediaRequest {
}
message DeleteMediaResponse {
oneof outcome {
oneof response {
DeleteMediaItem deleted_item = 1;
// The provided backup auth credential presentation could not be
@@ -14,6 +14,7 @@ import "google/protobuf/empty.proto";
import "org/signal/chat/common.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
// Provides methods for working with pre-keys.
service Keys {
@@ -152,7 +153,7 @@ message GetPreKeysResponse {
// Either the target account was not found, no active device with the given
// ID (if specified) was found on the target account.
errors.NotFound target_not_found = 2;
errors.NotFound target_not_found = 2 [(tag.reason) = "not_found"];
}
}
@@ -163,10 +164,10 @@ message GetPreKeysAnonymousResponse {
// Either the target account was not found, no active device with the given
// ID (if specified) was found on the target account.
errors.NotFound target_not_found = 2;
errors.NotFound target_not_found = 2 [(tag.reason) = "not_found"];
// The provided unidentified authorization credential was invalid
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3;
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
@@ -14,6 +14,7 @@ import "google/protobuf/empty.proto";
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/tag.proto";
// Provides methods for sending "unsealed sender" messages.
service Messages {
@@ -153,14 +154,14 @@ message SendMessageAuthenticatedSenderResponse {
// A list of discrepancies between the destination devices identified in a
// request to send a message and the devices that are actually linked to an
// account.
MismatchedDevices mismatched_devices = 2;
MismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
// A description of a challenge callers must complete before sending
// additional messages.
ChallengeRequired challenge_required = 3;
ChallengeRequired challenge_required = 3 [(tag.reason) = "challenge_required"];
// The destination account did not exist
errors.NotFound destination_not_found = 4;
errors.NotFound destination_not_found = 4 [(tag.reason) = "destination_not_found"];
}
}
@@ -233,13 +234,13 @@ message SendMessageResponse {
// A list of discrepancies between the destination devices identified in a
// request to send a message and the devices that are actually linked to an
// account.
MismatchedDevices mismatched_devices = 2;
MismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
// The provided unidentified authorization credential was invalid
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3;
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
// The destination account did not exist
errors.NotFound destination_not_found = 4;
errors.NotFound destination_not_found = 4 [(tag.reason) = "destination_not_found"];
}
}
@@ -307,10 +308,10 @@ message SendMultiRecipientMessageResponse {
// A list of sets of discrepancies between the destination devices
// identified in a request to send a message and the devices that are
// actually linked to a destination account.
MultiRecipientMismatchedDevices mismatched_devices = 2;
MultiRecipientMismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
// The provided unidentified authorization credential was invalid
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3;
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
@@ -13,7 +13,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
@@ -34,8 +33,16 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
@ExtendWith(MockitoExtension.class)
public class CloudflareTurnCredentialsManagerTest {
@RegisterExtension
private static final WireMockExtension wireMock = WireMockExtension.newInstance()
@@ -44,7 +51,12 @@ public class CloudflareTurnCredentialsManagerTest {
private ExecutorService httpExecutor;
private ScheduledExecutorService retryExecutor;
@Mock
private DnsNameResolver dnsResolver;
@Mock
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
@Mock
private ExperimentEnrollmentManager experimentEnrollmentManager;
private CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
@@ -64,8 +76,6 @@ public class CloudflareTurnCredentialsManagerTest {
httpExecutor = Executors.newSingleThreadExecutor();
retryExecutor = Executors.newSingleThreadScheduledExecutor();
dnsResolver = mock(DnsNameResolver.class);
cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
API_TOKEN,
"http://localhost:" + wireMock.getPort() + GET_CREDENTIALS_PATH,
@@ -79,7 +89,9 @@ public class CloudflareTurnCredentialsManagerTest {
httpExecutor,
null,
retryExecutor,
dnsResolver
dnsResolver,
dynamicConfigurationManager,
experimentEnrollmentManager
);
}
@@ -116,7 +128,7 @@ public class CloudflareTurnCredentialsManagerTest {
.thenReturn(new SucceededFuture<>(GlobalEventExecutor.INSTANCE,
List.of(InetAddress.getByName("127.0.0.1"), InetAddress.getByName("::1"))));
TurnToken token = cloudflareTurnCredentialsManager.retrieveFromCloudflare();
TurnToken token = cloudflareTurnCredentialsManager.retrieveFromCloudflare(AuthHelper.VALID_UUID);
wireMock.verify(postRequestedFor(urlEqualTo(GET_CREDENTIALS_PATH))
.withHeader("Content-Type", equalTo("application/json"))
@@ -152,8 +152,6 @@ public class BackupManagerTest {
when(dynamicConfiguration.getBackupConfiguration()).thenReturn(backupConfiguration);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(tusAttachmentGenerator.maxUploadSizeInBytes()).thenReturn(MAX_UPLOAD_SIZE);
this.backupManager = new BackupManager(
backupsDb,
backupAuthTestUtil.params,
@@ -224,9 +222,9 @@ public class BackupManagerTest {
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, backupLevel);
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, 17);
verify(tusCredentialGenerator, times(1))
.generateUpload("%s/%s".formatted(backupUser.backupDir(), BackupManager.MESSAGE_BACKUP_NAME));
.generateUpload("%s/%s".formatted(backupUser.backupDir(), BackupManager.MESSAGE_BACKUP_NAME), 17);
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser);
assertThat(info.backupSubdir()).isEqualTo(backupUser.backupDir()).isNotBlank();
@@ -247,7 +245,7 @@ public class BackupManagerTest {
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, backupLevel);
assertThatExceptionOfType(BackupWrongCredentialTypeException.class)
.isThrownBy(() -> backupManager.createMessageBackupUploadDescriptor(backupUser));
.isThrownBy(() -> backupManager.createMessageBackupUploadDescriptor(backupUser, MAX_UPLOAD_SIZE));
}
@Test
@@ -256,21 +254,21 @@ public class BackupManagerTest {
doThrow(new RateLimitExceededException(null))
.when(mediaUploadLimiter).validate(eq(BackupManager.rateLimitKey(backupUser)));
assertThatExceptionOfType(RateLimitExceededException.class)
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, MAX_UPLOAD_SIZE));
}
@Test
public void createTemporaryMediaAttachmentWrongTier() {
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.FREE);
assertThatExceptionOfType(BackupPermissionException.class)
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, MAX_UPLOAD_SIZE));
}
@Test
public void createTemporaryMediaAttachmentWrongCredentialType() {
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
assertThatExceptionOfType(BackupWrongCredentialTypeException.class)
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, MAX_UPLOAD_SIZE));
}
@ParameterizedTest
@@ -283,7 +281,7 @@ public class BackupManagerTest {
// create backup at t=tstart
testClock.pin(tstart);
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, MAX_UPLOAD_SIZE);
// refresh at t=tnext
testClock.pin(tnext);
@@ -305,11 +303,11 @@ public class BackupManagerTest {
// create backup at t=tstart
testClock.pin(tstart);
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, MAX_UPLOAD_SIZE);
// create again at t=tnext
testClock.pin(tnext);
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, MAX_UPLOAD_SIZE);
checkExpectedExpirations(
tnext.truncatedTo(ChronoUnit.DAYS),
@@ -478,7 +476,7 @@ public class BackupManagerTest {
.thenReturn(slow);
final ArrayBlockingQueue<CopyResult> copyResults = new ArrayBlockingQueue<>(100);
final CompletableFuture<Void> future = backupManager
.copyToBackup(backupManager.getCopyQuota(backupUser, toCopy))
.copyToBackup(backupManager.getCopyQuota(backupUser, toCopy, MAX_UPLOAD_SIZE))
.doOnNext(copyResults::add).then().toFuture();
for (int i = 0; i < slowIndex; i++) {
@@ -525,7 +523,7 @@ public class BackupManagerTest {
new CopyParameters(3, "missing", 200, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)),
new CopyParameters(3, "badlength", 300, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)));
when(tusCredentialGenerator.generateUpload(any()))
when(tusCredentialGenerator.generateUpload(any(), anyLong()))
.thenReturn(new BackupUploadDescriptor(3, "", Collections.emptyMap(), ""));
when(remoteStorageManager.copy(eq(3), eq("success"), eq(100), any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
@@ -534,7 +532,8 @@ public class BackupManagerTest {
when(remoteStorageManager.copy(eq(3), eq("badlength"), eq(300), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new InvalidLengthException("")));
final List<CopyResult> results = backupManager.copyToBackup(backupManager.getCopyQuota(backupUser, toCopy))
final List<CopyResult> results = backupManager
.copyToBackup(backupManager.getCopyQuota(backupUser, toCopy, MAX_UPLOAD_SIZE))
.collectList().block();
assertThat(results).hasSize(3);
@@ -871,7 +870,7 @@ public class BackupManagerTest {
.toList();
for (int i = 0; i < backupUsers.size(); i++) {
testClock.pin(days(i));
backupManager.createMessageBackupUploadDescriptor(backupUsers.get(i));
backupManager.createMessageBackupUploadDescriptor(backupUsers.get(i), MAX_UPLOAD_SIZE);
}
// set of backup-id hashes that should be expired (initially t=0)
@@ -906,11 +905,11 @@ public class BackupManagerTest {
// refreshed media timestamp at t=5
testClock.pin(days(5));
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.PAID));
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.PAID), MAX_UPLOAD_SIZE);
// refreshed messages timestamp at t=6
testClock.pin(days(6));
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.FREE));
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.FREE), MAX_UPLOAD_SIZE);
Function<Instant, List<ExpiredBackup>> getExpired = time -> backupManager
.getExpiredBackups(1, Schedulers.immediate(), time)
@@ -931,7 +930,7 @@ public class BackupManagerTest {
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"MEDIA", "ALL"})
public void expireBackup(ExpiredBackup.ExpirationType expirationType) throws BackupException {
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, MAX_UPLOAD_SIZE);
final String expectedPrefixToDelete = switch (expirationType) {
case ALL -> backupUser.backupDir();
@@ -975,7 +974,7 @@ public class BackupManagerTest {
@Test
public void deleteBackupPaginated() throws BackupException {
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, MAX_UPLOAD_SIZE);
final ExpiredBackup expiredBackup = expiredBackup(ExpiredBackup.ExpirationType.MEDIA, backupUser);
final String mediaPrefix = expiredBackup.prefixToDelete() + "/";
@@ -1033,21 +1032,24 @@ public class BackupManagerTest {
}
private CopyResult copyError(final AuthenticatedBackupUser backupUser, Throwable copyException) throws BackupException {
when(tusCredentialGenerator.generateUpload(any()))
when(tusCredentialGenerator.generateUpload(any(), anyLong()))
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
when(remoteStorageManager.copy(eq(3), eq(COPY_PARAM.sourceKey()), eq(COPY_PARAM.sourceLength()), any(), any()))
.thenReturn(CompletableFuture.failedFuture(copyException));
return backupManager.copyToBackup(backupManager.getCopyQuota(backupUser, List.of(COPY_PARAM))).single().block();
return backupManager
.copyToBackup(backupManager.getCopyQuota(backupUser, List.of(COPY_PARAM), MAX_UPLOAD_SIZE))
.single().block();
}
private CopyResult copy(final AuthenticatedBackupUser backupUser) throws BackupException {
when(tusCredentialGenerator.generateUpload(any()))
when(tusCredentialGenerator.generateUpload(any(), anyLong()))
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
when(tusCredentialGenerator.generateUpload(any()))
when(tusCredentialGenerator.generateUpload(any(), anyLong()))
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
when(remoteStorageManager.copy(eq(3), eq(COPY_PARAM.sourceKey()), eq(COPY_PARAM.sourceLength()), any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
return backupManager.copyToBackup(backupManager.getCopyQuota(backupUser, List.of(COPY_PARAM))).single().block();
return backupManager.copyToBackup(backupManager.getCopyQuota(backupUser, List.of(COPY_PARAM), MAX_UPLOAD_SIZE))
.single().block();
}
private static ExpiredBackup expiredBackup(final ExpiredBackup.ExpirationType expirationType,
@@ -28,10 +28,9 @@ public class Cdn3BackupCredentialGeneratorTest {
public void uploadGenerator() {
final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration(
new SecretBytes(SECRET),
"https://example.org/upload",
MAX_UPLOAD_LENGTH));
"https://example.org/upload"));
final BackupUploadDescriptor messageBackupUploadDescriptor = generator.generateUpload("subdir/key");
final BackupUploadDescriptor messageBackupUploadDescriptor = generator.generateUpload("subdir/key", MAX_UPLOAD_LENGTH);
assertThat(messageBackupUploadDescriptor.signedUploadLocation()).isEqualTo("https://example.org/upload/backups");
assertThat(messageBackupUploadDescriptor.key()).isEqualTo("subdir/key");
assertThat(messageBackupUploadDescriptor.headers()).containsKey("Authorization");
@@ -50,8 +49,7 @@ public class Cdn3BackupCredentialGeneratorTest {
public void readCredential() {
final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration(
new SecretBytes(SECRET),
"https://example.org/upload",
MAX_UPLOAD_LENGTH));
"https://example.org/upload"));
final Map<String, String> headers = generator.readHeaders("subdir");
assertThat(headers).containsKey("Authorization");
@@ -236,12 +236,12 @@ class DynamicConfigurationTest {
.getRemoteDeprecationConfiguration();
assertEquals(Map.of(ClientPlatform.IOS, new Semver("1.2.3"), ClientPlatform.ANDROID, new Semver("4.5.6")),
remoteDeprecationConfiguration.getMinimumVersions());
remoteDeprecationConfiguration.minimumVersions());
assertEquals(Map.of(ClientPlatform.DESKTOP, new Semver("7.8.9")),
remoteDeprecationConfiguration.getVersionsPendingDeprecation());
remoteDeprecationConfiguration.versionsPendingDeprecation());
assertEquals(Map.of(ClientPlatform.DESKTOP, Set.of(new Semver("1.4.0-beta.2"))),
remoteDeprecationConfiguration.getBlockedVersions());
assertTrue(remoteDeprecationConfiguration.getVersionsPendingBlock().isEmpty());
remoteDeprecationConfiguration.blockedVersions());
assertTrue(remoteDeprecationConfiguration.versionsPendingBlock().isEmpty());
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -73,6 +74,7 @@ import org.whispersystems.textsecuregcm.backup.BackupManager;
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
import org.whispersystems.textsecuregcm.backup.CopyResult;
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
@@ -90,7 +92,7 @@ import reactor.core.publisher.Flux;
@ExtendWith(DropwizardExtensionsSupport.class)
public class ArchiveControllerTest {
private static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = 1000L;
private static final long MAX_ATTACHMENT_SIZE = 1000L;
private static final AccountsManager accountsManager = mock(AccountsManager.class);
private static final BackupAuthManager backupAuthManager = mock(BackupAuthManager.class);
private static final BackupManager backupManager = mock(BackupManager.class);
@@ -106,7 +108,7 @@ public class ArchiveControllerTest {
.addProvider(new RateLimitExceededExceptionMapper())
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new ArchiveController(accountsManager, backupAuthManager, backupManager, new BackupMetrics()))
.addResource(new ArchiveController(accountsManager, backupAuthManager, backupManager, new BackupMetrics(), MAX_ATTACHMENT_SIZE))
.build();
private final UUID aci = UUID.randomUUID();
@@ -118,8 +120,6 @@ public class ArchiveControllerTest {
reset(backupAuthManager);
reset(backupManager);
when(backupManager.maxMessageBackupUploadSize()).thenReturn(MAX_MESSAGE_BACKUP_OBJECT_SIZE);
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID))
.thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
}
@@ -615,8 +615,8 @@ public class ArchiveControllerTest {
static Stream<Arguments> messagesUploadForm() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE), true),
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false)
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE), true),
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE + 1), false)
);
}
@@ -627,7 +627,7 @@ public class ArchiveControllerTest {
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
when(backupManager.authenticateBackupUser(any(), any(), any()))
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
when(backupManager.createMessageBackupUploadDescriptor(any()))
when(backupManager.createMessageBackupUploadDescriptor(any(), anyLong()))
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
final WebTarget builder = resources.getJerseyTest().target("v1/archives/upload/form");
@@ -641,36 +641,59 @@ public class ArchiveControllerTest {
if (expectSuccess) {
assertThat(response.getStatus()).isEqualTo(200);
ArchiveController.UploadDescriptorResponse desc = response.readEntity(ArchiveController.UploadDescriptorResponse.class);
assertThat(desc.cdn()).isEqualTo(3);
assertThat(desc.key()).isEqualTo("abc");
assertThat(desc.headers()).containsExactlyEntriesOf(Map.of("k", "v"));
assertThat(desc.signedUploadLocation()).isEqualTo("example.org");
assertThat(desc)
.isEqualTo(new ArchiveController.UploadDescriptorResponse(3, "abc", Map.of("k", "v"), "example.org"));
verify(backupManager).createMessageBackupUploadDescriptor(any(), eq(uploadLength.orElse(MAX_ATTACHMENT_SIZE)));
} else {
assertThat(response.getStatus()).isEqualTo(413);
}
}
static Stream<Arguments> mediaUploadForm() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE), true),
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE + 1), false)
);
}
@ParameterizedTest
@MethodSource
public void mediaUploadForm(Optional<Long> uploadLength, boolean expectSuccess) throws VerificationFailedException, BackupException, RateLimitExceededException {
final BackupAuthCredentialPresentation presentation =
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
when(backupManager.authenticateBackupUser(any(), any(), any()))
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
when(backupManager.createTemporaryAttachmentUploadDescriptor(any(), anyLong()))
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
final WebTarget builder = resources.getJerseyTest().target("v1/archives/media/upload/form");
final Response response = uploadLength
.map(length -> builder.queryParam("uploadLength", length))
.orElse(builder)
.request()
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
.header("X-Signal-ZK-Auth-Signature", "aaa")
.get();
if (expectSuccess) {
assertThat(response.getStatus()).isEqualTo(200);
final ArchiveController.UploadDescriptorResponse desc =
response.readEntity(ArchiveController.UploadDescriptorResponse.class);
assertThat(desc)
.isEqualTo(new ArchiveController.UploadDescriptorResponse(3, "abc", Map.of("k", "v"), "example.org"));
verify(backupManager).createTemporaryAttachmentUploadDescriptor(any(), eq(uploadLength.orElse(MAX_ATTACHMENT_SIZE)));
} else {
assertThat(response.getStatus()).isEqualTo(413);
}
}
@Test
public void mediaUploadForm() throws VerificationFailedException, BackupException, RateLimitExceededException {
public void rateLimitMediaUploadForm()
throws BackupWrongCredentialTypeException, RateLimitExceededException, BackupPermissionException, VerificationFailedException, BackupFailedZkAuthenticationException {
final BackupAuthCredentialPresentation presentation =
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
when(backupManager.authenticateBackupUser(any(), any(), any()))
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
final ArchiveController.UploadDescriptorResponse desc = resources.getJerseyTest()
.target("v1/archives/media/upload/form")
.request()
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
.header("X-Signal-ZK-Auth-Signature", "aaa")
.get(ArchiveController.UploadDescriptorResponse.class);
assertThat(desc.cdn()).isEqualTo(3);
assertThat(desc.key()).isEqualTo("abc");
assertThat(desc.headers()).containsExactlyEntriesOf(Map.of("k", "v"));
assertThat(desc.signedUploadLocation()).isEqualTo("example.org");
// rate limit
when(backupManager.createTemporaryAttachmentUploadDescriptor(any())).thenThrow(new RateLimitExceededException(null));
when(backupManager.createTemporaryAttachmentUploadDescriptor(any(), anyLong())).thenThrow(new RateLimitExceededException(null));
final Response response = resources.getJerseyTest()
.target("v1/archives/media/upload/form")
.request()
@@ -7,12 +7,16 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
@@ -30,8 +34,12 @@ import java.util.Map;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
@@ -41,7 +49,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.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -50,11 +58,13 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
class AttachmentControllerV4Test {
private static final RateLimiter RATE_LIMITER = mock(RateLimiter.class);
private static final RateLimiters RATE_LIMITERS = MockUtils.buildMock(RateLimiters.class, rateLimiters ->
when(rateLimiters.getAttachmentLimiter()).thenReturn(RATE_LIMITER));
private static final RateLimiter COUNT_RATE_LIMITER = mock(RateLimiter.class);
private static final RateLimiter BYTE_RATE_LIMITER = mock(RateLimiter.class);
private static final RateLimiters RATE_LIMITERS = MockUtils.buildMock(RateLimiters.class, rateLimiters -> {
when(rateLimiters.getAttachmentLimiter()).thenReturn(COUNT_RATE_LIMITER);
when(rateLimiters.getAttachmentBytesLimiter()).thenReturn(BYTE_RATE_LIMITER);
});
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);
@@ -65,6 +75,7 @@ class AttachmentControllerV4Test {
private static final byte[] TUS_SECRET = TestRandomUtil.nextBytes(32);
private static final String TUS_URL = "https://example.com/uploads";
private static final long MAX_UPLOAD_LENGTH = 1000;
public static final String RSA_PRIVATE_KEY_PEM;
@@ -88,26 +99,94 @@ class AttachmentControllerV4Test {
static {
try {
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator("some-cdn.signal.org",
"signal@example.com", 1000, "/attach-here", RSA_PRIVATE_KEY_PEM);
"signal@example.com", "/attach-here", RSA_PRIVATE_KEY_PEM);
resources = ResourceExtension.builder()
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.setMapper(SystemMapper.jsonMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addProvider(new RateLimitExceededExceptionMapper())
.addProvider(new AttachmentControllerV4(RATE_LIMITERS,
gcsAttachmentGenerator,
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL, 1000)),
EXPERIMENT_MANAGER))
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL)),
EXPERIMENT_MANAGER, MAX_UPLOAD_LENGTH))
.build();
} catch (IOException | InvalidKeyException | InvalidKeySpecException e) {
throw new AssertionError(e);
}
}
@AfterEach
public void tearDown() {
reset(COUNT_RATE_LIMITER, BYTE_RATE_LIMITER);
}
@ParameterizedTest
@ValueSource(longs = {-1, 0})
void testInvalidUploadLength(final long uploadLength) {
assertThat(resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.queryParam("uploadLength", uploadLength)
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get().getStatus())
.isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
}
@Test
void testUploadTooLarge() {
assertThat(resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.queryParam("uploadLength", MAX_UPLOAD_LENGTH + 1)
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get().getStatus())
.isEqualTo(Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
}
@Test
void missingUploadLengthDoesNotRateLimit() throws RateLimitExceededException {
doThrow(RateLimitExceededException.class).when(BYTE_RATE_LIMITER).validate(AuthHelper.VALID_UUID);
assertThatNoException().isThrownBy(() -> resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get().getStatus());
}
@Test
void countRateLimitExceeded() throws RateLimitExceededException {
doThrow(RateLimitExceededException.class).when(COUNT_RATE_LIMITER).validate(AuthHelper.VALID_UUID);
assertThat(resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get().getStatus())
.isEqualTo(Response.Status.TOO_MANY_REQUESTS.getStatusCode());
}
@Test
void rollbackRateLimit() throws RateLimitExceededException {
doThrow(RateLimitExceededException.class).when(BYTE_RATE_LIMITER)
.validate(AuthHelper.VALID_UUID, MAX_UPLOAD_LENGTH);
assertThat(resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.queryParam("uploadLength", MAX_UPLOAD_LENGTH)
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get().getStatus())
.isEqualTo(Response.Status.TOO_MANY_REQUESTS.getStatusCode());
verify(COUNT_RATE_LIMITER).validate(AuthHelper.VALID_UUID);
verify(COUNT_RATE_LIMITER).restorePermits(AuthHelper.VALID_UUID, 1);
}
@Test
void testV4TusForm() {
AttachmentDescriptorV3 descriptor = resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.queryParam("uploadLength", MAX_UPLOAD_LENGTH)
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get(AttachmentDescriptorV3.class);
@@ -72,7 +72,7 @@ class CallRoutingControllerV2Test {
@Test
void testGetRelaysBothRouting() throws IOException {
when(cloudflareTurnCredentialsManager.retrieveFromCloudflare()).thenReturn(CLOUDFLARE_TURN_TOKEN);
when(cloudflareTurnCredentialsManager.retrieveFromCloudflare(AuthHelper.VALID_UUID)).thenReturn(CLOUDFLARE_TURN_TOKEN);
try (final Response rawResponse = resources.getJerseyTest()
.target(GET_CALL_RELAYS_PATH)
@@ -32,6 +32,7 @@ import jakarta.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.EnumSet;
import java.util.HashMap;
@@ -40,6 +41,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
@@ -255,7 +257,7 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final AccountAttributes accountAttributes = new AccountAttributes(fetchesMessages, 1234, 5678, null,
null, true, Set.of());
null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
accountAttributes,
@@ -296,7 +298,7 @@ class DeviceControllerTest {
}
@CartesianTest
void deviceDowngrade(@CartesianTest.Enum final DeviceCapability capability,
void deviceDowngrade(@CartesianTest.Enum(mode = CartesianTest.Enum.Mode.EXCLUDE, names = "SPARSE_POST_QUANTUM_RATCHET") final DeviceCapability capability,
@CartesianTest.Values(booleans = {true, false}) final boolean accountHasCapability,
@CartesianTest.Values(booleans = {true, false}) final boolean requestHasCapability)
throws LinkDeviceTokenAlreadyUsedException {
@@ -354,6 +356,55 @@ class DeviceControllerTest {
}
}
@Test
void missingRequiredCapability() throws LinkDeviceTokenAlreadyUsedException {
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
when(accountsManager.addDevice(any(), any(), any()))
.thenReturn(new Pair<>(mock(Account.class), mock(Device.class)));
final Device primaryDevice = mock(Device.class);
when(primaryDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(account.getDevices()).thenReturn(List.of(primaryDevice));
final ECSignedPreKey aciSignedPreKey;
final ECSignedPreKey pniSignedPreKey;
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
final Set<DeviceCapability> requestCapabilities = Arrays.stream(DeviceCapability.values())
.filter(capability -> !capability.requireForNewDevices())
.collect(Collectors.toSet());
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, 1234, 5678, null, null, true, requestCapabilities),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/link")
.request()
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
.put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(409, response.getStatus());
}
}
@Test
void linkDeviceAtomicBadCredentials() {
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
@@ -422,7 +473,7 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final AccountAttributes accountAttributes = new AccountAttributes(true, 1234, 5678, null,
null, true, Set.of());
null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
accountAttributes,
@@ -760,7 +811,7 @@ class DeviceControllerTest {
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture(null));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
new AccountAttributes(false, registrationId, pniRegistrationId, null, null, true, Set.of()),
new AccountAttributes(false, registrationId, pniRegistrationId, null, null, true, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES),
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.of(new ApnRegistrationId("apn")), Optional.empty()));
try (final Response response = resources.getJerseyTest()
@@ -87,7 +87,6 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@ExtendWith(DropwizardExtensionsSupport.class)
class RegistrationControllerTest {
@@ -543,11 +542,11 @@ class RegistrationControllerTest {
final AccountAttributes fetchesMessagesAccountAttributes =
new AccountAttributes(true, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION);
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
final AccountAttributes pushAccountAttributes =
new AccountAttributes(false, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION);
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
return List.of(
Arguments.argumentSet("\"Fetches messages\" is true, but an APNs token is provided",
@@ -634,7 +633,7 @@ class RegistrationControllerTest {
final AccountAttributes accountAttributes =
new AccountAttributes(true, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION);
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
return List.of(
Arguments.argumentSet("Signed PNI EC pre-key is missing",
@@ -859,7 +858,7 @@ class RegistrationControllerTest {
final int registrationId = 1;
final int pniRegistrationId = 2;
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION;
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES;
final AccountAttributes fetchesMessagesAccountAttributes =
new AccountAttributes(true, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities);
@@ -1012,7 +1011,7 @@ class RegistrationControllerTest {
final boolean skipDeviceTransfer,
final int registrationId,
final int pniRegistrationId) {
return requestToJson(request(sessionId, recoveryPassword, skipDeviceTransfer, registrationId, pniRegistrationId, DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION));
return requestToJson(request(sessionId, recoveryPassword, skipDeviceTransfer, registrationId, pniRegistrationId, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES));
}
/**
@@ -9,6 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -19,7 +20,9 @@ import com.google.common.net.HttpHeaders;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import com.google.rpc.ErrorInfo;
import com.google.rpc.Status;
import com.vdurmont.semver4j.Semver;
import io.dropwizard.auth.basic.BasicCredentials;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.StatusRuntimeException;
@@ -31,94 +34,154 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.signal.chat.rpc.EchoRequest;
import org.signal.chat.rpc.EchoServiceGrpc;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
import org.whispersystems.textsecuregcm.grpc.EchoServiceImpl;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.MockRequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.RequestAttributes;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
class RemoteDeprecationFilterTest {
@Test
void testEmptyMap() throws IOException, ServletException {
// We're happy as long as there's no exception
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
final DynamicRemoteDeprecationConfiguration emptyConfiguration = new DynamicRemoteDeprecationConfiguration();
private DynamicConfiguration dynamicConfiguration;
private RemoteDeprecationFilter remoteDeprecationFilter;
private static final UUID ACCOUNT_IDENTIFIER_WITH_SPQR = UUID.randomUUID();
private static final UUID ACCOUNT_IDENTIFIER_WITHOUT_SPQR = UUID.randomUUID();
private static final String PASSWORD = RandomStringUtils.insecure().nextAlphanumeric(16);
@BeforeEach
void setUp() {
final AccountsManager accountsManager = mock(AccountsManager.class);
when(accountsManager.getByAccountIdentifier(any())).thenReturn(Optional.empty());
final Account accountWithSpqr = buildMockAccount(true);
final Account accountWithoutSpqr = buildMockAccount(false);
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER_WITH_SPQR))
.thenReturn(Optional.of(accountWithSpqr));
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER_WITHOUT_SPQR))
.thenReturn(Optional.of(accountWithoutSpqr));
final AccountAuthenticator accountAuthenticator = mock(AccountAuthenticator.class);
when(accountAuthenticator.authenticate(any())).thenReturn(Optional.empty());
when(accountAuthenticator.authenticate(new BasicCredentials(ACCOUNT_IDENTIFIER_WITH_SPQR.toString(), PASSWORD)))
.thenReturn(Optional.of(new AuthenticatedDevice(ACCOUNT_IDENTIFIER_WITH_SPQR, Device.PRIMARY_ID, Instant.now())));
when(accountAuthenticator.authenticate(new BasicCredentials(ACCOUNT_IDENTIFIER_WITHOUT_SPQR.toString(), PASSWORD)))
.thenReturn(Optional.of(new AuthenticatedDevice(ACCOUNT_IDENTIFIER_WITHOUT_SPQR, Device.PRIMARY_ID, Instant.now())));
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(emptyConfiguration);
when(dynamicConfiguration.getRemoteDeprecationConfiguration())
.thenReturn(DynamicRemoteDeprecationConfiguration.DEFAULT);
final RemoteDeprecationFilter filter = new RemoteDeprecationFilter(dynamicConfigurationManager);
remoteDeprecationFilter =
new RemoteDeprecationFilter(accountsManager, accountAuthenticator, dynamicConfigurationManager);
}
private static Account buildMockAccount(final boolean hasSpqr) {
final Device device = mock(Device.class);
when(device.hasCapability(any())).thenReturn(false);
when(device.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(hasSpqr);
final Account account = mock(Account.class);
when(account.getDevice(anyByte())).thenReturn(Optional.empty());
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
return account;
}
@Test
void testEmptyMap() throws IOException, ServletException {
final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
final HttpServletResponse servletResponse = mock(HttpServletResponse.class);
final FilterChain filterChain = mock(FilterChain.class);
when(servletRequest.getHeader("UserAgent")).thenReturn("Signal-Android/4.68.3");
filter.doFilter(servletRequest, servletResponse, filterChain);
assertDoesNotThrow(() -> remoteDeprecationFilter.doFilter(servletRequest, servletResponse, filterChain));
verify(filterChain).doFilter(servletRequest, servletResponse);
verify(servletResponse, never()).sendError(anyInt());
}
private RemoteDeprecationFilter filterConfiguredForTest() {
final EnumMap<ClientPlatform, Semver> minimumVersionsByPlatform = new EnumMap<>(ClientPlatform.class);
minimumVersionsByPlatform.put(ClientPlatform.ANDROID, new Semver("1.0.0"));
minimumVersionsByPlatform.put(ClientPlatform.IOS, new Semver("1.0.0"));
minimumVersionsByPlatform.put(ClientPlatform.DESKTOP, new Semver("1.0.0"));
private static DynamicRemoteDeprecationConfiguration configuration() {
final EnumMap<ClientPlatform, Semver> minimumVersionsByPlatform = new EnumMap<>(Map.of(
ClientPlatform.ANDROID, new Semver("1.0.0"),
ClientPlatform.IOS, new Semver("1.0.0"),
ClientPlatform.DESKTOP, new Semver("1.0.0")
));
final EnumMap<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = new EnumMap<>(ClientPlatform.class);
minimumVersionsByPlatform.put(ClientPlatform.ANDROID, new Semver("1.1.0"));
minimumVersionsByPlatform.put(ClientPlatform.IOS, new Semver("1.1.0"));
minimumVersionsByPlatform.put(ClientPlatform.DESKTOP, new Semver("1.1.0"));
final EnumMap<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = new EnumMap<>(Map.of(
ClientPlatform.ANDROID, new Semver("1.1.0"),
ClientPlatform.IOS, new Semver("1.1.0"),
ClientPlatform.DESKTOP, new Semver("1.1.0")
));
final EnumMap<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = new EnumMap<>(ClientPlatform.class);
blockedVersionsByPlatform.put(ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.2")));
final EnumMap<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = new EnumMap<>(Map.of(
ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.2"))
));
final EnumMap<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = new EnumMap<>(ClientPlatform.class);
versionsPendingBlockByPlatform.put(ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.3")));
final EnumMap<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = new EnumMap<>(Map.of(
ClientPlatform.DESKTOP, Set.of(new Semver("8.0.0-beta.3"))
));
final DynamicRemoteDeprecationConfiguration remoteDeprecationConfiguration = new DynamicRemoteDeprecationConfiguration();
remoteDeprecationConfiguration.setMinimumVersions(minimumVersionsByPlatform);
remoteDeprecationConfiguration.setVersionsPendingDeprecation(versionsPendingDeprecationByPlatform);
remoteDeprecationConfiguration.setBlockedVersions(blockedVersionsByPlatform);
remoteDeprecationConfiguration.setVersionsPendingBlock(versionsPendingBlockByPlatform);
remoteDeprecationConfiguration.setUnrecognizedUserAgentAllowed(true);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(remoteDeprecationConfiguration);
return new RemoteDeprecationFilter(dynamicConfigurationManager);
return new DynamicRemoteDeprecationConfiguration(
minimumVersionsByPlatform,
versionsPendingDeprecationByPlatform,
blockedVersionsByPlatform,
versionsPendingBlockByPlatform,
false,
false);
}
@ParameterizedTest
@MethodSource
void testFilter(final String userAgent, final boolean expectDeprecation) throws IOException, ServletException {
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(configuration());
final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
final HttpServletResponse servletResponse = mock(HttpServletResponse.class);
final FilterChain filterChain = mock(FilterChain.class);
when(servletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(userAgent);
final RemoteDeprecationFilter filter = filterConfiguredForTest();
filter.doFilter(servletRequest, servletResponse, filterChain);
remoteDeprecationFilter.doFilter(servletRequest, servletResponse, filterChain);
if (expectDeprecation) {
verify(filterChain, never()).doFilter(any(), any());
@@ -129,16 +192,19 @@ class RemoteDeprecationFilterTest {
}
}
@SuppressWarnings("DataFlowIssue")
@ParameterizedTest
@MethodSource(value="testFilter")
void testGrpcFilter(final String userAgentString, final boolean expectDeprecation) throws IOException, InterruptedException {
when(dynamicConfiguration.getRemoteDeprecationConfiguration()).thenReturn(configuration());
final MockRequestAttributesInterceptor mockRequestAttributesInterceptor = new MockRequestAttributesInterceptor();
mockRequestAttributesInterceptor.setRequestAttributes(new RequestAttributes(InetAddresses.forString("127.0.0.1"), userAgentString, null));
final Server testServer = InProcessServerBuilder.forName("RemoteDeprecationFilterTest")
.directExecutor()
.addService(new EchoServiceImpl())
.intercept(filterConfiguredForTest())
.intercept(remoteDeprecationFilter)
.intercept(mockRequestAttributesInterceptor)
.build()
.start();
@@ -149,23 +215,26 @@ class RemoteDeprecationFilterTest {
.build();
try {
final String echoString = "Test";
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
final EchoRequest req = EchoRequest.newBuilder()
.setPayload(ByteString.copyFromUtf8(echoString))
.build();
final EchoRequest req = EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("cluck cluck, i'm a parrot")).build();
if (expectDeprecation) {
final StatusRuntimeException e = assertThrows(
StatusRuntimeException.class,
() -> client.echo(req));
final com.google.rpc.Status status = StatusProto.fromThrowable(e);
final StatusRuntimeException e = assertThrows(StatusRuntimeException.class, () -> client.echo(req));
final Status status = StatusProto.fromThrowable(e);
final ErrorInfo errorInfo = assertDoesNotThrow(() -> status.getDetailsList().stream()
.filter(any -> any.is(ErrorInfo.class)).findFirst()
.orElseThrow(() -> new AssertionError("No error info found"))
.unpack(ErrorInfo.class));
assertEquals(GrpcExceptions.DOMAIN, errorInfo.getDomain());
assertEquals(io.grpc.Status.Code.INVALID_ARGUMENT.value(), status.getCode());
assertEquals("UPGRADE_REQUIRED", errorInfo.getReason());
} else {
assertEquals("cluck cluck, i'm a parrot", client.echo(req).getPayload().toStringUtf8());
assertEquals(echoString, client.echo(req).getPayload().toStringUtf8());
}
} finally {
testServer.shutdownNow();
@@ -187,4 +256,61 @@ class RemoteDeprecationFilterTest {
Arguments.of("Signal-iOS/8.0.0-beta.2", false));
}
@ParameterizedTest
@MethodSource
void isMissingSpqrCapability(@Nullable final String authHeader, final boolean expectMissingCapability) {
assertEquals(expectMissingCapability, remoteDeprecationFilter.isMissingSpqrCapability(authHeader));
}
private static List<Arguments> isMissingSpqrCapability() {
final String password = RandomStringUtils.insecure().nextAlphanumeric(16);
AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITH_SPQR, password);
return List.of(
Arguments.argumentSet("No authentication header", null, false),
Arguments.argumentSet("Authentication header for device with SPQR",
AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITH_SPQR, PASSWORD), false),
Arguments.argumentSet("Authentication header for device without SPQR",
AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITHOUT_SPQR, PASSWORD), true)
);
}
@ParameterizedTest
@MethodSource
void shouldBlockSpqr(final boolean enforcementPending, final boolean spqrRequired, final String authHeader, final boolean expectBlock) {
when(dynamicConfiguration.getRemoteDeprecationConfiguration())
.thenReturn(new DynamicRemoteDeprecationConfiguration(
DynamicRemoteDeprecationConfiguration.DEFAULT.minimumVersions(),
DynamicRemoteDeprecationConfiguration.DEFAULT.versionsPendingDeprecation(),
DynamicRemoteDeprecationConfiguration.DEFAULT.blockedVersions(),
DynamicRemoteDeprecationConfiguration.DEFAULT.versionsPendingBlock(),
enforcementPending,
spqrRequired));
assertEquals(expectBlock, remoteDeprecationFilter.shouldBlock(null, authHeader));
}
private static List<Arguments> shouldBlockSpqr() {
return List.of(
Arguments.argumentSet("Has capability, no enforcement",
false, false, AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITH_SPQR, PASSWORD), false),
Arguments.argumentSet("Has capability, enforcement pending",
true, false, AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITH_SPQR, PASSWORD), false),
Arguments.argumentSet("Has capability, enforcement active",
false, true, AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITH_SPQR, PASSWORD), false),
Arguments.argumentSet("Missing capability, no enforcement",
false, false, AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITHOUT_SPQR, PASSWORD), false),
Arguments.argumentSet("Missing capability, enforcement pending",
true, false, AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITHOUT_SPQR, PASSWORD), false),
Arguments.argumentSet("Missing capability, enforcement active",
false, true, AuthHelper.getAuthHeader(ACCOUNT_IDENTIFIER_WITHOUT_SPQR, PASSWORD), true)
);
}
}
@@ -7,7 +7,9 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
@@ -31,11 +33,14 @@ 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.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
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.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
@@ -44,7 +49,6 @@ 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;
@@ -53,11 +57,14 @@ class AttachmentsGrpcServiceTest extends
private static final byte[] TUS_SECRET = TestRandomUtil.nextBytes(32);
private static final String TUS_URL = "https://example.com/uploads";
private static final int MAX_UPLOAD_LENGTH = 1000;
@Mock
private ExperimentEnrollmentManager experimentEnrollmentManager;
@Mock
private RateLimiter rateLimiter;
private RateLimiter countRateLimiter;
@Mock
private RateLimiter byteRateLimiter;
@Override
protected AttachmentsGrpcService createServiceBeforeEachTest() {
@@ -70,28 +77,66 @@ class AttachmentsGrpcServiceTest extends
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);
"some-cdn.signal.org", "signal@example.com", "/attach-here", gcsPrivateKeyPem);
final TusAttachmentGenerator tusAttachmentGenerator =
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL, 1000));
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL));
return new AttachmentsGrpcService(
experimentEnrollmentManager,
MockUtils.buildMock(RateLimiters.class, rateLimiters ->
when(rateLimiters.getAttachmentLimiter()).thenReturn(rateLimiter)),
MockUtils.buildMock(RateLimiters.class, rateLimiters -> {
when(rateLimiters.getAttachmentLimiter()).thenReturn(countRateLimiter);
when(rateLimiters.getAttachmentBytesLimiter()).thenReturn(byteRateLimiter);
}),
gcsAttachmentGenerator,
tusAttachmentGenerator);
tusAttachmentGenerator,
MAX_UPLOAD_LENGTH);
} catch (NoSuchAlgorithmException | IOException | InvalidKeyException | InvalidKeySpecException e) {
throw new AssertionError(e);
}
}
@ParameterizedTest
@ValueSource(longs = {-1, 0})
void invalidUploadLength(final long uploadLength) {
GrpcTestUtils.assertStatusInvalidArgument(() -> authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().setUploadLength(uploadLength).build()));
}
@Test
void uploadLengthTooBig() {
assertThat(authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().setUploadLength(MAX_UPLOAD_LENGTH + 1).build())
.hasExceedsMaxUploadLength()).isTrue();
}
@Test
void countRateLimitExceeded() throws RateLimitExceededException {
final Duration retryAfter = Duration.ofSeconds(17);
doThrow(new RateLimitExceededException(retryAfter)).when(countRateLimiter).validate(AUTHENTICATED_ACI);
GrpcTestUtils.assertRateLimitExceeded(retryAfter, () -> authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().setUploadLength(123).build()));
}
@Test
void rollbackRateLimit() throws RateLimitExceededException {
final Duration retryAfter = Duration.ofSeconds(17);
doThrow(new RateLimitExceededException(retryAfter)).when(byteRateLimiter)
.validate(AUTHENTICATED_ACI, 123);
GrpcTestUtils.assertRateLimitExceeded(retryAfter, () -> authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().setUploadLength(123).build()));
verify(countRateLimiter).validate(AUTHENTICATED_ACI);
verify(countRateLimiter).restorePermits(AUTHENTICATED_ACI, 1);
}
@Test
void getUploadFormCdn3() {
when(experimentEnrollmentManager.isEnrolled(AUTHENTICATED_ACI, AttachmentUtil.CDN3_EXPERIMENT_NAME))
.thenReturn(true);
final GetUploadFormResponse response = authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().build());
.getUploadForm(GetUploadFormRequest.newBuilder().setUploadLength(1).build());
final UploadForm uploadForm = response.getUploadForm();
assertThat(uploadForm.getCdn()).isEqualTo(3);
@@ -105,11 +150,12 @@ class AttachmentsGrpcServiceTest extends
@Test
void getUploadFormCdn2() throws MalformedURLException {
final long uploadLength = 13;
when(experimentEnrollmentManager.isEnrolled(AUTHENTICATED_ACI, AttachmentUtil.CDN3_EXPERIMENT_NAME))
.thenReturn(false);
final GetUploadFormResponse response = authenticatedServiceStub()
.getUploadForm(GetUploadFormRequest.newBuilder().build());
.getUploadForm(GetUploadFormRequest.newBuilder().setUploadLength(uploadLength).build());
final UploadForm uploadForm = response.getUploadForm();
assertThat(uploadForm.getCdn()).isEqualTo(2);
@@ -117,7 +163,7 @@ class AttachmentsGrpcServiceTest extends
assertThat(uploadForm.getHeadersMap()).containsExactlyInAnyOrderEntriesOf(Map.of(
"host", "some-cdn.signal.org",
"x-goog-resumable", "start",
"x-goog-content-length-range", "1,1000"));
"x-goog-content-length-range", "1," + uploadLength));
assertThat(uploadForm.getSignedUploadLocation()).isNotEmpty();
final URL signedUploadLocation = URI.create(uploadForm.getSignedUploadLocation()).toURL();
@@ -150,12 +196,17 @@ class AttachmentsGrpcServiceTest extends
assertThat(credentialParts[4]).isEqualTo("goog4_request");
}
@Test
void getUploadFormRateLimited() throws RateLimitExceededException {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void getUploadFormRateLimited(boolean useByteRateLimiter) throws RateLimitExceededException {
final Duration retryAfter = Duration.ofMinutes(5);
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimiter).validate(any(UUID.class));
if (useByteRateLimiter) {
doThrow(new RateLimitExceededException(retryAfter)).when(byteRateLimiter).validate(any(UUID.class), anyLong());
} else {
doThrow(new RateLimitExceededException(retryAfter)).when(countRateLimiter).validate(any(UUID.class));
}
assertRateLimitExceeded(retryAfter, () ->
authenticatedServiceStub().getUploadForm(GetUploadFormRequest.newBuilder().build()));
authenticatedServiceStub().getUploadForm(GetUploadFormRequest.newBuilder().setUploadLength(1).build()));
}
}
@@ -7,7 +7,9 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@@ -90,7 +92,7 @@ class BackupsAnonymousGrpcServiceTest extends
@Override
protected BackupsAnonymousGrpcService createServiceBeforeEachTest() {
return new BackupsAnonymousGrpcService(backupManager, new BackupMetrics());
return new BackupsAnonymousGrpcService(backupManager, new BackupMetrics(), MAX_MESSAGE_BACKUP_OBJECT_SIZE);
}
@BeforeEach
@@ -98,7 +100,6 @@ class BackupsAnonymousGrpcServiceTest extends
try {
when(backupManager.authenticateBackupUser(any(), any(), any()))
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
when(backupManager.maxMessageBackupUploadSize()).thenReturn(MAX_MESSAGE_BACKUP_OBJECT_SIZE);
} catch (BackupFailedZkAuthenticationException e) {
Assertions.fail(e);
}
@@ -110,7 +111,7 @@ class BackupsAnonymousGrpcServiceTest extends
.setPublicKey(ByteString.copyFrom(ECKeyPair.generate().getPublicKey().serialize()))
.setSignedPresentation(signedPresentation(presentation))
.build())
.getOutcomeCase()).isEqualTo(SetPublicKeyResponse.OutcomeCase.SUCCESS);
.getResponseCase()).isEqualTo(SetPublicKeyResponse.ResponseCase.SUCCESS);
}
@Test
@@ -323,55 +324,66 @@ class BackupsAnonymousGrpcServiceTest extends
}
@Test
void mediaUploadForm() throws RateLimitExceededException, BackupException {
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
void mediaUploadFormRateLimit() throws RateLimitExceededException, BackupException {
final GetUploadFormRequest request = GetUploadFormRequest.newBuilder()
.setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance())
.setSignedPresentation(signedPresentation(presentation))
.setUploadLength(100)
.build();
final GetUploadFormResponse uploadForm = unauthenticatedServiceStub().getUploadForm(request);
assertThat(uploadForm.getUploadForm().getCdn()).isEqualTo(3);
assertThat(uploadForm.getUploadForm().getKey()).isEqualTo("abc");
assertThat(uploadForm.getUploadForm().getHeadersMap()).containsExactlyEntriesOf(Map.of("k", "v"));
assertThat(uploadForm.getUploadForm().getSignedUploadLocation()).isEqualTo("example.org");
// rate limit
Duration duration = Duration.ofSeconds(10);
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
when(backupManager.createTemporaryAttachmentUploadDescriptor(any(), anyLong()))
.thenThrow(new RateLimitExceededException(duration));
GrpcTestUtils.assertRateLimitExceeded(duration, () -> unauthenticatedServiceStub().getUploadForm(request));
}
static Stream<Arguments> messagesUploadForm() {
return Stream.of(
Arguments.of(Optional.empty(), true),
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE), true),
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false)
);
}
@ParameterizedTest
@MethodSource
public void messagesUploadForm(Optional<Long> uploadLength, boolean allowedSize) throws BackupException {
when(backupManager.createMessageBackupUploadDescriptor(any()))
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
final GetUploadFormRequest.MessagesUploadType.Builder builder = GetUploadFormRequest.MessagesUploadType.newBuilder();
uploadLength.ifPresent(builder::setUploadLength);
final GetUploadFormRequest request = GetUploadFormRequest.newBuilder()
.setMessages(builder.build())
@EnumSource(value = GetUploadFormRequest.UploadTypeCase.class, names = "UPLOADTYPE_NOT_SET", mode = EnumSource.Mode.EXCLUDE)
public void uploadForm(GetUploadFormRequest.UploadTypeCase uploadType)
throws BackupException, RateLimitExceededException {
final long uploadLength = 100;
final BackupUploadDescriptor result =
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org");
final GetUploadFormRequest.Builder builder = switch (uploadType) {
case MESSAGES -> {
when(backupManager.createMessageBackupUploadDescriptor(any(), eq(uploadLength)))
.thenReturn(result);
yield GetUploadFormRequest.newBuilder().setMessages(GetUploadFormRequest.MessagesUploadType.getDefaultInstance());
}
case MEDIA -> {
when(backupManager.createTemporaryAttachmentUploadDescriptor(any(), eq(uploadLength)))
.thenReturn(result);
yield GetUploadFormRequest.newBuilder().setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance());
}
default -> throw new IllegalArgumentException("Unknown upload type: " + uploadType);
};
final GetUploadFormRequest request = builder
.setSignedPresentation(signedPresentation(presentation))
.setUploadLength(uploadLength)
.build();
final GetUploadFormResponse response = unauthenticatedServiceStub().getUploadForm(request);
if (allowedSize) {
assertThat(response.getUploadForm().getCdn()).isEqualTo(3);
assertThat(response.getUploadForm().getKey()).isEqualTo("abc");
assertThat(response.getUploadForm().getHeadersMap()).containsExactlyEntriesOf(Map.of("k", "v"));
assertThat(response.getUploadForm().getSignedUploadLocation()).isEqualTo("example.org");
} else {
assertThat(response.hasExceedsMaxUploadLength()).isTrue();
}
}
@ParameterizedTest
@EnumSource(value = GetUploadFormRequest.UploadTypeCase.class, names = "UPLOADTYPE_NOT_SET", mode = EnumSource.Mode.EXCLUDE)
public void uploadFormExceedsMax(GetUploadFormRequest.UploadTypeCase uploadType) throws BackupException {
final GetUploadFormRequest.Builder builder = switch (uploadType) {
case MESSAGES -> GetUploadFormRequest.newBuilder()
.setMessages(GetUploadFormRequest.MessagesUploadType.getDefaultInstance());
case MEDIA -> GetUploadFormRequest.newBuilder()
.setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance());
default -> throw new IllegalArgumentException("Unknown upload type: " + uploadType);
};
final GetUploadFormRequest request = builder
.setSignedPresentation(signedPresentation(presentation))
.setUploadLength(MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1)
.build();
final GetUploadFormResponse response = unauthenticatedServiceStub().getUploadForm(request);
assertThat(response.hasExceedsMaxUploadLength()).isTrue();
}
@@ -170,14 +170,14 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
public static Stream<Arguments> redeemReceipt() {
return Stream.of(
Arguments.of(null, RedeemReceiptResponse.OutcomeCase.SUCCESS),
Arguments.of(new BackupBadReceiptException("test"), RedeemReceiptResponse.OutcomeCase.INVALID_RECEIPT),
Arguments.of(new BackupMissingIdCommitmentException(), RedeemReceiptResponse.OutcomeCase.ACCOUNT_MISSING_COMMITMENT));
Arguments.of(null, RedeemReceiptResponse.ResponseCase.SUCCESS),
Arguments.of(new BackupBadReceiptException("test"), RedeemReceiptResponse.ResponseCase.INVALID_RECEIPT),
Arguments.of(new BackupMissingIdCommitmentException(), RedeemReceiptResponse.ResponseCase.ACCOUNT_MISSING_COMMITMENT));
}
@ParameterizedTest
@MethodSource
void redeemReceipt(@Nullable final BackupException exception, final RedeemReceiptResponse.OutcomeCase expectedOutcome)
void redeemReceipt(@Nullable final BackupException exception, final RedeemReceiptResponse.ResponseCase expectedOutcome)
throws InvalidInputException, VerificationFailedException, BackupInvalidArgumentException, BackupMissingIdCommitmentException, BackupBadReceiptException {
final ServerSecretParams params = ServerSecretParams.generate();
@@ -197,7 +197,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
RedeemReceiptRequest.newBuilder()
.setPresentation(ByteString.copyFrom(presentation.serialize()))
.build());
assertThat(redeemReceiptResponse.getOutcomeCase()).isEqualTo(expectedOutcome);
assertThat(redeemReceiptResponse.getResponseCase()).isEqualTo(expectedOutcome);
verify(backupAuthManager).redeemReceipt(account, presentation);
}
@@ -15,7 +15,6 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
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;
@@ -38,6 +37,7 @@ 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.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
@@ -599,28 +599,48 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
assertTrue(response.hasTargetNotFound());
}
@Test
void getPreKeysRateLimited() throws RateLimitExceededException {
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(UUID.randomUUID());
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevices()).thenReturn(Collections.emptyList());
when(targetAccount.getDevice(anyByte())).thenReturn(Optional.empty());
@CartesianTest
void getPreKeysRateLimited(
@CartesianTest.Values(booleans = {true, false}) boolean allDevices,
@CartesianTest.Values(booleans = {true, false}) boolean targetMissing) throws RateLimitExceededException {
final UUID targetAccountId = UUID.randomUUID();
final byte targetDeviceId = 1;
final int registrationId = 123;
if (!targetMissing) {
final Device mockDevice = mock(Device.class);
when(mockDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(targetAccountId);
when(targetAccount.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(ECKeyPair.generate().getPublicKey()));
when(targetAccount.getDevice(targetDeviceId)).thenReturn(Optional.of(mockDevice));
when(targetAccount.getDevices()).thenReturn(List.of(mockDevice));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAccountId)))
.thenReturn(Optional.of(targetAccount));
}
when(accountsManager.getByServiceIdentifier(any()))
.thenReturn(Optional.of(targetAccount));
final Duration retryAfterDuration = Duration.ofMinutes(7);
final String expectedRateLimitKey = AUTHENTICATED_ACI + "." +
AUTHENTICATED_DEVICE_ID + "__" +
targetAccountId + "." +
(allDevices ? "*" : targetDeviceId) + "." +
((allDevices || targetMissing) ? "*" : registrationId);
doThrow(new RateLimitExceededException(retryAfterDuration))
.when(preKeysRateLimiter).validate(anyString());
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getPreKeys(GetPreKeysRequest.newBuilder()
final GetPreKeysRequest.Builder builder = GetPreKeysRequest.newBuilder()
.setTargetIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build())
.build()));
verifyNoInteractions(accountsManager);
.setUuid(UUIDUtil.toByteString(targetAccountId)));
if (!allDevices) {
builder.setDeviceId(targetDeviceId);
}
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getPreKeys(builder.build()));
verify(preKeysRateLimiter).validate(expectedRateLimitKey);
}
}
@@ -28,10 +28,12 @@ import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -100,7 +102,8 @@ public class MetricServerInterceptorTest {
@Test
void unary() {
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
client.echo(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("hello")).build());
final EchoRequest request = EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("hello")).build();
final EchoResponse response = client.echo(request);
final Tags commonTags = Tags.of(
"platform", "android",
@@ -110,9 +113,15 @@ public class MetricServerInterceptorTest {
final Counter requestCount = find(Counter.class, MetricServerInterceptor.REQUEST_MESSAGE_COUNTER_NAME);
assertThat(requestCount.count()).isCloseTo(1.0, offset(0.01));
final Counter requestByteCount = find(Counter.class, MetricServerInterceptor.REQUEST_BYTES_COUNTER_NAME);
assertThat(requestByteCount.count()).isCloseTo(request.getSerializedSize(), offset(0.01));
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
assertThat(responseCount.count()).isCloseTo(1.0, offset(0.01));
final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME);
assertThat(responseByteCount.count()).isCloseTo(response.getSerializedSize(), offset(0.01));
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
@@ -132,20 +141,37 @@ public class MetricServerInterceptorTest {
void streaming() throws StatusException, InterruptedException {
final EchoServiceGrpc.EchoServiceBlockingV2Stub client = EchoServiceGrpc.newBlockingV2Stub(channel);
final BlockingClientCall<EchoRequest, EchoResponse> echoStream = client.echoStream();
echoStream.write(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("1")).build());
echoStream.write(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("2")).build());
echoStream.read();
echoStream.read();
final List<EchoRequest> requests = IntStream.range(0, 2)
.mapToObj(i -> EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8(String.valueOf(i))).build())
.toList();
for (final EchoRequest request : requests) {
echoStream.write(request);
}
final List<EchoResponse> responses = new ArrayList<>(requests.size());
for (int i = 0; i < requests.size(); i++) {
responses.add(echoStream.read());
}
echoStream.halfClose();
// Make sure we don't check metrics before our close is processed
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
final Counter requestCount = find(Counter.class, MetricServerInterceptor.REQUEST_MESSAGE_COUNTER_NAME);
assertThat(requestCount.count()).isCloseTo(2.0, offset(0.01));
assertThat(requestCount.count()).isCloseTo(requests.size(), offset(0.01));
final Counter requestByteCount = find(Counter.class, MetricServerInterceptor.REQUEST_BYTES_COUNTER_NAME);
assertThat(requestByteCount.count()).isCloseTo(requests.stream().mapToInt(EchoRequest::getSerializedSize).sum(), offset(0.01));
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
assertThat(responseCount.count()).isCloseTo(2.0, offset(0.01));
assertThat(responseCount.count()).isCloseTo(responses.size(), offset(0.01));
final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME);
assertThat(responseByteCount.count()).isCloseTo(responses.stream().mapToInt(EchoResponse::getSerializedSize).sum(), offset(0.01));
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
@@ -172,15 +198,15 @@ public class MetricServerInterceptorTest {
static Stream<Arguments> testUnaryOkResponseReason() {
return Stream.of(
Arguments.argumentSet("Default reason", TagResponse.newBuilder().build(), "success"),
Arguments.argumentSet("No reason", TagResponse.newBuilder().setNoReason(true).build(), "success"),
Arguments.argumentSet("Explicitly set reason", TagResponse.newBuilder().setReason1(true).build(), "reason_1"),
Arguments.argumentSet("Nested reason", TagResponse.newBuilder().setNestedReason(TagResponse.NestedReason.newBuilder().setReason(true)).build(), "nested_reason"));
Arguments.argumentSet("Default reason", TagResponse.newBuilder().build(), "SUCCESS"),
Arguments.argumentSet("No reason", TagResponse.newBuilder().setNoReason(true).build(), "SUCCESS"),
Arguments.argumentSet("Explicitly set reason", TagResponse.newBuilder().setReason1(true).build(), "REASON_1"),
Arguments.argumentSet("Nested reason", TagResponse.newBuilder().setNestedReason(TagResponse.NestedReason.newBuilder().setReason(true)).build(), "NESTED_REASON"));
}
@ParameterizedTest
@MethodSource
void testUnaryOkResponseReason(TagResponse response, String expectedReason) throws InterruptedException {
void testUnaryOkResponseReason(TagResponse response, String expectedReason) {
final TagTestServiceGrpc.TagTestServiceBlockingStub tagTestServiceBlockingStub =
TagTestServiceGrpc.newBlockingStub(channel);
when(tagResponseSupplier.get()).thenReturn(response);
@@ -203,13 +229,13 @@ public class MetricServerInterceptorTest {
// We make no promises if proto fields that have reason tags are present on a message, but this tests for the sane
// behavior that at least one of these tags makes it into the metric.
assertThat(find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME).getId().getTag("reason"))
.isIn("duplicate_reason", "reason_1");
.isIn("DUPLICATE_REASON", "REASON_1");
}
@CartesianTest
public void testStatusErrorResponseReason(
@CartesianTest.Enum(mode = CartesianTest.Enum.Mode.EXCLUDE, names = {"OK"}) Status.Code statusCode,
@CartesianTest.Values(strings = {"test", "", "null"}) String reasonParam) {
@CartesianTest.Values(strings = {"TEST", "", "null"}) String reasonParam) {
final String reason, expectedReasonTag;
if (reasonParam.equals("null")) {
@@ -76,6 +76,30 @@ class LeakyBucketRateLimiterTest {
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate(key));
}
@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 100})
void restorePermits(int permitsToAdd) throws RateLimitExceededException {
final int bucketSize = 3;
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(bucketSize, Duration.ofHours(1), false),
validateRateLimitScript,
REDIS_CLUSTER_EXTENSION.getRedisCluster(),
retryExecutor,
CLOCK);
final String key = RandomStringUtils.insecure().nextAlphanumeric(16);
for (int i = 0; i < bucketSize; i++) {
rateLimiter.validate(key);
}
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate(key));
rateLimiter.restorePermits(key, permitsToAdd);
for (int i = 0; i < Math.min(permitsToAdd, bucketSize); i++) {
assertDoesNotThrow(() -> rateLimiter.validate(key));
}
assertThrows(RateLimitExceededException.class, () -> rateLimiter.validate(key));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void validateAsync(final boolean failOpen) {
@@ -0,0 +1,107 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import reactor.core.publisher.Flux;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
class RemoveNonSpqrAccountsCommandTest {
private static class TestRemoveNonSpqrAccountsCommand extends RemoveNonSpqrAccountsCommand {
private final CommandDependencies commandDependencies;
private final Namespace namespace;
public TestRemoveNonSpqrAccountsCommand(final int maxAccounts, final boolean isDryRun) {
commandDependencies = mock(CommandDependencies.class);
when(commandDependencies.accountsManager()).thenReturn(mock(AccountsManager.class));
namespace = new Namespace(Map.of(
RemoveNonSpqrAccountsCommand.MAX_ACCOUNTS_ARGUMENT, maxAccounts,
RemoveNonSpqrAccountsCommand.DRY_RUN_ARGUMENT, isDryRun,
RemoveNonSpqrAccountsCommand.MAX_CONCURRENCY_ARGUMENT, 16));
}
@Override
protected CommandDependencies getCommandDependencies() {
return commandDependencies;
}
@Override
protected Namespace getNamespace() {
return namespace;
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void crawlAccounts(final boolean dryRun) {
final int maxAccountsToRemove = 4;
final List<Account> accounts = new ArrayList<>();
for (int i = 0; i < maxAccountsToRemove * 2; i++) {
accounts.add(buildMockAccount(true));
}
for (int i = 0; i < maxAccountsToRemove * 2; i++) {
accounts.add(buildMockAccount(false));
}
Collections.shuffle(accounts);
final RemoveNonSpqrAccountsCommand removeNonSpqrAccountsCommand =
new TestRemoveNonSpqrAccountsCommand(maxAccountsToRemove, dryRun);
removeNonSpqrAccountsCommand.crawlAccounts(Flux.fromIterable(accounts));
final AccountsManager accountsManager = removeNonSpqrAccountsCommand.getCommandDependencies().accountsManager();
if (dryRun) {
verify(accountsManager, never()).delete(any(), any());
} else {
verify(accountsManager, times(maxAccountsToRemove)).delete(
argThat(account -> !account.getPrimaryDevice().hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)),
eq(AccountsManager.DeletionReason.ADMIN_DELETED));
verifyNoMoreInteractions(accountsManager);
}
}
private static Account buildMockAccount(final boolean supportsSpqr) {
final Device primaryDevice = mock(Device.class);
when(primaryDevice.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(supportsSpqr);
final Account account = mock(Account.class);
when(account.getPrimaryDevice()).thenReturn(primaryDevice);
return account;
}
}
@@ -0,0 +1,98 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import reactor.core.publisher.Flux;
class RemoveNonSpqrLinkedDevicesCommandTest {
private static class TestRemoveNonSpqrLinkedDevicesCommand extends RemoveNonSpqrLinkedDevicesCommand {
private final CommandDependencies commandDependencies;
private final Namespace namespace;
public TestRemoveNonSpqrLinkedDevicesCommand(final boolean isDryRun) {
commandDependencies = mock(CommandDependencies.class);
when(commandDependencies.accountsManager()).thenReturn(mock(AccountsManager.class));
namespace = new Namespace(Map.of(
RemoveNonSpqrLinkedDevicesCommand.DRY_RUN_ARGUMENT, isDryRun,
RemoveNonSpqrLinkedDevicesCommand.MAX_CONCURRENCY_ARGUMENT, 16));
}
@Override
protected CommandDependencies getCommandDependencies() {
return commandDependencies;
}
@Override
protected Namespace getNamespace() {
return namespace;
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void crawlAccounts(final boolean dryRun) {
final Device primaryDeviceWithSpqr = buildMockDevice(true, true);
final Device primaryDeviceWithoutSpqr = buildMockDevice(true, false);
final Device linkedDeviceWithSpqr = buildMockDevice(false, true);
final Device linkedDeviceWithoutSpqr = buildMockDevice(false, false);
final Account accountWithNonSpqrPrimary = mock(Account.class);
when(accountWithNonSpqrPrimary.getDevices())
.thenReturn(List.of(primaryDeviceWithoutSpqr));
final Account accountWithSpqrLinkedDevice = mock(Account.class);
when(accountWithSpqrLinkedDevice.getDevices())
.thenReturn(List.of(primaryDeviceWithSpqr, linkedDeviceWithSpqr));
final Account accountWithNonSpqrLinkedDevice = mock(Account.class);
when(accountWithNonSpqrLinkedDevice.getDevices())
.thenReturn(List.of(primaryDeviceWithSpqr, linkedDeviceWithoutSpqr));
final RemoveNonSpqrLinkedDevicesCommand removeNonSpqrLinkedDevicesCommand =
new TestRemoveNonSpqrLinkedDevicesCommand(dryRun);
removeNonSpqrLinkedDevicesCommand.crawlAccounts(Flux.just(
accountWithNonSpqrPrimary, accountWithSpqrLinkedDevice, accountWithNonSpqrLinkedDevice));
final AccountsManager accountsManager =
removeNonSpqrLinkedDevicesCommand.getCommandDependencies().accountsManager();
if (dryRun) {
verifyNoInteractions(accountsManager);
} else {
verify(accountsManager).removeDevice(accountWithNonSpqrLinkedDevice, linkedDeviceWithoutSpqr.getId());
verifyNoMoreInteractions(accountsManager);
}
}
private Device buildMockDevice(final boolean isPrimary, final boolean supportsSpqr) {
final Device device = mock(Device.class);
when(device.isPrimary()).thenReturn(isPrimary);
when(device.getId()).thenReturn(isPrimary ? Device.PRIMARY_ID : Device.PRIMARY_ID + 1);
when(device.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(supportsSpqr);
return device;
}
}
+3 -2
View File
@@ -239,17 +239,18 @@ messageCache: # Redis server configuration for message store cache
cluster:
type: local
attachments:
maxUploadSizeInBytes: 1024
gcpAttachments: # GCP Storage configuration
domain: example.com
email: user@example.cocm
maxSizeInBytes: 1024
pathPrefix:
rsaSigningKey: secret://gcpAttachments.rsaSigningKey
tus:
uploadUri: https://example.org/upload
userAuthenticationTokenSharedSecret: secret://tus.userAuthenticationTokenSharedSecret
maxSizeInBytes: 1024
apn: # Apple Push Notifications configuration
sandbox: true