mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 10:36:47 +00:00
Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
971d9d64a8 | ||
|
|
cfac798f9e | ||
|
|
34e8e04793 | ||
|
|
0664c04074 | ||
|
|
e454b29c6a | ||
|
|
4a8313eb67 | ||
|
|
fa145d7889 | ||
|
|
edcc61d4ba | ||
|
|
34c7106e7e | ||
|
|
ee409af54a | ||
|
|
04c4d993a6 | ||
|
|
0ee06d83b7 | ||
|
|
f9d3cd8d82 | ||
|
|
771c98fd92 | ||
|
|
82d9107865 | ||
|
|
f2b0264fac | ||
|
|
132611f159 | ||
|
|
a741edd80f | ||
|
|
8c3dd7aa48 | ||
|
|
b0792dd0a7 | ||
|
|
d9d6560b47 | ||
|
|
8cc0948a34 | ||
|
|
575280da74 | ||
|
|
46bfc12869 | ||
|
|
73ec57e911 | ||
|
|
fb84066f09 | ||
|
|
4d24c814cc | ||
|
|
9dc807a255 | ||
|
|
5d59538924 | ||
|
|
04c102e51f | ||
|
|
71bc23ed02 | ||
|
|
7c26965ece | ||
|
|
5c3a82c257 | ||
|
|
5fedb48b55 | ||
|
|
69d9fc12ca | ||
|
|
81f2499889 | ||
|
|
82a3bba7ec | ||
|
|
ee09d6b334 | ||
|
|
dc215cab54 | ||
|
|
99bbbbe1ac | ||
|
|
38121bcbfa | ||
|
|
5e7a50a36d | ||
|
|
17531c5927 | ||
|
|
e7df1aeb5b | ||
|
|
dc8e03bd40 | ||
|
|
4578150e5a | ||
|
|
bd97e70a56 | ||
|
|
206f114b34 | ||
|
|
2dc4db3918 | ||
|
|
98dc758bb7 | ||
|
|
b4c594c657 | ||
|
|
b55afdd704 | ||
|
|
136cddf6e2 | ||
|
|
b7d455ed11 | ||
|
|
ac23b8e79e | ||
|
|
af2d276f37 | ||
|
|
8154bb1047 | ||
|
|
b647853983 | ||
|
|
3350922456 | ||
|
|
69af979bfa | ||
|
|
a142916fef | ||
|
|
9ff1431488 | ||
|
|
cf2d3369cb | ||
|
|
c41ae57871 | ||
|
|
6d351aad7b | ||
|
|
a320504fdc | ||
|
|
11df65b8d8 | ||
|
|
e96149ecf5 | ||
|
|
db66d4ef18 | ||
|
|
610782b8c3 | ||
|
|
aae1541e88 | ||
|
|
1cf3bf5ecf | ||
|
|
a90fa5db02 | ||
|
|
f5f217f3de | ||
|
|
c93aa7a9b9 |
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;
|
||||
@@ -26,6 +25,7 @@ import org.signal.libsignal.protocol.util.KeyHelper;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
|
||||
public class TestUser {
|
||||
|
||||
@@ -128,7 +128,8 @@ public class TestUser {
|
||||
}
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, Set.of())
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
|
||||
.withUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.withRecoveryPassword(registrationPassword);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -231,10 +231,12 @@ 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
|
||||
|
||||
|
||||
+11
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -142,6 +142,7 @@ import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.AttachmentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.BackupsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.BackupsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
|
||||
@@ -293,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;
|
||||
@@ -355,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",
|
||||
@@ -753,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,
|
||||
@@ -821,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());
|
||||
|
||||
@@ -946,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();
|
||||
@@ -969,7 +976,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager))
|
||||
new DevicesGrpcService(accountsManager),
|
||||
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
|
||||
gcsAttachmentGenerator, tusAttachmentGenerator, 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!
|
||||
@@ -988,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
|
||||
@@ -1072,7 +1081,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
|
||||
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
|
||||
));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
@@ -1091,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),
|
||||
@@ -1120,7 +1129,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters),
|
||||
rateLimiters, registrationFraudChecker),
|
||||
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
@@ -1150,7 +1159,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
WebSocketEnvironment<AuthenticatedDevice> provisioningEnvironment = new WebSocketEnvironment<>(environment,
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, asnInfoProviderSupplier, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
+1
-1
@@ -10,6 +10,6 @@ public interface AttachmentGenerator {
|
||||
|
||||
record Descriptor(Map<String, String> headers, String signedUploadLocation) {}
|
||||
|
||||
Descriptor generateAttachment(final String key);
|
||||
Descriptor generateAttachment(final String key, final long uploadLength);
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
public class AttachmentUtil {
|
||||
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
|
||||
|
||||
private AttachmentUtil() {}
|
||||
|
||||
public static String generateAttachmentKey(final SecureRandom secureRandom) {
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().encodeToString(bytes);
|
||||
}
|
||||
}
|
||||
+4
-5
@@ -24,16 +24,16 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
|
||||
private final CanonicalRequestSigner canonicalRequestSigner;
|
||||
|
||||
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.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));
|
||||
}
|
||||
|
||||
@@ -50,5 +50,4 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
|
||||
"x-goog-resumable", "start");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+9
-16
@@ -6,8 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
@@ -18,28 +17,22 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
|
||||
|
||||
private static final String ATTACHMENTS = "attachments";
|
||||
|
||||
final ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
final String tusUri;
|
||||
private final JwtGenerator jwtGenerator;
|
||||
private final String tusUri;
|
||||
|
||||
public TusAttachmentGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg);
|
||||
}
|
||||
|
||||
private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock, final TusConfiguration cfg) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.prependUsername(false)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Descriptor generateAttachment(final String key) {
|
||||
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(ATTACHMENTS + "/" + 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, uploadLength));
|
||||
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
final Map<String, String> headers = Map.of(
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials),
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token),
|
||||
"Upload-Metadata", String.format("filename %s", b64Key)
|
||||
);
|
||||
return new Descriptor(headers, tusUri + "/" + ATTACHMENTS);
|
||||
|
||||
+2
-2
@@ -6,10 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record TusConfiguration(
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotEmpty String uploadUri
|
||||
){}
|
||||
@NotEmpty String uploadUri){}
|
||||
+28
-6
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTCreator;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/// Generates JWT tokens for external services to validate. This class always uses symmetric HMAC-SHA256 with a shared secret
|
||||
public class JwtGenerator {
|
||||
|
||||
public static final String MAX_LENGTH_CLAIM_KEY = "maxLen";
|
||||
public static final String SCOPE_CLAIM_KEY = "scope";
|
||||
|
||||
private final Algorithm algorithm;
|
||||
private final Clock clock;
|
||||
|
||||
public JwtGenerator(final byte[] sharedSecret, final Clock clock) {
|
||||
this.algorithm = Algorithm.HMAC256(sharedSecret);
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public String generateJwt(final String audience, final String subject, Consumer<JWTCreator.Builder> claimCustomizer) {
|
||||
final Instant now = clock.instant();
|
||||
JWTCreator.Builder builder = JWT.create()
|
||||
.withAudience(audience)
|
||||
.withSubject(subject)
|
||||
.withIssuedAt(now);
|
||||
claimCustomizer.accept(builder);
|
||||
return builder.sign(algorithm);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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"));
|
||||
|
||||
+3
-4
@@ -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,
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -46,6 +45,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -60,8 +60,6 @@ import javax.annotation.Nullable;
|
||||
public class BackupManager {
|
||||
|
||||
static final String MESSAGE_BACKUP_NAME = "messageBackup";
|
||||
public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
|
||||
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
|
||||
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
|
||||
@@ -157,30 +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 byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
|
||||
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
|
||||
final String attachmentKey = AttachmentUtil.generateAttachmentKey(secureRandom);
|
||||
final AttachmentGenerator.Descriptor descriptor =
|
||||
tusAttachmentGenerator.generateAttachment(attachmentKey, uploadSize);
|
||||
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
|
||||
}
|
||||
|
||||
@@ -198,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 - BackupManager.MAX_MEDIA_OBJECT_SIZE);
|
||||
(maxTotalMediaSize - 1024 * 1024 * 100);
|
||||
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
@@ -333,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() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) {
|
||||
if (copyParameters.sourceLength() > maximumSourceObjectSize || copyParameters.sourceLength() < 0) {
|
||||
throw new BackupInvalidArgumentException("Invalid sourceObject size");
|
||||
}
|
||||
}
|
||||
|
||||
+14
-32
@@ -7,8 +7,7 @@ package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -17,47 +16,29 @@ import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
public class Cdn3BackupCredentialGenerator {
|
||||
|
||||
public static final String CDN_PATH = "backups";
|
||||
public static final int BACKUP_CDN = 3;
|
||||
|
||||
private static String READ_PERMISSION = "read";
|
||||
private static String WRITE_PERMISSION = "write";
|
||||
private static String PERMISSION_SEPARATOR = "$";
|
||||
|
||||
// Write entities will be of the form 'write$backups/<string>
|
||||
private static final String WRITE_ENTITY_PREFIX = String.format("%s%s%s/", WRITE_PERMISSION, PERMISSION_SEPARATOR,
|
||||
CDN_PATH);
|
||||
// Read entities will be of the form 'read$backups/<string>
|
||||
private static final String READ_ENTITY_PREFIX = String.format("%s%s%s/", READ_PERMISSION, PERMISSION_SEPARATOR,
|
||||
CDN_PATH);
|
||||
|
||||
private final ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
private final String tusUri;
|
||||
private final JwtGenerator jwtGenerator;
|
||||
|
||||
public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg);
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock,
|
||||
final TusConfiguration cfg) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.prependUsername(false)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}
|
||||
|
||||
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 entity = WRITE_ENTITY_PREFIX + key;
|
||||
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(entity);
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder
|
||||
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize)
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write"));
|
||||
|
||||
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
|
||||
final Map<String, String> headers = Map.of(
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials),
|
||||
HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token),
|
||||
"Upload-Metadata", String.format("filename %s", b64Key));
|
||||
|
||||
return new BackupUploadDescriptor(
|
||||
@@ -71,8 +52,9 @@ public class Cdn3BackupCredentialGenerator {
|
||||
if (hashedBackupId.isBlank()) {
|
||||
throw new IllegalArgumentException("Backup subdir name must be non-empty");
|
||||
}
|
||||
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(
|
||||
READ_ENTITY_PREFIX + hashedBackupId);
|
||||
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials));
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, builder -> builder
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "read"));
|
||||
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token));
|
||||
}
|
||||
}
|
||||
+10
@@ -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) {
|
||||
}
|
||||
-1
@@ -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")
|
||||
|
||||
+10
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
+21
-1
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@@ -19,12 +20,24 @@ public class DynamicMessagePersisterConfiguration {
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
@JsonProperty
|
||||
private Duration nodeClaimTtl = Duration.ofMinutes(5);
|
||||
|
||||
@JsonProperty
|
||||
private Duration sleepBetweenNodes = Duration.ofSeconds(5);
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled, final double trimOversizedQueueExtraRoomRatio) {
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
|
||||
final double trimOversizedQueueExtraRoomRatio,
|
||||
final Duration nodeClaimTtl,
|
||||
final Duration sleepBetweenNodes) {
|
||||
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
this.nodeClaimTtl = nodeClaimTtl;
|
||||
this.sleepBetweenNodes = sleepBetweenNodes;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
@@ -35,4 +48,11 @@ public class DynamicMessagePersisterConfiguration {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public Duration getNodeClaimTtl() {
|
||||
return nodeClaimTtl;
|
||||
}
|
||||
|
||||
public Duration getSleepBetweenNodes() {
|
||||
return sleepBetweenNodes;
|
||||
}
|
||||
}
|
||||
+30
-52
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -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;
|
||||
}
|
||||
}
|
||||
+27
-11
@@ -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.MAX_MESSAGE_BACKUP_OBJECT_SIZE)
|
||||
.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)
|
||||
|
||||
+45
-19
@@ -7,18 +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.Base64;
|
||||
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;
|
||||
@@ -36,10 +43,10 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@Tag(name = "Attachments")
|
||||
public class AttachmentControllerV4 {
|
||||
|
||||
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
|
||||
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final RateLimiter rateLimiter;
|
||||
private final RateLimiter countRateLimiter;
|
||||
private final RateLimiter bytesRateLimiter;
|
||||
private final long maxUploadLength;
|
||||
|
||||
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
|
||||
|
||||
@@ -50,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,
|
||||
@@ -68,28 +78,44 @@ 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 = "413", 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"))
|
||||
@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 String key = generateAttachmentKey();
|
||||
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), CDN3_EXPERIMENT_NAME);
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
private String generateAttachmentKey() {
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().encodeToString(bytes);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+4
@@ -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)
|
||||
|
||||
+17
-13
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+58
-7
@@ -11,6 +11,10 @@ import com.google.common.base.Preconditions;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -72,7 +76,6 @@ import org.whispersystems.textsecuregcm.entities.BaseProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
|
||||
@@ -151,6 +154,18 @@ public class ProfileController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Update profile",
|
||||
description = "Updates an account’s profile. Must be authenticated.")
|
||||
@ApiResponse(responseCode = "200", description = "The profile was updated successfully.",
|
||||
content = @Content(schema = @Schema(
|
||||
implementation = ProfileAvatarUploadAttributes.class,
|
||||
description = "If the request changed the avatar, the response body contains an upload form.")))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number.")
|
||||
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth, @NotNull @Valid CreateProfileRequest request) {
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
@@ -214,8 +229,16 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get versioned profile",
|
||||
description = "Retrieves a specific version of an account's profile. Requires either authentication or an unidentified access key.")
|
||||
@ApiResponse(responseCode = "200", description = "Profile retrieved successfully.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Malformed identifier")
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
@ManagedAsync
|
||||
public VersionedProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@@ -241,9 +264,21 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}/{credentialRequest}")
|
||||
public CredentialProfileResponse getProfile(
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get profile with credential",
|
||||
description = "Retrieves a specific version of an account's profile along with an expiring profile key credential. Requires either authentication or an unidentified access key."
|
||||
)
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Account found. Profile information will be limited and credential will be null if the version was not found",
|
||||
useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid credential type or credential request.")
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
public ExpiringProfileKeyCredentialProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@@ -276,8 +311,16 @@ public class ProfileController {
|
||||
// Although clients should generally be using versioned profiles wherever possible, there are still a few lingering
|
||||
// use cases for getting profiles without a version (e.g. getting a contact's unidentified access key checksum).
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get unversioned profile",
|
||||
description = "Retrieves basic profile information without a specific version. Supports ACI and PNI identifiers. Requires authentication, an unidentified access key, or a group send token.")
|
||||
@ApiResponse(responseCode = "200", description = "Unversioned profile retrieved successfully.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request (e.g., multiple authorization types provided).")
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
@ManagedAsync
|
||||
public BaseProfileResponse getUnversionedProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@@ -318,9 +361,17 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/identity_check/batch")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/identity_check/batch")
|
||||
@Operation(
|
||||
summary = "Batch identity key check",
|
||||
description = "Checks identity key fingerprints for multiple accounts. Returns accounts where the fingerprint does not match. Should not be authenticated.")
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Batch check completed successfully. Response may contain accounts with mismatched fingerprints.",
|
||||
content = @Content(schema = @Schema(implementation = BatchIdentityCheckResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request format or validation failed.")
|
||||
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid BatchIdentityCheckRequest request) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
|
||||
@@ -410,7 +461,7 @@ public class ProfileController {
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
|
||||
|
||||
if (maybeProfile.isEmpty()) {
|
||||
// Hypothesis: this should basically never happen since clients can't delete versions
|
||||
// this can happen if an account re-registers, which includes some device-transfer scenarios
|
||||
Metrics.counter(
|
||||
VERSION_NOT_FOUND_COUNTER_NAME,
|
||||
Tags.of(
|
||||
|
||||
@@ -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("*"));
|
||||
}
|
||||
}
|
||||
+28
-3
@@ -32,7 +32,10 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
@@ -43,6 +46,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -68,16 +72,21 @@ public class RegistrationController {
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
|
||||
|
||||
public RegistrationController(final AccountsManager accounts,
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
final RateLimiters rateLimiters,
|
||||
final RegistrationFraudChecker registrationFraudChecker) {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -100,6 +109,7 @@ public class RegistrationController {
|
||||
@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"))
|
||||
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
|
||||
public AccountCreationResponse register(
|
||||
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
|
||||
@@ -114,10 +124,17 @@ public class RegistrationController {
|
||||
throw new WebApplicationException("Invalid signature", 422);
|
||||
}
|
||||
|
||||
if (!(registrationRequest.accountAttributes().getCapabilities() != null
|
||||
? registrationRequest.accountAttributes().getCapabilities()
|
||||
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)) {
|
||||
|
||||
throw new WebApplicationException("Missing required device capability", 499);
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(
|
||||
requestContext, number, registrationRequest);
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(requestContext, number, registrationRequest);
|
||||
|
||||
final Optional<Account> existingAccount = accounts.getByE164(number);
|
||||
|
||||
@@ -160,6 +177,14 @@ public class RegistrationController {
|
||||
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
|
||||
userAgent);
|
||||
|
||||
if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) {
|
||||
try {
|
||||
registrationFraudChecker.handleVerificationCompleted(registrationRequest.sessionId(), account);
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to notify fraud checker of completed verification session", e);
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(number)),
|
||||
|
||||
@@ -40,6 +40,7 @@ public class AccountAttributes {
|
||||
private byte[] name;
|
||||
|
||||
@JsonProperty
|
||||
@ExactlySize({0, 64})
|
||||
private String registrationLock;
|
||||
|
||||
@JsonProperty
|
||||
@@ -61,6 +62,7 @@ public class AccountAttributes {
|
||||
@JsonProperty
|
||||
@Nullable
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@ExactlySize({0, 32})
|
||||
private byte[] recoveryPassword = null;
|
||||
|
||||
public AccountAttributes() {
|
||||
|
||||
+8
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
@@ -17,27 +18,34 @@ import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Schema(description = "Unversioned profile containing basic information")
|
||||
public class BaseProfileResponse {
|
||||
|
||||
@Schema(description = "The account's public identity key (unpadded base64)")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
private IdentityKey identityKey;
|
||||
|
||||
@Schema(description = "Checksum for unidentified access authentication (padded base64)")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
private byte[] unidentifiedAccess;
|
||||
|
||||
@Schema(description = "Whether unidentified access is unrestricted for this account")
|
||||
@JsonProperty
|
||||
private boolean unrestrictedUnidentifiedAccess;
|
||||
|
||||
@Schema(description = "Device capabilities and whether they are enabled")
|
||||
@JsonProperty
|
||||
private Map<String, Boolean> capabilities;
|
||||
|
||||
@Schema(description = "List of badges displayed on the profile")
|
||||
@JsonProperty
|
||||
private List<Badge> badges;
|
||||
|
||||
@Schema(description = "Service identifier (ACI or PNI)")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
|
||||
+18
-11
@@ -7,29 +7,36 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
|
||||
|
||||
public record BatchIdentityCheckRequest(@Valid @NotNull @Size(max = 1000) List<Element> elements) {
|
||||
@Schema(description = "Request to check identity key fingerprints for multiple accounts")
|
||||
public record BatchIdentityCheckRequest(
|
||||
@Schema(description = "List of accounts to check")
|
||||
@Valid @NotNull @Size(max = 1000) List<Element> elements) {
|
||||
|
||||
/**
|
||||
* @param uuid account id or phone number id
|
||||
* @param fingerprint most significant 4 bytes of SHA-256 of the 33-byte identity key field (32-byte curve25519 public
|
||||
* key prefixed with 0x05)
|
||||
*/
|
||||
public record Element(@NotNull
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
@Schema(description = "A service identifier and expected identity key fingerprint")
|
||||
public record Element(
|
||||
@Schema(description = "Identifier (ACI or PNI)")
|
||||
@NotNull
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
@NotNull
|
||||
@ExactlySize(4)
|
||||
byte[] fingerprint) {
|
||||
}
|
||||
@Schema(description = "Expected identity key fingerprint (4 bytes, most significant bytes of SHA-256 hash of 33-byte identity key field)")
|
||||
@NotNull
|
||||
@ExactlySize(4)
|
||||
byte[] fingerprint) {
|
||||
}
|
||||
}
|
||||
+18
-10
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.List;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -16,17 +17,24 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
|
||||
|
||||
public record BatchIdentityCheckResponse(@Valid List<Element> elements) {
|
||||
@Schema(description = "Response containing accounts with mismatched identity key fingerprints")
|
||||
public record BatchIdentityCheckResponse(
|
||||
@Schema(description = "List of accounts where fingerprint did not match (empty if all matched)")
|
||||
@Valid List<Element> elements) {
|
||||
|
||||
public record Element(@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
@NotNull
|
||||
ServiceIdentifier uuid,
|
||||
@Schema(description = "An account with a mismatched identity key fingerprint")
|
||||
public record Element(
|
||||
@Schema(description = "Service identifier (ACI or PNI)")
|
||||
@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
@NotNull
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
@NotNull
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
IdentityKey identityKey) {
|
||||
@Schema(description = "The actual identity key for this account")
|
||||
@NotNull
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
IdentityKey identityKey) {
|
||||
}
|
||||
}
|
||||
+12
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
@@ -17,52 +18,63 @@ import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.ValidHexString;
|
||||
|
||||
@Schema(description = "Request to create or update a versioned profile")
|
||||
public record CreateProfileRequest(
|
||||
@Schema(description = "Profile key commitment")
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@JsonDeserialize(using = ProfileKeyCommitmentAdapter.Deserializing.class)
|
||||
@JsonSerialize(using = ProfileKeyCommitmentAdapter.Serializing.class)
|
||||
ProfileKeyCommitment commitment,
|
||||
|
||||
@Schema(description = "Profile version identifier (hex-encoding of the public key)")
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
@ValidHexString
|
||||
@ExactlySize({64})
|
||||
String version,
|
||||
|
||||
@Schema(description = "Encrypted profile name. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({81, 285})
|
||||
byte[] name,
|
||||
|
||||
@Schema(description = "Encrypted about emoji. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({0, 60})
|
||||
byte[] aboutEmoji,
|
||||
|
||||
@Schema(description = "Encrypted about text. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({0, 156, 282, 540})
|
||||
byte[] about,
|
||||
|
||||
@Schema(description = "Encrypted payment address. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
@ExactlySize({0, 582})
|
||||
byte[] paymentAddress,
|
||||
|
||||
@Schema(description = "Whether the profile has an avatar")
|
||||
@JsonProperty("avatar")
|
||||
boolean hasAvatar,
|
||||
|
||||
@Schema(description = "Whether the avatar is unchanged from the previous version")
|
||||
@JsonProperty
|
||||
boolean sameAvatar,
|
||||
|
||||
@Schema(description = "List of badge IDs to display on the profile")
|
||||
@JsonProperty("badgeIds")
|
||||
Optional<List<String>> badges,
|
||||
|
||||
@Schema(description = "Encrypted phone number sharing preference. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
|
||||
public abstract class CredentialProfileResponse {
|
||||
|
||||
@JsonUnwrapped
|
||||
private VersionedProfileResponse versionedProfileResponse;
|
||||
|
||||
protected CredentialProfileResponse() {
|
||||
}
|
||||
|
||||
protected CredentialProfileResponse(final VersionedProfileResponse versionedProfileResponse) {
|
||||
this.versionedProfileResponse = versionedProfileResponse;
|
||||
}
|
||||
|
||||
public VersionedProfileResponse getVersionedProfileResponse() {
|
||||
return versionedProfileResponse;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
|
||||
|
||||
public record ECPreKey(
|
||||
@@ -16,6 +19,8 @@ public record ECPreKey(
|
||||
An arbitrary ID for this key, which will be provided by peers using this key to encrypt messages so the private key can be looked up.
|
||||
Should not be zero. Should be less than 2^24.
|
||||
""")
|
||||
@Max(KeyIdUtil.MAX_KEY_ID)
|
||||
@Min(KeyIdUtil.MIN_KEY_ID)
|
||||
long keyId,
|
||||
|
||||
@JsonSerialize(using = ECPublicKeyAdapter.Serializer.class)
|
||||
|
||||
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
|
||||
import java.util.Arrays;
|
||||
@@ -19,6 +22,8 @@ public record ECSignedPreKey(
|
||||
An arbitrary ID for this key, which will be provided by peers using this key to encrypt messages so the private key can be looked up.
|
||||
Should not be zero. Should be less than 2^24.
|
||||
""")
|
||||
@Max(KeyIdUtil.MAX_KEY_ID)
|
||||
@Min(KeyIdUtil.MIN_KEY_ID)
|
||||
long keyId,
|
||||
|
||||
@JsonSerialize(using = ECPublicKeyAdapter.Serializer.class)
|
||||
|
||||
+13
-2
@@ -6,13 +6,20 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
|
||||
public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfileResponse {
|
||||
@Schema(description = "Profile response with an expiring profile key credential")
|
||||
public class ExpiringProfileKeyCredentialProfileResponse {
|
||||
|
||||
@JsonUnwrapped
|
||||
private VersionedProfileResponse versionedProfileResponse;
|
||||
|
||||
@Schema(description = "Expiring profile key credential response. Null if profile version was not found")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ExpiringProfileKeyCredentialResponseAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ExpiringProfileKeyCredentialResponseAdapter.Deserializing.class)
|
||||
@@ -25,7 +32,7 @@ public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfi
|
||||
public ExpiringProfileKeyCredentialProfileResponse(final VersionedProfileResponse versionedProfileResponse,
|
||||
@Nullable final ExpiringProfileKeyCredentialResponse credential) {
|
||||
|
||||
super(versionedProfileResponse);
|
||||
this.versionedProfileResponse = versionedProfileResponse;
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
@@ -33,4 +40,8 @@ public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfi
|
||||
public ExpiringProfileKeyCredentialResponse getCredential() {
|
||||
return credential;
|
||||
}
|
||||
|
||||
public VersionedProfileResponse getVersionedProfileResponse() {
|
||||
return versionedProfileResponse;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,10 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.KEMPublicKeyAdapter;
|
||||
import java.util.Arrays;
|
||||
@@ -20,6 +23,8 @@ public record KEMSignedPreKey(
|
||||
Should not be zero. Should be less than 2^24. The owner of this key must be able to determine from the key ID whether this represents
|
||||
a single-use or last-resort key, but another party should *not* be able to tell.
|
||||
""")
|
||||
@Max(KeyIdUtil.MAX_KEY_ID)
|
||||
@Min(KeyIdUtil.MIN_KEY_ID)
|
||||
long keyId,
|
||||
|
||||
@JsonSerialize(using = KEMPublicKeyAdapter.Serializer.class)
|
||||
|
||||
+18
-11
@@ -6,44 +6,51 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "Profile avatar upload form (S3 Post Policy, AWS Signature version 4)")
|
||||
public class ProfileAvatarUploadAttributes {
|
||||
|
||||
@Schema(description = "Object key for the avatar")
|
||||
@JsonProperty
|
||||
private String key;
|
||||
|
||||
@Schema(description = "Credential for the upload")
|
||||
@JsonProperty
|
||||
private String credential;
|
||||
|
||||
@Schema(description = "Access control list setting")
|
||||
@JsonProperty
|
||||
private String acl;
|
||||
|
||||
@Schema(description = "Signing algorithm")
|
||||
@JsonProperty
|
||||
private String algorithm;
|
||||
|
||||
@Schema(description = "Date in AWS format")
|
||||
@JsonProperty
|
||||
private String date;
|
||||
|
||||
@Schema(description = "Base64-encoded upload policy")
|
||||
@JsonProperty
|
||||
private String policy;
|
||||
|
||||
@Schema(description = "Signature calculated over the policy")
|
||||
@JsonProperty
|
||||
private String signature;
|
||||
|
||||
public ProfileAvatarUploadAttributes() {}
|
||||
|
||||
public ProfileAvatarUploadAttributes(String key, String credential,
|
||||
String acl, String algorithm,
|
||||
String date, String policy,
|
||||
String signature)
|
||||
{
|
||||
this.key = key;
|
||||
public ProfileAvatarUploadAttributes(String key, String credential, String acl, String algorithm, String date,
|
||||
String policy, String signature) {
|
||||
|
||||
this.key = key;
|
||||
this.credential = credential;
|
||||
this.acl = acl;
|
||||
this.algorithm = algorithm;
|
||||
this.date = date;
|
||||
this.policy = policy;
|
||||
this.signature = signature;
|
||||
this.acl = acl;
|
||||
this.algorithm = algorithm;
|
||||
this.date = date;
|
||||
this.policy = policy;
|
||||
this.signature = signature;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
|
||||
+9
@@ -9,36 +9,45 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
|
||||
@Schema(description = "Versioned profile containing encrypted fields. Versioned fields may be empty if the version was not found.")
|
||||
public record VersionedProfileResponse(
|
||||
|
||||
@Schema(description = "Base profile information")
|
||||
@JsonUnwrapped
|
||||
BaseProfileResponse baseProfileResponse,
|
||||
|
||||
@Schema(description = "Encrypted profile name. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] name,
|
||||
|
||||
@Schema(description = "Encrypted about text. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] about,
|
||||
|
||||
@Schema(description = "Encrypted about emoji. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] aboutEmoji,
|
||||
|
||||
@Schema(description = "Avatar CDN path")
|
||||
@JsonProperty
|
||||
String avatar,
|
||||
|
||||
@Schema(description = "Encrypted payment address. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] paymentAddress,
|
||||
|
||||
@Schema(description = "Encrypted phone number sharing preference. Padded base64.")
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
|
||||
+64
-18
@@ -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;
|
||||
}
|
||||
}
|
||||
+4
-7
@@ -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) {
|
||||
|
||||
-7
@@ -15,7 +15,6 @@ import org.signal.chat.account.LookupUsernameLinkRequest;
|
||||
import org.signal.chat.account.LookupUsernameLinkResponse;
|
||||
import org.signal.chat.account.SimpleAccountsAnonymousGrpc;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -52,12 +51,6 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
|
||||
public LookupUsernameHashResponse lookupUsernameHash(final LookupUsernameHashRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
|
||||
throw GrpcExceptions.fieldViolation("username_hash",
|
||||
String.format("Illegal username hash length; expected %d bytes, but got %d bytes",
|
||||
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()));
|
||||
}
|
||||
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getUsernameLookupLimiter());
|
||||
|
||||
return accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray()).join()
|
||||
|
||||
@@ -45,7 +45,6 @@ import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
@@ -103,10 +102,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public SetRegistrationLockResponse setRegistrationLock(final SetRegistrationLockRequest request) {
|
||||
if (request.getRegistrationLock().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("registration_lock", "Registration lock secret must not be empty");
|
||||
}
|
||||
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
final SaltedTokenHash credentials =
|
||||
@@ -131,16 +126,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getUsernameHashesCount() == 0) {
|
||||
throw GrpcExceptions.fieldViolation("username_hashes", "List of username hashes must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameHashesCount() > AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH) {
|
||||
throw GrpcExceptions.fieldViolation("username_hashes",
|
||||
String.format("List of username hashes may have at most %d elements, but actually had %d",
|
||||
AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH, request.getUsernameHashesCount()));
|
||||
}
|
||||
|
||||
final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount());
|
||||
|
||||
for (final ByteString usernameHash : request.getUsernameHashesList()) {
|
||||
@@ -175,30 +160,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getUsernameHash().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("username_hash", "Username hash must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
|
||||
throw GrpcExceptions.fieldViolation("username_hash",
|
||||
String.format("Username hash length must be %d bytes, but was actually %d",
|
||||
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()));
|
||||
}
|
||||
|
||||
if (request.getZkProof().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("zk_proof", "Zero-knowledge proof must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameCiphertext().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("username_ciphertext", "Username ciphertext must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameCiphertext().size() > AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH) {
|
||||
throw GrpcExceptions.fieldViolation("username_ciphertext",
|
||||
String.format("Username ciphertext length must at most %d bytes, but was actually %d",
|
||||
AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH, request.getUsernameCiphertext().size()));
|
||||
}
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
|
||||
} catch (final BaseUsernameException e) {
|
||||
@@ -242,11 +203,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getUsernameCiphertext().isEmpty() || request.getUsernameCiphertext().size() > EncryptedUsername.MAX_SIZE) {
|
||||
throw GrpcExceptions.fieldViolation("username_ciphertext",
|
||||
String.format("Username ciphertext must not be empty and must be shorter than %d bytes", EncryptedUsername.MAX_SIZE));
|
||||
}
|
||||
|
||||
rateLimiters.getUsernameLinkOperationLimiter().validate(authenticatedDevice.accountIdentifier());
|
||||
|
||||
final Account account = getAuthenticatedAccount();
|
||||
@@ -304,10 +260,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
|
||||
if (request.getRegistrationRecoveryPassword().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("registration_recovery_password", "Registration recovery password must not be empty");
|
||||
}
|
||||
|
||||
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
|
||||
request.getRegistrationRecoveryPassword().toByteArray())
|
||||
.join();
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Map;
|
||||
import org.signal.chat.attachments.GetUploadFormRequest;
|
||||
import org.signal.chat.attachments.GetUploadFormResponse;
|
||||
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
|
||||
import org.signal.chat.common.UploadForm;
|
||||
import org.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;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
|
||||
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
|
||||
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final RateLimiter countRateLimiter;
|
||||
private final RateLimiter bytesRateLimiter;
|
||||
private final long maxUploadLength;
|
||||
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
|
||||
private final SecureRandom secureRandom;
|
||||
|
||||
public AttachmentsGrpcService(
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator,
|
||||
final TusAttachmentGenerator tusAttachmentGenerator,
|
||||
final long maxUploadLength) {
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
|
||||
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
|
||||
this.maxUploadLength = maxUploadLength;
|
||||
this.secureRandom = new SecureRandom();
|
||||
this.attachmentGenerators = Map.of(
|
||||
2, gcsAttachmentGenerator,
|
||||
3, tusAttachmentGenerator);
|
||||
}
|
||||
|
||||
@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();
|
||||
|
||||
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, request.getUploadLength());
|
||||
return GetUploadFormResponse.newBuilder().setUploadForm(UploadForm.newBuilder()
|
||||
.setCdn(cdn)
|
||||
.setKey(key)
|
||||
.putAllHeaders(descriptor.headers())
|
||||
.setSignedUploadLocation(descriptor.signedUploadLocation()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+24
-27
@@ -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.MAX_MESSAGE_BACKUP_OBJECT_SIZE;
|
||||
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()
|
||||
|
||||
-3
@@ -53,9 +53,6 @@ public class ExternalServiceCredentialsAnonymousGrpcService extends
|
||||
@Override
|
||||
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
|
||||
final List<String> tokens = request.getPasswordsList();
|
||||
if (tokens.size() > 10) {
|
||||
throw GrpcExceptions.fieldViolation("passwordsList", "At most 10 passwords may be provided");
|
||||
}
|
||||
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
|
||||
tokens,
|
||||
svrCredentialsGenerator,
|
||||
|
||||
+11
-1
@@ -13,6 +13,7 @@ import java.util.Arrays;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.keys.AccountPreKeyBundles;
|
||||
import org.signal.chat.keys.CheckIdentityKeyRequest;
|
||||
import org.signal.chat.keys.CheckIdentityKeyResponse;
|
||||
import org.signal.chat.keys.GetPreKeysAnonymousRequest;
|
||||
@@ -22,6 +23,7 @@ import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
@@ -74,7 +76,15 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build());
|
||||
|
||||
default -> throw GrpcExceptions.fieldViolation("authorization", "invalid authorization type");
|
||||
case UNRESTRICTED_ACCESS -> accountsManager.getByServiceIdentifier(serviceIdentifier)
|
||||
.filter(Account::isUnrestrictedUnidentifiedAccess)
|
||||
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, serviceIdentifier, deviceId, keysManager))
|
||||
.map(accountPreKeyBundles -> GetPreKeysAnonymousResponse.newBuilder().setPreKeys(accountPreKeyBundles).build())
|
||||
.orElseGet(() -> GetPreKeysAnonymousResponse.newBuilder()
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build());
|
||||
|
||||
case AUTHORIZATION_NOT_SET -> throw GrpcExceptions.fieldViolation("authorization", "invalid authorization type");
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.signal.chat.keys.DevicePreKeyBundle;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
|
||||
class KeysGrpcHelper {
|
||||
@@ -67,19 +68,20 @@ class KeysGrpcHelper {
|
||||
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
|
||||
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
|
||||
|
||||
|
||||
final DevicePreKeyBundle.Builder builder = DevicePreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.ecSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature())))
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
|
||||
.setRegistrationId(device.getRegistrationId(targetServiceIdentifier.identityType()));
|
||||
|
||||
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecPreKey.keyId())
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))));
|
||||
|
||||
preKeyBundlesBuilder.putDevicePreKeys(deviceId, builder.build());
|
||||
|
||||
@@ -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)
|
||||
@@ -119,10 +131,6 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
|
||||
@Override
|
||||
public SetPreKeyResponse setOneTimeEcPreKeys(final SetOneTimeEcPreKeysRequest request) {
|
||||
if (request.getPreKeysList().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("pre_keys", "pre_keys must be non-empty");
|
||||
}
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
@@ -136,10 +144,6 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
|
||||
@Override
|
||||
public SetPreKeyResponse setOneTimeKemSignedPreKeys(final SetOneTimeKemSignedPreKeysRequest request) {
|
||||
if (request.getPreKeysList().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("pre_keys", "pre_keys must be non-empty");
|
||||
}
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
|
||||
+12
-8
@@ -102,6 +102,8 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
}
|
||||
case GROUP_SEND_TOKEN ->
|
||||
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), destinationServiceIdentifier);
|
||||
case UNRESTRICTED_ACCESS ->
|
||||
maybeDestination.map(account -> account.isUnrestrictedUnidentifiedAccess()).orElse(false);
|
||||
case AUTHORIZATION_NOT_SET ->
|
||||
throw GrpcExceptions.fieldViolation("authorization", "expected authorization token not provided");
|
||||
};
|
||||
@@ -293,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();
|
||||
|
||||
|
||||
+23
-3
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,37 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public record RequestAttributes(InetAddress remoteAddress,
|
||||
@Nullable String userAgent,
|
||||
@Nullable String acceptLanguageRaw,
|
||||
List<Locale.LanguageRange> acceptLanguage) {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RequestAttributes.class);
|
||||
|
||||
public RequestAttributes(InetAddress remoteAddress,
|
||||
@Nullable String userAgent,
|
||||
@Nullable String acceptLanguageRaw) {
|
||||
this(remoteAddress, userAgent, acceptLanguageRaw, parseAcceptLanguage(acceptLanguageRaw, userAgent));
|
||||
}
|
||||
|
||||
private static List<Locale.LanguageRange> parseAcceptLanguage(final String acceptLanguageRaw, final String userAgent) {
|
||||
List<Locale.LanguageRange> acceptLanguages = Collections.emptyList();
|
||||
if (StringUtils.isNotBlank(acceptLanguageRaw)) {
|
||||
try {
|
||||
acceptLanguages = Locale.LanguageRange.parse(acceptLanguageRaw);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
LOGGER.debug("Invalid Accept-Language header from User-Agent {}: {}", userAgent, acceptLanguageRaw, e);
|
||||
}
|
||||
}
|
||||
return acceptLanguages;
|
||||
}
|
||||
}
|
||||
+1
-10
@@ -70,17 +70,8 @@ public class RequestAttributesInterceptor implements ServerInterceptor {
|
||||
return ServerInterceptorUtil.closeWithStatus(call, Status.UNAVAILABLE);
|
||||
}
|
||||
|
||||
@Nullable List<Locale.LanguageRange> acceptLanguages = Collections.emptyList();
|
||||
if (StringUtils.isNotBlank(acceptLanguageHeader)) {
|
||||
try {
|
||||
acceptLanguages = Locale.LanguageRange.parse(acceptLanguageHeader);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
log.debug("Invalid Accept-Language header from User-Agent {}: {}", userAgentHeader, acceptLanguageHeader, e);
|
||||
}
|
||||
}
|
||||
|
||||
final RequestAttributes requestAttributes =
|
||||
new RequestAttributes(remoteAddress.get(), userAgentHeader, acceptLanguages);
|
||||
new RequestAttributes(remoteAddress.get(), userAgentHeader, acceptLanguageHeader);
|
||||
return Contexts.interceptCall(
|
||||
Context.current().withValue(RequestAttributesUtil.REQUEST_ATTRIBUTES_CONTEXT_KEY, requestAttributes),
|
||||
call, headers, next);
|
||||
|
||||
+10
@@ -1,6 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Context;
|
||||
import javax.annotation.Nullable;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -22,6 +23,15 @@ public class RequestAttributesUtil {
|
||||
return REQUEST_ATTRIBUTES_CONTEXT_KEY.get().acceptLanguage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw "Accept-Language" header string from the remote client in the current gRPC request context
|
||||
*
|
||||
* @return the raw "Accept-Language" header listed by the remote client; may be null if not specified
|
||||
*/
|
||||
public static @Nullable String getAcceptLanguageRaw() {
|
||||
return REQUEST_ATTRIBUTES_CONTEXT_KEY.get().acceptLanguageRaw();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of distinct locales supported by the JVM and accepted by the remote client in the current gRPC
|
||||
* context. May be empty if the client did not supply a list of acceptable languages, if the list of acceptable
|
||||
|
||||
+4
-1
@@ -19,8 +19,11 @@ public class ServiceIdentifierUtil {
|
||||
}
|
||||
|
||||
public static ServiceIdentifier fromGrpcServiceIdentifier(final org.signal.chat.common.ServiceIdentifier serviceIdentifier) {
|
||||
final UUID uuid;
|
||||
if (serviceIdentifier == null) {
|
||||
throw GrpcExceptions.invalidArguments("invalid service identifier");
|
||||
}
|
||||
|
||||
final UUID uuid;
|
||||
try {
|
||||
uuid = UUIDUtil.fromByteString(serviceIdentifier.getUuid());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
|
||||
@@ -94,6 +94,12 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
|
||||
final String extensionName = extensionFieldDescriptor.getFullName();
|
||||
|
||||
// If this is a oneof, but this field isn't set, we shouldn't validate it. We assume if you have a validator
|
||||
// that requires presence, you don't actually want presence enforcement on a oneof case.
|
||||
if (fd.getRealContainingOneof() != null && !msg.hasField(fd)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// first validate the field
|
||||
final FieldValidator validator = fieldValidators.get(extensionName);
|
||||
// not all extensions are validators, so `validator` value here could legitimately be `null`
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+26
@@ -2,14 +2,19 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfo;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
@@ -18,11 +23,13 @@ import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
public class OpenWebSocketCounter {
|
||||
|
||||
private final Supplier<AsnInfoProvider> asnInfoProviderSupplier;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private final Tags baseTags;
|
||||
|
||||
private final Map<Tags, AtomicInteger> openWebsocketsByTags;
|
||||
private final Map<String, AtomicInteger> openWebsocketsByAsnRegion = new ConcurrentHashMap<>();
|
||||
private final AtomicInteger totalConnections;
|
||||
|
||||
private static final int MAX_COUNTERS = 4096;
|
||||
@@ -33,10 +40,13 @@ public class OpenWebSocketCounter {
|
||||
private static final String WEB_SOCKET_CLOSED_COUNTER_NAME = name(OpenWebSocketCounter.class, "websocketClosed");
|
||||
private static final String SESSION_DURATION_TIMER_NAME = name(OpenWebSocketCounter.class, "sessionDuration");
|
||||
private static final String GAUGE_COUNT_GAUGE_NAME = name(OpenWebSocketCounter.class, "gaugeCount");
|
||||
private static final String OPEN_WEBSOCKET_BY_ASN_REGION_GAUGE_NAME = name(OpenWebSocketCounter.class, "openWebsocketsByAsnRegion");
|
||||
|
||||
public OpenWebSocketCounter(final String webSocketType,
|
||||
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
|
||||
this.asnInfoProviderSupplier = asnInfoProviderSupplier;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.baseTags = Tags.of("webSocketType", webSocketType);
|
||||
@@ -48,6 +58,21 @@ public class OpenWebSocketCounter {
|
||||
public void countOpenWebSocket(final WebSocketSessionContext context) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final Optional<AtomicInteger> maybeOpenWebSocketsByAsnRegion;
|
||||
|
||||
if (context.getClient().getRemoteAddress() instanceof InetSocketAddress inetSocketAddress) {
|
||||
maybeOpenWebSocketsByAsnRegion =
|
||||
asnInfoProviderSupplier.get().lookup(InetAddresses.toAddrString(inetSocketAddress.getAddress()))
|
||||
.map(AsnInfo::regionCode)
|
||||
.map(asnRegion -> openWebsocketsByAsnRegion.computeIfAbsent(asnRegion, region ->
|
||||
Metrics.gauge(OPEN_WEBSOCKET_BY_ASN_REGION_GAUGE_NAME, Tags.of("asnRegion", region),
|
||||
new AtomicInteger(0))));
|
||||
} else {
|
||||
maybeOpenWebSocketsByAsnRegion = Optional.empty();
|
||||
}
|
||||
|
||||
maybeOpenWebSocketsByAsnRegion.ifPresent(AtomicInteger::incrementAndGet);
|
||||
|
||||
@Nullable final UserAgent userAgent;
|
||||
{
|
||||
UserAgent parsedUserAgent;
|
||||
@@ -85,6 +110,7 @@ public class OpenWebSocketCounter {
|
||||
.register(Metrics.globalRegistry));
|
||||
|
||||
maybeOpenWebSocketCounter.ifPresent(AtomicInteger::decrementAndGet);
|
||||
maybeOpenWebSocketsByAsnRegion.ifPresent(AtomicInteger::decrementAndGet);
|
||||
totalConnections.decrementAndGet();
|
||||
|
||||
Metrics.counter(WEB_SOCKET_CLOSED_COUNTER_NAME, tagsWithClientPlatform.and("status", String.valueOf(statusCode)))
|
||||
|
||||
+13
@@ -8,6 +8,7 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public interface RegistrationFraudChecker {
|
||||
|
||||
@@ -47,6 +48,14 @@ public interface RegistrationFraudChecker {
|
||||
final VerificationSession verificationSession,
|
||||
final String e164);
|
||||
|
||||
/**
|
||||
* Handles a completed verification session resulting in a registration.
|
||||
*
|
||||
* @param verificationSessionId The ID of the verification session that resulted in a completed registration
|
||||
* @param createdAccount The account created at the end of the verification session
|
||||
*/
|
||||
void handleVerificationCompleted(final String verificationSessionId, final Account createdAccount);
|
||||
|
||||
static RegistrationFraudChecker noop() {
|
||||
return new RegistrationFraudChecker() {
|
||||
|
||||
@@ -64,6 +73,10 @@ public interface RegistrationFraudChecker {
|
||||
|
||||
return VerificationCheck.DEFAULT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleVerificationCompleted(final String verificationSessionId, final Account createdAccount) {
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static org.whispersystems.textsecuregcm.util.Util.getAlternateForms;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
@@ -371,7 +372,28 @@ public class Accounts {
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, accountToCreate).transactItem());
|
||||
|
||||
// Phone number canonicalization means that a user can use a different phone number in the same equivalence class
|
||||
// to reclaim the account.
|
||||
if (!existingAccount.getNumber().equals(accountToCreate.getNumber())) {
|
||||
if (getAlternateForms(existingAccount.getNumber()).contains(accountToCreate.getNumber())) {
|
||||
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getUuid());
|
||||
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreate.getNumber());
|
||||
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
|
||||
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
|
||||
|
||||
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccount.getNumber()));
|
||||
writeItems.add(phoneNumberConstraintPut);
|
||||
} else {
|
||||
log.error("Reclaiming account with a non-equivalent phone number. Old account {}:{}:{}, new account {}:{}:{}",
|
||||
existingAccount.getUuid(), existingAccount.getNumber(), existingAccount.getPhoneNumberIdentifier(),
|
||||
accountToCreate.getUuid(), accountToCreate.getNumber(), accountToCreate.getPhoneNumberIdentifier());
|
||||
throw new IllegalArgumentException("reclaimed accounts must have equivalent phone numbers");
|
||||
}
|
||||
}
|
||||
|
||||
final int updateAccountItemIndex = writeItems.size();
|
||||
writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumber()).transactItem());
|
||||
writeItems.addAll(additionalWriteItems);
|
||||
|
||||
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
|
||||
@@ -382,6 +404,16 @@ public class Accounts {
|
||||
.exceptionally(throwable -> {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
|
||||
if (unwrapped instanceof TransactionCanceledException te) {
|
||||
if (Accounts.conditionalCheckFailed(te.cancellationReasons().get(updateAccountItemIndex))) {
|
||||
final Map<String, AttributeValue> item = te.cancellationReasons().get(updateAccountItemIndex).item();
|
||||
final String existingNumber = AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null);
|
||||
if (!existingAccount.getNumber().equals(existingNumber)) {
|
||||
log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}",
|
||||
existingAccount.getUuid(), existingAccount.getNumber(), existingNumber);
|
||||
throw new UnexpectedExistingPhoneNumberException();
|
||||
}
|
||||
}
|
||||
|
||||
if (te.cancellationReasons().stream().anyMatch(Accounts::conditionalCheckFailed)) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
@@ -889,6 +921,37 @@ public class Accounts {
|
||||
}
|
||||
}
|
||||
|
||||
record UpdateExpression (List<String> setClauses, List<String> addClauses, List<String> removeClauses) {
|
||||
public String toExpressionString() {
|
||||
final StringBuilder updateExpressionBuilder = new StringBuilder();
|
||||
|
||||
if (!setClauses.isEmpty()) {
|
||||
updateExpressionBuilder.append("SET ");
|
||||
updateExpressionBuilder.append(String.join(", ", setClauses));
|
||||
}
|
||||
|
||||
if (!removeClauses.isEmpty()) {
|
||||
if (!updateExpressionBuilder.isEmpty()) {
|
||||
updateExpressionBuilder.append(" ");
|
||||
}
|
||||
|
||||
updateExpressionBuilder.append("REMOVE ");
|
||||
updateExpressionBuilder.append(String.join(", ", removeClauses));
|
||||
}
|
||||
|
||||
if (!addClauses.isEmpty()) {
|
||||
if (!updateExpressionBuilder.isEmpty()) {
|
||||
updateExpressionBuilder.append(" ");
|
||||
}
|
||||
|
||||
updateExpressionBuilder.append("ADD ");
|
||||
updateExpressionBuilder.append(String.join(", ", addClauses));
|
||||
}
|
||||
|
||||
return updateExpressionBuilder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A ddb update that can be used as part of a transaction or single-item update statement.
|
||||
*/
|
||||
@@ -897,13 +960,13 @@ public class Accounts {
|
||||
Map<String, AttributeValue> key,
|
||||
Map<String, String> attrNames,
|
||||
Map<String, AttributeValue> attrValues,
|
||||
String updateExpression,
|
||||
UpdateExpression updateExpression,
|
||||
String conditionExpression) {
|
||||
UpdateItemRequest updateItemRequest() {
|
||||
return UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(key)
|
||||
.updateExpression(updateExpression)
|
||||
.updateExpression(updateExpression.toExpressionString())
|
||||
.conditionExpression(conditionExpression)
|
||||
.expressionAttributeNames(attrNames)
|
||||
.expressionAttributeValues(attrValues)
|
||||
@@ -914,17 +977,46 @@ public class Accounts {
|
||||
return TransactWriteItem.builder().update(Update.builder()
|
||||
.tableName(tableName)
|
||||
.key(key)
|
||||
.updateExpression(updateExpression)
|
||||
.updateExpression(updateExpression.toExpressionString())
|
||||
.conditionExpression(conditionExpression)
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.expressionAttributeNames(attrNames)
|
||||
.expressionAttributeValues(attrValues)
|
||||
.build()).build();
|
||||
}
|
||||
|
||||
static UpdateAccountSpec forReclaimedAccount(
|
||||
final String accountTableName,
|
||||
final Account account,
|
||||
final String expectedExistingE164) {
|
||||
final UpdateAccountSpec base = forAccount(accountTableName, account);
|
||||
|
||||
final Map<String, AttributeValue> attrValues = new HashMap<>(base.attrValues());
|
||||
attrValues.put(":number", AttributeValues.fromString(account.getNumber()));
|
||||
|
||||
final UpdateExpression updateExpression = base.updateExpression();
|
||||
final List<String> setClauses = new ArrayList<>(updateExpression.setClauses());
|
||||
setClauses.add("#number = :number");
|
||||
|
||||
final MembershipExpression membershipExpression = MembershipExpression.build(getAlternateForms(expectedExistingE164));
|
||||
attrValues.putAll(membershipExpression.values());
|
||||
|
||||
// Defensive check: we should only update the e164 to another e164 in the same equivalence class
|
||||
final String conditionExpression = base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression());
|
||||
|
||||
return new UpdateAccountSpec(
|
||||
base.tableName(),
|
||||
base.key(),
|
||||
base.attrNames(),
|
||||
attrValues,
|
||||
new UpdateExpression(setClauses, updateExpression.addClauses(), updateExpression.removeClauses()),
|
||||
conditionExpression
|
||||
);
|
||||
}
|
||||
|
||||
static UpdateAccountSpec forAccount(
|
||||
final String accountTableName,
|
||||
final Account account) {
|
||||
// username, e164, and pni cannot be modified through this method
|
||||
final Map<String, String> attrNames = new HashMap<>(Map.of(
|
||||
"#number", ATTR_ACCOUNT_E164,
|
||||
"#data", ATTR_ACCOUNT_DATA,
|
||||
@@ -937,19 +1029,20 @@ public class Accounts {
|
||||
":version", AttributeValues.fromInt(account.getVersion()),
|
||||
":version_increment", AttributeValues.fromInt(1)));
|
||||
|
||||
final StringBuilder updateExpressionBuilder = new StringBuilder("SET #data = :data, #cds = :cds");
|
||||
final List<String> setClauses = new ArrayList<>(List.of("#data = :data", "#cds = :cds"));
|
||||
|
||||
if (account.getUnidentifiedAccessKey().isPresent()) {
|
||||
// if it's present in the account, also set the uak
|
||||
attrNames.put("#uak", ATTR_UAK);
|
||||
attrValues.put(":uak", AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
|
||||
updateExpressionBuilder.append(", #uak = :uak");
|
||||
setClauses.add("#uak = :uak");
|
||||
}
|
||||
|
||||
if (account.getUsernameHash().isPresent()) {
|
||||
// if it's present in the account, also set the username hash
|
||||
attrNames.put("#usernameHash", ATTR_USERNAME_HASH);
|
||||
attrValues.put(":usernameHash", AttributeValues.fromByteArray(account.getUsernameHash().get()));
|
||||
updateExpressionBuilder.append(", #usernameHash = :usernameHash");
|
||||
setClauses.add("#usernameHash = :usernameHash");
|
||||
}
|
||||
|
||||
// If the account has a username/handle pair, we should add it to the top level attributes.
|
||||
@@ -959,7 +1052,7 @@ public class Accounts {
|
||||
if (account.getEncryptedUsername().isPresent() && account.getUsernameLinkHandle() != null) {
|
||||
attrNames.put("#ul", ATTR_USERNAME_LINK_UUID);
|
||||
attrValues.put(":ul", AttributeValues.fromUUID(account.getUsernameLinkHandle()));
|
||||
updateExpressionBuilder.append(", #ul = :ul");
|
||||
setClauses.add("#ul = :ul");
|
||||
}
|
||||
|
||||
// Some operations may remove the usernameLink or the usernameHash (re-registration, clear username link, and
|
||||
@@ -974,17 +1067,20 @@ public class Accounts {
|
||||
attrNames.put("#username_hash", ATTR_USERNAME_HASH);
|
||||
removes.add("#username_hash");
|
||||
}
|
||||
|
||||
final List<String> removeClauses = new ArrayList<>();
|
||||
if (!removes.isEmpty()) {
|
||||
updateExpressionBuilder.append(" REMOVE %s".formatted(String.join(",", removes)));
|
||||
removeClauses.add(String.join(",", removes));
|
||||
}
|
||||
updateExpressionBuilder.append(" ADD #version :version_increment");
|
||||
|
||||
final List<String> addClauses = List.of("#version :version_increment");
|
||||
|
||||
return new UpdateAccountSpec(
|
||||
accountTableName,
|
||||
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())),
|
||||
attrNames,
|
||||
attrValues,
|
||||
updateExpressionBuilder.toString(),
|
||||
new UpdateExpression(setClauses, addClauses, removeClauses),
|
||||
"attribute_exists(#number) AND #version = :version");
|
||||
}
|
||||
}
|
||||
@@ -1584,4 +1680,26 @@ public class Accounts {
|
||||
: phoneNumber.substring(phoneNumber.length() - 2));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
record MembershipExpression(String expression, Map<String, AttributeValue> values) {
|
||||
public static MembershipExpression build(final Collection<String> values) {
|
||||
if (values.isEmpty()) {
|
||||
throw new IllegalArgumentException("must have at least one value");
|
||||
}
|
||||
|
||||
final Map<String, AttributeValue> expressionValues = new HashMap<>();
|
||||
final List<String> placeholders = new ArrayList<>();
|
||||
final String prefix = "val";
|
||||
int i = 0;
|
||||
for (final String value : values) {
|
||||
String key = ":" + prefix + i;
|
||||
placeholders.add(key);
|
||||
expressionValues.put(key, AttributeValues.fromString(value));
|
||||
i++;
|
||||
}
|
||||
|
||||
final String expression = "(" + String.join(", ", placeholders) + ")";
|
||||
return new MembershipExpression(expression, expressionValues);
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
-7
@@ -5,13 +5,17 @@
|
||||
|
||||
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;
|
||||
|
||||
public enum DeviceCapability {
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, false, true);
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true);
|
||||
|
||||
public enum AccountCapabilityMode {
|
||||
/**
|
||||
@@ -33,10 +37,16 @@ public enum DeviceCapability {
|
||||
ALWAYS_CAPABLE,
|
||||
}
|
||||
|
||||
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 requireForNewDevices;
|
||||
|
||||
/**
|
||||
* Create a DeviceCapability
|
||||
@@ -46,19 +56,22 @@ public enum DeviceCapability {
|
||||
* 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
|
||||
* 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
|
||||
* 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 includeInProfile,
|
||||
final boolean requireForNewDevices) {
|
||||
|
||||
this.name = name;
|
||||
this.accountCapabilityMode = accountCapabilityMode;
|
||||
this.preventDowngrade = preventDowngrade;
|
||||
this.includeInProfile = includeInProfile;
|
||||
this.requireForNewDevices = requireForNewDevices;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
@@ -77,6 +90,10 @@ public enum DeviceCapability {
|
||||
return includeInProfile;
|
||||
}
|
||||
|
||||
public boolean requireForNewDevices() {
|
||||
return requireForNewDevices;
|
||||
}
|
||||
|
||||
public static Optional<DeviceCapability> forName(final String name) {
|
||||
for (final DeviceCapability capability : DeviceCapability.values()) {
|
||||
if (capability.getName().equals(name)) {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class KeyIdUtil {
|
||||
public static final long MAX_KEY_ID = (1L << 32) - 1;
|
||||
public static final long MIN_KEY_ID = 0;
|
||||
private KeyIdUtil(){}
|
||||
|
||||
public static boolean keyIdValid(final long keyId) {
|
||||
return keyId <= MAX_KEY_ID && keyId >= MIN_KEY_ID;
|
||||
}
|
||||
|
||||
/// Convert a long keyId (a 32-bit unsigned int) into an int representation.
|
||||
///
|
||||
/// The inverse of [Integer#toUnsignedLong].
|
||||
///
|
||||
/// @param keyId A key ID which must be in the range [0, 2^32)
|
||||
/// @throws IllegalArgumentException If `keyId` is not within the range
|
||||
/// @return A 32-bit unsigned integer where the top bit is stored in the sign bit
|
||||
public static int toUnsignedInt(final long keyId) {
|
||||
if (!keyIdValid(keyId)) {
|
||||
throw new IllegalArgumentException("Invalid keyId " + keyId);
|
||||
}
|
||||
return (int) keyId;
|
||||
}
|
||||
}
|
||||
+273
-183
@@ -9,19 +9,22 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.LongTaskTimer;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -32,7 +35,10 @@ import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
import reactor.util.retry.RetryBackoffSpec;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
|
||||
|
||||
public class MessagePersister implements Managed {
|
||||
@@ -41,153 +47,228 @@ public class MessagePersister implements Managed {
|
||||
private final MessagesManager messagesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Scheduler persistQueueScheduler;
|
||||
private final Clock clock;
|
||||
|
||||
private final Duration persistDelay;
|
||||
private final int maxConcurrency;
|
||||
private final int scanCount;
|
||||
|
||||
private final RetryBackoffSpec retryBackoffSpec;
|
||||
|
||||
private final String persisterId = UUID.randomUUID().toString();
|
||||
|
||||
private final Thread[] workerThreads;
|
||||
private volatile boolean running;
|
||||
|
||||
@Nullable
|
||||
private Thread workerThread;
|
||||
|
||||
private static final String INSPECTED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "inspectedQueue");
|
||||
|
||||
private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized");
|
||||
private static final String PERSISTED_MESSAGE_COUNTER_NAME = name(MessagePersister.class, "persistMessage");
|
||||
private static final String PERSISTED_BYTES_COUNTER_NAME = name(MessagePersister.class, "persistBytes");
|
||||
|
||||
private static final Timer GET_QUEUES_TIMER = Metrics.timer(name(MessagePersister.class, "getQueues"));
|
||||
private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue"));
|
||||
private static final Counter PERSIST_QUEUE_EXCEPTION_METER =
|
||||
Metrics.counter(name(MessagePersister.class, "persistQueueException"));
|
||||
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
|
||||
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
|
||||
|
||||
private static final Counter PERSIST_NODE_COUNTER = Metrics.counter(name(MessagePersister.class, "persistNodeCount"));
|
||||
private static final LongTaskTimer PERSIST_NODE_TIMER = Metrics.more().longTaskTimer(name(MessagePersister.class, "persistNode"));
|
||||
|
||||
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
|
||||
|
||||
static final int QUEUE_BATCH_LIMIT = 100;
|
||||
static final int MESSAGE_BATCH_LIMIT = 100;
|
||||
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
|
||||
name(MessagePersister.class, "queueCount"))
|
||||
.register(Metrics.globalRegistry);
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY =
|
||||
DistributionSummary.builder(name(MessagePersister.class, "queueCount"))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
|
||||
|
||||
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
|
||||
|
||||
public MessagePersister(final MessagesCache messagesCache,
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Scheduler persistQueueScheduler,
|
||||
final Clock clock,
|
||||
final Duration persistDelay,
|
||||
final int dedicatedProcessWorkerThreadCount) {
|
||||
final int maxConcurrency,
|
||||
final int scanCount) {
|
||||
|
||||
this(messagesCache,
|
||||
messagesManager,
|
||||
accountsManager,
|
||||
dynamicConfigurationManager,
|
||||
persistQueueScheduler,
|
||||
clock,
|
||||
persistDelay,
|
||||
maxConcurrency,
|
||||
scanCount,
|
||||
Retry.backoff(3, Duration.ofSeconds(1)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessagePersister(final MessagesCache messagesCache,
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Scheduler persistQueueScheduler,
|
||||
final Clock clock,
|
||||
final Duration persistDelay,
|
||||
final int maxConcurrency,
|
||||
final int scanCount,
|
||||
final RetryBackoffSpec retryBackoffSpec) {
|
||||
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.clock = clock;
|
||||
this.persistDelay = persistDelay;
|
||||
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
|
||||
|
||||
for (int i = 0; i < workerThreads.length; i++) {
|
||||
workerThreads[i] = new Thread(() -> {
|
||||
while (running) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
|
||||
.isPersistenceEnabled()) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextQueues(Instant.now());
|
||||
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
|
||||
|
||||
if (queuesPersisted == 0) {
|
||||
Util.sleep(100);
|
||||
}
|
||||
} catch (final Throwable t) {
|
||||
logger.warn("Failed to persist queues", t);
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
} else {
|
||||
Util.sleep(1000);
|
||||
}
|
||||
}
|
||||
}, "MessagePersisterWorker-" + i);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Duration getPersistDelay() {
|
||||
return persistDelay;
|
||||
this.maxConcurrency = maxConcurrency;
|
||||
this.scanCount = scanCount;
|
||||
this.retryBackoffSpec = retryBackoffSpec;
|
||||
this.persistQueueScheduler = persistQueueScheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
public synchronized void start() {
|
||||
running = true;
|
||||
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
workerThread.start();
|
||||
}
|
||||
workerThread = new Thread(() -> {
|
||||
while (running) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().isPersistenceEnabled()) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextNode();
|
||||
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
|
||||
|
||||
if (queuesPersisted == 0) {
|
||||
Util.sleep(100);
|
||||
}
|
||||
} catch (final Throwable t) {
|
||||
logger.warn("Failed to persist queues", t);
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Persisters work through nodes quickly, and running in a hot loop taxes Redis nodes unnecessarily
|
||||
Thread.sleep(dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getSleepBetweenNodes());
|
||||
} catch (final InterruptedException _) {
|
||||
}
|
||||
}
|
||||
}, "MessagePersister");
|
||||
|
||||
workerThread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
if (workerThread != null) {
|
||||
try {
|
||||
workerThread.join();
|
||||
} catch (final InterruptedException e) {
|
||||
logger.warn("Interrupted while waiting for worker thread to complete current operation");
|
||||
}
|
||||
|
||||
workerThread = null;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int persistNextQueues(final Instant currentTime) {
|
||||
final int slot = messagesCache.getNextSlotToPersist();
|
||||
final String shard = messagesCache.shardForSlot(slot);
|
||||
int persistNextNode() {
|
||||
final RedisClusterNode node;
|
||||
{
|
||||
final Duration nodeClaimTtl =
|
||||
dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getNodeClaimTtl();
|
||||
|
||||
List<String> queuesToPersist;
|
||||
int queuesPersisted = 0;
|
||||
final Optional<RedisClusterNode> maybeNode = messagesCache.claimNextNodeToPersist(persisterId, nodeClaimTtl);
|
||||
|
||||
do {
|
||||
queuesToPersist = GET_QUEUES_TIMER.record(
|
||||
() -> messagesCache.getQueuesToPersist(slot, currentTime.minus(persistDelay), QUEUE_BATCH_LIMIT));
|
||||
|
||||
for (final String queue : queuesToPersist) {
|
||||
final UUID accountUuid = MessagesCache.getAccountUuidFromQueueName(queue);
|
||||
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queue);
|
||||
|
||||
final Optional<Account> maybeAccount = accountsManager.getByAccountIdentifier(accountUuid);
|
||||
if (maybeAccount.isEmpty()) {
|
||||
logger.error("No account record found for account {}", accountUuid);
|
||||
continue;
|
||||
}
|
||||
final Optional<Device> maybeDevice = maybeAccount.flatMap(account -> account.getDevice(deviceId));
|
||||
if (maybeDevice.isEmpty()) {
|
||||
logger.error("Account {} does not have a device with id {}", accountUuid, deviceId);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
persistQueue(maybeAccount.get(), maybeDevice.get(), shard);
|
||||
} catch (final Exception e) {
|
||||
PERSIST_QUEUE_EXCEPTION_METER.increment();
|
||||
logger.warn("Failed to persist queue {}::{} (slot {}, shard {}); will schedule for retry",
|
||||
accountUuid, deviceId, slot, shard, e);
|
||||
|
||||
messagesCache.addQueueToPersist(accountUuid, deviceId);
|
||||
|
||||
if (!(e instanceof MessagePersistenceException)) {
|
||||
// Pause after unexpected exceptions
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
}
|
||||
if (maybeNode.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
queuesPersisted += queuesToPersist.size();
|
||||
} while (queuesToPersist.size() >= QUEUE_BATCH_LIMIT);
|
||||
node = maybeNode.get();
|
||||
}
|
||||
|
||||
return queuesPersisted;
|
||||
try {
|
||||
return persistNode(node);
|
||||
} finally {
|
||||
messagesCache.releaseNodeClaim(node, persisterId);
|
||||
}
|
||||
}
|
||||
|
||||
int persistNode(final RedisClusterNode node) {
|
||||
final LongTaskTimer.Sample sample = PERSIST_NODE_TIMER.start();
|
||||
|
||||
try {
|
||||
final Tags tags = Tags.of("node", node.getUri().getHost());
|
||||
|
||||
return messagesCache.getQueues(node, scanCount)
|
||||
.filter(_ -> dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
|
||||
.isPersistenceEnabled())
|
||||
.flatMap(queueKey -> Mono.defer(() -> shouldPersistQueue(queueKey))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to determine whether queue {} should be persisted", queueKey, e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.mapNotNull(shouldPersist -> shouldPersist ? queueKey : null)
|
||||
.doOnTerminate(() -> Metrics.counter(INSPECTED_QUEUE_COUNTER_NAME, tags).increment()), maxConcurrency)
|
||||
.distinct()
|
||||
.flatMap(queueKey -> {
|
||||
final UUID accountIdentifier = MessagesCache.getAccountUuidFromQueueName(queueKey);
|
||||
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queueKey);
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(accountIdentifier))
|
||||
.map(maybeAccount -> maybeAccount
|
||||
.flatMap(account -> account.getDevice(deviceId))
|
||||
.map(device -> Tuples.of(maybeAccount.get(), device)))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to fetch account/device for queue: {}", queueKey, e);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.flatMap(accountAndDevice -> {
|
||||
final Account account = accountAndDevice.getT1();
|
||||
final Device device = accountAndDevice.getT2();
|
||||
|
||||
return persistQueue(account, device, tags)
|
||||
.thenReturn(1)
|
||||
.retryWhen(retryBackoffSpec
|
||||
// Don't retry with backoff for persistence exceptions
|
||||
.filter(e -> !(e instanceof MessagePersistenceException)))
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to persist queue {}::{} ({}); will schedule for retry",
|
||||
account.getIdentifier(IdentityType.ACI), device.getId(), node.getUri().getHost(), e);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Unhandled error while persisting messages", e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.count()
|
||||
.blockOptional()
|
||||
.map(Math::toIntExact)
|
||||
.orElse(0);
|
||||
} finally {
|
||||
sample.stop();
|
||||
PERSIST_NODE_COUNTER.increment();
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void persistQueue(final Account account, final Device device, final String shard) throws MessagePersistenceException {
|
||||
Mono<Void> persistQueue(final Account account, final Device device, final Tags baseTags) {
|
||||
final UUID accountUuid = account.getUuid();
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
@@ -196,119 +277,128 @@ public class MessagePersister implements Managed {
|
||||
.orElse("unknown"));
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final Tags tags = baseTags.and(platformTag);
|
||||
|
||||
messagesCache.lockQueueForPersistence(accountUuid, deviceId);
|
||||
return Flux.usingWhen(
|
||||
messagesCache.lockQueueForPersistence(accountUuid, deviceId)
|
||||
.thenReturn(true),
|
||||
_ -> Flux.from(messagesCache.getMessagesToPersist(accountUuid, deviceId))
|
||||
.buffer(MESSAGE_BATCH_LIMIT)
|
||||
.flatMap(messages -> {
|
||||
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
|
||||
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
|
||||
|
||||
try {
|
||||
int messageCount = 0;
|
||||
List<MessageProtos.Envelope> messages;
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
|
||||
Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags)
|
||||
.increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum());
|
||||
|
||||
int consecutiveEmptyCacheRemovals = 0;
|
||||
return Mono.fromRunnable(() -> messagesManager.persistMessages(accountUuid, device, messages))
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.thenReturn(messages.size());
|
||||
}, 1)
|
||||
.reduce(0, Integer::sum)
|
||||
.onErrorResume(ItemCollectionSizeLimitExceededException.class, _ -> {
|
||||
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
|
||||
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
|
||||
// may throw, in which case we'll retry later by the usual mechanism
|
||||
if (isPrimary) {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
|
||||
account.getUuid(), deviceId);
|
||||
|
||||
do {
|
||||
messages = messagesCache.getMessagesToPersist(accountUuid, deviceId, MESSAGE_BATCH_LIMIT);
|
||||
return trimQueue(account, device)
|
||||
.then(Mono.error(new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed")));
|
||||
} else {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
|
||||
|
||||
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
|
||||
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
|
||||
|
||||
final Tags tags = Tags.of(platformTag, Tag.of("shard", shard));
|
||||
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
|
||||
Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags)
|
||||
.increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum());
|
||||
|
||||
int messagesRemovedFromCache = messagesManager.persistMessages(accountUuid, device, messages);
|
||||
messageCount += messages.size();
|
||||
|
||||
if (messagesRemovedFromCache == 0) {
|
||||
consecutiveEmptyCacheRemovals += 1;
|
||||
} else {
|
||||
consecutiveEmptyCacheRemovals = 0;
|
||||
}
|
||||
|
||||
if (consecutiveEmptyCacheRemovals > CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT) {
|
||||
throw new MessagePersistenceException("persistence failure loop detected");
|
||||
}
|
||||
|
||||
} while (!messages.isEmpty());
|
||||
|
||||
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
|
||||
.tags(Tags.of(platformTag))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(messageCount);
|
||||
} catch (ItemCollectionSizeLimitExceededException e) {
|
||||
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
|
||||
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
|
||||
// may throw, in which case we'll retry later by the usual mechanism
|
||||
if (isPrimary) {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
|
||||
account.getUuid(), deviceId);
|
||||
trimQueue(account, deviceId);
|
||||
throw new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed");
|
||||
} else {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
|
||||
accountsManager.removeDevice(account, deviceId);
|
||||
}
|
||||
} finally {
|
||||
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
|
||||
sample.stop(PERSIST_QUEUE_TIMER);
|
||||
}
|
||||
return Mono.fromRunnable(() -> accountsManager.removeDevice(account, deviceId))
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.then(Mono.empty());
|
||||
}
|
||||
})
|
||||
.doOnSuccess(messagesPersisted -> {
|
||||
if (messagesPersisted != null) {
|
||||
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
|
||||
.tags(Tags.of(platformTag))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(messagesPersisted);
|
||||
}
|
||||
})
|
||||
.doOnTerminate(() -> sample.stop(PERSIST_QUEUE_TIMER)),
|
||||
_ -> messagesCache.unlockQueueForPersistence(accountUuid, deviceId))
|
||||
.then();
|
||||
}
|
||||
|
||||
private void trimQueue(final Account account, byte deviceId) {
|
||||
private Mono<Void> trimQueue(final Account account, final Device device) {
|
||||
final UUID aci = account.getIdentifier(IdentityType.ACI);
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
final Optional<Device> maybeDevice = account.getDevice(deviceId);
|
||||
if (maybeDevice.isEmpty()) {
|
||||
logger.warn("Not deleting messages for overfull queue {}::{}, deviceId {} does not exist",
|
||||
aci, deviceId, deviceId);
|
||||
return;
|
||||
}
|
||||
final Device device = maybeDevice.get();
|
||||
|
||||
// Calculate how many bytes we should trim
|
||||
final long cachedMessageBytes = messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId).join();
|
||||
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
|
||||
.getMessagePersisterConfiguration()
|
||||
.getTrimOversizedQueueExtraRoomRatio();
|
||||
final long targetDeleteBytes = Math.round(cachedMessageBytes * extraRoomRatio);
|
||||
|
||||
final AtomicLong oldestMessage = new AtomicLong(0L);
|
||||
final AtomicLong newestMessage = new AtomicLong(0L);
|
||||
final AtomicLong bytesDeleted = new AtomicLong(0L);
|
||||
|
||||
// Iterate from the oldest message until we've removed targetDeleteBytes
|
||||
final Pair<Long, Long> outcomes = Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
|
||||
.concatMap(envelope -> {
|
||||
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes) {
|
||||
return Mono.just(Optional.<MessageProtos.Envelope>empty());
|
||||
}
|
||||
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
|
||||
newestMessage.set(envelope.getServerTimestamp());
|
||||
return Mono.just(Optional.of(envelope));
|
||||
})
|
||||
.takeWhile(Optional::isPresent)
|
||||
.flatMap(maybeEnvelope -> {
|
||||
final MessageProtos.Envelope envelope = maybeEnvelope.get();
|
||||
TRIMMED_MESSAGE_COUNTER.increment();
|
||||
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
|
||||
return Mono
|
||||
.fromCompletionStage(() -> messagesManager
|
||||
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.retryWhen(Retry.backoff(5, Duration.ofSeconds(1)))
|
||||
.map(Optional::isPresent);
|
||||
})
|
||||
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
|
||||
? Pair.of(acc.getLeft() + 1, acc.getRight())
|
||||
: Pair.of(acc.getLeft(), acc.getRight() + 1))
|
||||
.block();
|
||||
final AtomicLong cachedMessageBytes = new AtomicLong(0L);
|
||||
final AtomicLong targetDeleteBytes = new AtomicLong(0L);
|
||||
|
||||
logger.warn(
|
||||
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
|
||||
aci, deviceId,
|
||||
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
|
||||
targetDeleteBytes, cachedMessageBytes,
|
||||
outcomes.getLeft(), outcomes.getRight());
|
||||
return Mono.fromFuture(() -> messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId))
|
||||
.flatMap(estimatedPersistedQueueSize -> {
|
||||
cachedMessageBytes.set(estimatedPersistedQueueSize);
|
||||
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
|
||||
|
||||
return Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
|
||||
.concatMap(envelope -> {
|
||||
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
|
||||
return Mono.just(Optional.<MessageProtos.Envelope>empty());
|
||||
}
|
||||
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
|
||||
newestMessage.set(envelope.getServerTimestamp());
|
||||
return Mono.just(Optional.of(envelope));
|
||||
})
|
||||
.takeWhile(Optional::isPresent)
|
||||
.flatMap(maybeEnvelope -> {
|
||||
// We know this must be present because we `takeWhile` values are present
|
||||
final MessageProtos.Envelope envelope = maybeEnvelope.orElseThrow(AssertionError::new);
|
||||
TRIMMED_MESSAGE_COUNTER.increment();
|
||||
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
|
||||
return Mono
|
||||
.fromCompletionStage(() -> messagesManager
|
||||
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.map(Optional::isPresent);
|
||||
})
|
||||
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
|
||||
? Pair.of(acc.getLeft() + 1, acc.getRight())
|
||||
: Pair.of(acc.getLeft(), acc.getRight() + 1));
|
||||
})
|
||||
.doOnSuccess(outcomes -> {
|
||||
if (outcomes != null) {
|
||||
logger.warn(
|
||||
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
|
||||
aci, deviceId,
|
||||
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
|
||||
targetDeleteBytes, cachedMessageBytes,
|
||||
outcomes.getLeft(), outcomes.getRight());
|
||||
}
|
||||
})
|
||||
.then();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Mono<Boolean> shouldPersistQueue(final String queueKey) {
|
||||
return messagesCache.getEarliestUndeliveredTimestamp(
|
||||
MessagesCache.getAccountUuidFromQueueName(queueKey),
|
||||
MessagesCache.getDeviceIdFromQueueName(queueKey))
|
||||
.map(oldestMessageTimestamp ->
|
||||
Duration.between(Instant.ofEpochMilli(oldestMessageTimestamp), clock.instant()).compareTo(persistDelay) > 0)
|
||||
.switchIfEmpty(Mono.just(false));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String getPersisterId() {
|
||||
return persisterId;
|
||||
}
|
||||
}
|
||||
+106
-92
@@ -13,9 +13,12 @@ import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.github.resilience4j.reactor.retry.RetryOperator;
|
||||
import io.lettuce.core.Limit;
|
||||
import io.lettuce.core.Range;
|
||||
import io.lettuce.core.ScanArgs;
|
||||
import io.lettuce.core.ScanStream;
|
||||
import io.lettuce.core.ScoredValue;
|
||||
import io.lettuce.core.ZAddArgs;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -38,6 +41,7 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
@@ -48,9 +52,8 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -85,9 +88,6 @@ import reactor.core.scheduler.Schedulers;
|
||||
* <dt>{@code queueLockKey}</dt>
|
||||
* <dd>Used to indicate that a queue is being modified by the {@link MessagePersister} and that {@code get_items} should
|
||||
* return an empty list.</dd>
|
||||
* <dt>{@code queueTotalIndexKey}</dt>
|
||||
* <dd>A sorted set of all queues in a shard. A queue’s score is the timestamp of its oldest message, which is used by
|
||||
* the {@link MessagePersister} to prioritize queues to persist.</dd>
|
||||
* </dl>
|
||||
* <p>
|
||||
* At a high level, the process is:
|
||||
@@ -127,15 +127,15 @@ public class MessagesCache {
|
||||
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
|
||||
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
|
||||
private final MessagesCacheGetItemsScript getItemsScript;
|
||||
private final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript;
|
||||
private final MessagesCacheRemoveQueueScript removeQueueScript;
|
||||
private final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript;
|
||||
private final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript;
|
||||
private final MessagesCacheUnlockQueueScript unlockQueueScript;
|
||||
|
||||
private int nextNodeRotateDistance = 0;
|
||||
|
||||
private final Timer insertTimer = Metrics.timer(name(MessagesCache.class, "insert"));
|
||||
private final Timer insertSharedMrmPayloadTimer = Metrics.timer(name(MessagesCache.class, "insertSharedMrmPayload"));
|
||||
private final Timer getMessagesTimer = Metrics.timer(name(MessagesCache.class, "get"));
|
||||
private final Timer getQueuesToPersistTimer = Metrics.timer(name(MessagesCache.class, "getQueuesToPersist"));
|
||||
private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid"));
|
||||
private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView"));
|
||||
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
|
||||
@@ -154,7 +154,6 @@ public class MessagesCache {
|
||||
|
||||
static final String RETRY_NAME = ResilienceUtil.name(MessagesCache.class);
|
||||
|
||||
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
|
||||
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -164,7 +163,9 @@ public class MessagesCache {
|
||||
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
|
||||
|
||||
private static final String GET_FLUX_NAME = MetricsUtil.name(MessagesCache.class, "get");
|
||||
private static final int PAGE_SIZE = 100;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int PAGE_SIZE = 100;
|
||||
|
||||
private static final int REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY = 8;
|
||||
|
||||
@@ -187,9 +188,9 @@ public class MessagesCache {
|
||||
new MessagesCacheInsertScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheGetItemsScript(redisCluster),
|
||||
new MessagesCacheReleaseNodeClaimScript(redisCluster),
|
||||
new MessagesCacheRemoveByGuidScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheRemoveQueueScript(redisCluster),
|
||||
new MessagesCacheGetQueuesToPersistScript(redisCluster),
|
||||
new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster),
|
||||
new MessagesCacheUnlockQueueScript(redisCluster)
|
||||
);
|
||||
@@ -202,9 +203,10 @@ public class MessagesCache {
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript,
|
||||
final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript,
|
||||
final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheRemoveQueueScript removeQueueScript,
|
||||
final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript,
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript,
|
||||
final MessagesCacheUnlockQueueScript unlockQueueScript) throws IOException {
|
||||
|
||||
@@ -220,8 +222,8 @@ public class MessagesCache {
|
||||
this.insertMrmScript = insertMrmScript;
|
||||
this.removeByGuidScript = removeByGuidScript;
|
||||
this.getItemsScript = getItemsScript;
|
||||
this.releaseNodeClaimScript = releaseNodeClaimScript;
|
||||
this.removeQueueScript = removeQueueScript;
|
||||
this.getQueuesToPersistScript = getQueuesToPersistScript;
|
||||
this.removeRecipientViewFromMrmDataScript = removeRecipientViewFromMrmDataScript;
|
||||
this.unlockQueueScript = unlockQueueScript;
|
||||
}
|
||||
@@ -307,13 +309,30 @@ public class MessagesCache {
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDevice) {
|
||||
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDeviceId) {
|
||||
return get(destinationUuid,
|
||||
destinationDeviceId,
|
||||
clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY),
|
||||
false);
|
||||
}
|
||||
|
||||
final long earliestAllowableEphemeralTimestamp =
|
||||
clock.millis() - MAX_EPHEMERAL_MESSAGE_DELAY.toMillis();
|
||||
Publisher<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDeviceId) {
|
||||
return Flux.from(get(accountUuid,
|
||||
destinationDeviceId,
|
||||
// Discard all ephemeral messages when persisting
|
||||
Instant.ofEpochMilli(Long.MAX_VALUE),
|
||||
true));
|
||||
}
|
||||
|
||||
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDevice,
|
||||
earliestAllowableEphemeralTimestamp, PAGE_SIZE)
|
||||
private Publisher<MessageProtos.Envelope> get(final UUID destinationUuid,
|
||||
final byte destinationDeviceId,
|
||||
final Instant earliestAllowableEphemeralTimestamp,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final long earliestAllowableEphemeralTimestampMillis = earliestAllowableEphemeralTimestamp.toEpochMilli();
|
||||
|
||||
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDeviceId,
|
||||
earliestAllowableEphemeralTimestampMillis, PAGE_SIZE, bypassLock)
|
||||
.publish()
|
||||
// We expect exactly three subscribers to this base flux:
|
||||
// 1. the websocket that delivers messages to clients
|
||||
@@ -325,25 +344,41 @@ public class MessagesCache {
|
||||
|
||||
final Flux<MessageProtos.Envelope> messagesToPublish = allMessages
|
||||
.filter(Predicate.not(envelope ->
|
||||
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp) || isStaleMrmMessage(envelope)));
|
||||
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis) || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleEphemeralMessages = allMessages
|
||||
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestamp));
|
||||
discardStaleMessages(destinationUuid, destinationDevice, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis));
|
||||
discardStaleMessages(destinationUuid, destinationDeviceId, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
|
||||
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
|
||||
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
|
||||
discardStaleMessages(destinationUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
discardStaleMessages(destinationUuid, destinationDeviceId, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
|
||||
return messagesToPublish.name(GET_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public Mono<Long> getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return getAllMessages(destinationUuid, destinationDevice, -1, 1)
|
||||
/// Returns the server-issued timestamp of the earliest message in the queue for the given account/device, regardless
|
||||
/// of the type of message. Note that this method may return a timestamp for a message that would ultimately be
|
||||
/// discarded were a caller to actually fetch messages (i.e. an expired ephemeral message).
|
||||
///
|
||||
/// @param destinationUuid the account identifier for the queue for which to get a timestamp
|
||||
/// @param destinationDeviceId the device identifier for the queue for which to get a timestamp
|
||||
///
|
||||
/// @return a `Mono` that publishes the timestamp (in milliseconds since the epoch) of the earliest message in the
|
||||
/// given queue or yields no value if the queue is empty or does not exist
|
||||
public Mono<Long> getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDeviceId) {
|
||||
return redisCluster.withBinaryCluster(connection ->
|
||||
connection.reactive().zrange(getMessageQueueKey(destinationUuid, destinationDeviceId), 0, 0))
|
||||
.next()
|
||||
.map(MessageProtos.Envelope::getServerTimestamp);
|
||||
.flatMap(serializedEnvelope -> {
|
||||
try {
|
||||
return Mono.just(parseEnvelope(serializedEnvelope).getServerTimestamp());
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
return Mono.error(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
|
||||
@@ -373,18 +408,21 @@ public class MessagesCache {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid, final byte destinationDevice,
|
||||
final long earliestAllowableEphemeralTimestamp, final int pageSize) {
|
||||
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final long earliestAllowableEphemeralTimestamp,
|
||||
final int pageSize,
|
||||
final boolean bypassLock) {
|
||||
|
||||
// fetch messages by page
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize)
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize, bypassLock)
|
||||
.expand(queueItemsAndLastMessageId -> {
|
||||
// expand() is breadth-first, so each page will be published in order
|
||||
if (queueItemsAndLastMessageId.first().isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize);
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize, bypassLock);
|
||||
})
|
||||
.limitRate(1)
|
||||
// we want to ensure we don’t accidentally block the Lettuce/netty i/o executors
|
||||
@@ -529,10 +567,13 @@ public class MessagesCache {
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid, final byte destinationDevice,
|
||||
long messageId, int pageSize) {
|
||||
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final long messageId,
|
||||
final int pageSize,
|
||||
final boolean bypassLock) {
|
||||
|
||||
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId)
|
||||
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId, bypassLock)
|
||||
.map(queueItems -> {
|
||||
logger.trace("Processing page: {}", messageId);
|
||||
|
||||
@@ -583,35 +624,6 @@ public class MessagesCache {
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
|
||||
final int limit) {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
|
||||
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
|
||||
|
||||
final Flux<MessageProtos.Envelope> allMessages = parseAndFetchMrms(Flux.fromIterable(messages), destinationDevice);
|
||||
|
||||
final Flux<MessageProtos.Envelope> messagesToPersist = allMessages
|
||||
.filter(Predicate.not(envelope ->
|
||||
envelope.getEphemeral() || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> ephemeralMessages = allMessages
|
||||
.filter(MessageProtos.Envelope::getEphemeral);
|
||||
discardStaleMessages(accountUuid, destinationDevice, ephemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
|
||||
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
|
||||
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
|
||||
discardStaleMessages(accountUuid, destinationDevice, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
|
||||
return messagesToPersist
|
||||
.collectList()
|
||||
.doOnTerminate(() -> sample.stop(getMessagesTimer))
|
||||
.block(Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
private Flux<MessageProtos.Envelope> parseAndFetchMrms(final Flux<byte[]> serializedMessages, final byte destinationDevice) {
|
||||
return serializedMessages
|
||||
.mapNotNull(message -> {
|
||||
@@ -680,37 +692,47 @@ public class MessagesCache {
|
||||
.thenRun(() -> sample.stop(clearQueueTimer));
|
||||
}
|
||||
|
||||
public String shardForSlot(int slot) {
|
||||
try {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.getPartitions().getPartitionBySlot(slot).getUri().getHost());
|
||||
} catch (final Throwable _) {
|
||||
return "unknown";
|
||||
}
|
||||
Optional<RedisClusterNode> claimNextNodeToPersist(final String persisterId, final Duration ttl) {
|
||||
final List<RedisClusterNode> primaryNodes = redisCluster.withCluster(connection -> connection.getPartitions().stream()
|
||||
.filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM))
|
||||
.collect(Collectors.toCollection(ArrayList::new)));
|
||||
|
||||
Collections.rotate(primaryNodes, Math.abs(nextNodeRotateDistance++) % primaryNodes.size());
|
||||
|
||||
return primaryNodes.stream()
|
||||
.filter(node -> claimNode(node, persisterId, ttl))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
int getNextSlotToPersist() {
|
||||
return (int) (redisCluster.withCluster(connection -> connection.sync().incr(NEXT_SLOT_TO_PERSIST_KEY))
|
||||
% SlotHash.SLOT_COUNT);
|
||||
@VisibleForTesting
|
||||
boolean claimNode(final RedisClusterNode node, final String persisterId, final Duration claimTtl) {
|
||||
return redisCluster.withCluster(connection ->
|
||||
"OK".equals(connection.sync().set(getPersisterNodeClaimKey(node), persisterId, SetArgs.Builder.nx().ex(claimTtl))));
|
||||
}
|
||||
|
||||
List<String> getQueuesToPersist(final int slot, final Instant maxTime, final int limit) {
|
||||
return getQueuesToPersistTimer.record(() -> getQueuesToPersistScript.execute(slot, maxTime, limit));
|
||||
void releaseNodeClaim(final RedisClusterNode node, final String persisterId) {
|
||||
releaseNodeClaimScript.execute(node, persisterId);
|
||||
}
|
||||
|
||||
void addQueueToPersist(final UUID accountUuid, final byte deviceId) {
|
||||
redisCluster.useBinaryCluster(connection -> connection.sync()
|
||||
.zadd(getQueueIndexKey(accountUuid, deviceId), ZAddArgs.Builder.nx(), System.currentTimeMillis(),
|
||||
getMessageQueueKey(accountUuid, deviceId)));
|
||||
@VisibleForTesting
|
||||
static String getPersisterNodeClaimKey(final RedisClusterNode node) {
|
||||
return "persister_node_claim::" + node.getNodeId();
|
||||
}
|
||||
|
||||
void lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
redisCluster.useBinaryCluster(
|
||||
connection -> connection.sync().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE));
|
||||
Flux<String> getQueues(final RedisClusterNode node, final int scanCount) {
|
||||
return redisCluster.withCluster(connection ->
|
||||
ScanStream.scan(connection.getConnection(node.getNodeId()).reactive(),
|
||||
ScanArgs.Builder.matches("user_queue::*").limit(scanCount)));
|
||||
}
|
||||
|
||||
void unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
unlockQueueScript.execute(accountUuid, deviceId);
|
||||
Mono<Void> lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.reactive().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE))
|
||||
.then();
|
||||
}
|
||||
|
||||
Mono<Void> unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
return unlockQueueScript.execute(accountUuid, deviceId);
|
||||
}
|
||||
|
||||
static byte[] getMessageQueueKey(final UUID accountUuid, final byte deviceId) {
|
||||
@@ -721,14 +743,6 @@ public class MessagesCache {
|
||||
return ("user_queue_metadata::{" + accountUuid.toString() + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getQueueIndexKey(final UUID accountUuid, final byte deviceId) {
|
||||
return getQueueIndexKey(SlotHash.getSlot(accountUuid.toString() + "::" + deviceId));
|
||||
}
|
||||
|
||||
static byte[] getQueueIndexKey(final int slot) {
|
||||
return ("user_queue_index::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getSharedMrmKey(final UUID mrmGuid) {
|
||||
return ("mrm::{" + mrmGuid.toString() + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
+8
-3
@@ -28,15 +28,20 @@ class MessagesCacheGetItemsScript {
|
||||
this.getItemsScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_items.lua", ScriptOutputType.OBJECT);
|
||||
}
|
||||
|
||||
Mono<List<byte[]>> execute(final UUID destinationUuid, final byte destinationDevice,
|
||||
int limit, long afterMessageId) {
|
||||
Mono<List<byte[]>> execute(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final int limit,
|
||||
final long afterMessageId,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getPersistInProgressKey(destinationUuid, destinationDevice) // queueLockKey
|
||||
);
|
||||
final List<byte[]> args = List.of(
|
||||
String.valueOf(limit).getBytes(StandardCharsets.UTF_8), // limit
|
||||
String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8) // afterMessageId
|
||||
String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8), // afterMessageId
|
||||
String.valueOf(bypassLock).getBytes(StandardCharsets.UTF_8) // bypassLock
|
||||
);
|
||||
//noinspection unchecked
|
||||
return getItemsScript.executeBinaryReactive(keys, args)
|
||||
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
/**
|
||||
* Returns a list of queues that may be persisted. They will be sorted from oldest to more recent, limited by the
|
||||
* {@code maxTime} argument.
|
||||
*
|
||||
* @see MessagePersister
|
||||
*/
|
||||
class MessagesCacheGetQueuesToPersistScript {
|
||||
|
||||
private final ClusterLuaScript getQueuesToPersistScript;
|
||||
|
||||
MessagesCacheGetQueuesToPersistScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.getQueuesToPersistScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_queues_to_persist.lua",
|
||||
ScriptOutputType.MULTI);
|
||||
}
|
||||
|
||||
List<String> execute(final int slot, final Instant maxTime, final int limit) {
|
||||
final List<String> keys = List.of(
|
||||
new String(MessagesCache.getQueueIndexKey(slot), StandardCharsets.UTF_8) // queueTotalIndexKey
|
||||
);
|
||||
final List<String> args = List.of(
|
||||
String.valueOf(maxTime.toEpochMilli()), // maxTime
|
||||
String.valueOf(limit) // limit
|
||||
);
|
||||
|
||||
//noinspection unchecked
|
||||
return (List<String>) getQueuesToPersistScript.execute(keys, args);
|
||||
}
|
||||
}
|
||||
-2
@@ -58,13 +58,11 @@ class MessagesCacheInsertScript {
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice), // queueTotalIndexKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>(Arrays.asList(
|
||||
EnvelopeUtil.compress(envelope).toByteArray(), // message
|
||||
String.valueOf(envelope.getServerTimestamp()).getBytes(StandardCharsets.UTF_8), // currentTime
|
||||
envelope.getServerGuid().getBytes(StandardCharsets.UTF_8), // guid
|
||||
NEW_MESSAGE_EVENT_BYTES // eventPayload
|
||||
));
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
class MessagesCacheReleaseNodeClaimScript {
|
||||
|
||||
private final ClusterLuaScript releaseNodeClaimScript;
|
||||
|
||||
MessagesCacheReleaseNodeClaimScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.releaseNodeClaimScript =
|
||||
ClusterLuaScript.fromResource(redisCluster, "lua/release_node_claim.lua", ScriptOutputType.STATUS);
|
||||
}
|
||||
|
||||
void execute(final RedisClusterNode node, final String persisterId) {
|
||||
final List<String> keys = List.of(MessagesCache.getPersisterNodeClaimKey(node));
|
||||
final List<String> arguments = List.of(persisterId);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(getClass().getSimpleName())
|
||||
.executeRunnable(() -> releaseNodeClaimScript.execute(keys, arguments));
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -37,8 +37,7 @@ class MessagesCacheRemoveByGuidScript {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice) // queueTotalIndexKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
final List<byte[]> args = messageGuids.stream().map(guid -> guid.toString().getBytes(StandardCharsets.UTF_8))
|
||||
.toList();
|
||||
|
||||
+1
-2
@@ -39,8 +39,7 @@ class MessagesCacheRemoveQueueScript {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice) // queueTotalIndexKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>();
|
||||
|
||||
+10
-7
@@ -6,15 +6,17 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
/**
|
||||
* Unlocks a message queue for persistence/message retrieval.
|
||||
@@ -33,13 +35,14 @@ class MessagesCacheUnlockQueueScript {
|
||||
ClusterLuaScript.fromResource(redisCluster, "lua/unlock_queue.lua", ScriptOutputType.STATUS);
|
||||
}
|
||||
|
||||
void execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
Mono<Void> execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
|
||||
);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME)
|
||||
.executeRunnable(() -> unlockQueueScript.executeBinary(keys, MESSAGES_PERSISTED_EVENT_ARGS));
|
||||
return unlockQueueScript.executeBinaryReactive(keys, MESSAGES_PERSISTED_EVENT_ARGS)
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+18
-4
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
@@ -71,6 +72,7 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
private final Timer deleteForDeviceTimer = Metrics.timer(name(getClass(), "deleteForDevice"));
|
||||
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
|
||||
|
||||
private final Counter outOfRangeKeysDiscarded = Metrics.counter(name(getClass(), "outOfRangeKeysDiscarded"));
|
||||
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "availableKeyCount"))
|
||||
.register(Metrics.globalRegistry);
|
||||
@@ -159,7 +161,14 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
*/
|
||||
public CompletableFuture<Optional<KEMSignedPreKey>> take(final UUID identifier, final byte deviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
return takeHelper(identifier, deviceId)
|
||||
.whenComplete((maybeKey, throwable) ->
|
||||
sample.stop(Metrics.timer(
|
||||
takeKeyTimerName,
|
||||
KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent()))));
|
||||
}
|
||||
|
||||
private CompletableFuture<Optional<KEMSignedPreKey>> takeHelper(final UUID identifier, final byte deviceId) {
|
||||
return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
@@ -196,10 +205,15 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(
|
||||
ConditionalCheckFailedException.class,
|
||||
e -> Optional.empty()))
|
||||
.whenComplete((maybeKey, throwable) ->
|
||||
sample.stop(Metrics.timer(
|
||||
takeKeyTimerName,
|
||||
KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent()))));
|
||||
.thenCompose(maybeKey -> {
|
||||
if (!maybeKey.map(KEMSignedPreKey::keyId).map(KeyIdUtil::keyIdValid).orElse(true)) {
|
||||
// At some point we did not validate that keyIds fit in an unsigned 32-bit integer, which clients require.
|
||||
// This keyId was invalid, so just recursively fetch the next key
|
||||
outOfRangeKeysDiscarded.increment();
|
||||
return takeHelper(identifier, deviceId);
|
||||
}
|
||||
return CompletableFuture.completedFuture(maybeKey);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+7
-4
@@ -107,11 +107,14 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
|
||||
.build())
|
||||
.thenApply(response -> response.hasItem() ? Optional.of(getPreKeyFromItem(response.item())) : Optional.empty());
|
||||
|
||||
findFuture.whenComplete((maybeSignedPreKey, throwable) ->
|
||||
sample.stop(Metrics.timer(findKeyTimerName,
|
||||
"keyPresent", String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent()))));
|
||||
return findFuture.whenComplete((maybeSignedPreKey, throwable) -> {
|
||||
if (throwable == null && maybeSignedPreKey.map(k -> !KeyIdUtil.keyIdValid(k.keyId())).orElse(false)) {
|
||||
throw new IllegalStateException("Encountered an impossible invalid repeated use pre-key id of " + maybeSignedPreKey.get().keyId());
|
||||
}
|
||||
|
||||
return findFuture;
|
||||
sample.stop(Metrics.timer(findKeyTimerName,
|
||||
"keyPresent", String.valueOf(maybeSignedPreKey != null && maybeSignedPreKey.isPresent())));
|
||||
});
|
||||
}
|
||||
|
||||
protected static Map<String, AttributeValue> getPrimaryKey(final UUID identifier, final byte deviceId) {
|
||||
|
||||
+22
-7
@@ -47,7 +47,6 @@ import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
* may fall back to using the device's repeated-use ("last-resort") signed pre-key instead.
|
||||
*/
|
||||
public class SingleUseECPreKeyStore {
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
|
||||
@@ -58,12 +57,14 @@ public class SingleUseECPreKeyStore {
|
||||
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
|
||||
|
||||
private final Counter noKeyCountAvailableCounter = Metrics.counter(name(getClass(), "noKeyCountAvailable"));
|
||||
|
||||
private final Counter outOfRangeKeysDiscarded =
|
||||
Metrics.counter(name(getClass(), "outOfRangeKeysDiscarded"));
|
||||
final DistributionSummary keysConsideredForTakeDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "keysConsideredForTake"))
|
||||
.distributionStatisticExpiry(Duration.ofMinutes(10))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
|
||||
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "availableKeyCount"))
|
||||
.distributionStatisticExpiry(Duration.ofMinutes(10))
|
||||
@@ -135,7 +136,7 @@ public class SingleUseECPreKeyStore {
|
||||
public CompletableFuture<Optional<ECPreKey>> take(final UUID identifier, final byte deviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final AttributeValue partitionKey = getPartitionKey(identifier);
|
||||
final AtomicInteger keysConsidered = new AtomicInteger(0);
|
||||
final AtomicInteger deletionAttempts = new AtomicInteger(0);
|
||||
|
||||
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
@@ -156,16 +157,26 @@ public class SingleUseECPreKeyStore {
|
||||
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build())
|
||||
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), 1)
|
||||
.doOnNext(deleteItemResponse -> keysConsidered.incrementAndGet())
|
||||
.concatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)))
|
||||
.doOnNext(_ -> deletionAttempts.incrementAndGet())
|
||||
.filter(DeleteItemResponse::hasAttributes)
|
||||
.filter(item -> {
|
||||
final long keyId = getKeyIdFromItem(item.attributes());
|
||||
final boolean keyIdValid = KeyIdUtil.keyIdValid(keyId);
|
||||
if (!keyIdValid) {
|
||||
outOfRangeKeysDiscarded.increment();
|
||||
}
|
||||
// At some point we did not validate that keyIds fit in an unsigned 32-bit integer, which clients require.
|
||||
// If this keyId is invalid, we'll skip it and fetch the next key
|
||||
return keyIdValid;
|
||||
})
|
||||
.next()
|
||||
.map(deleteItemResponse -> getPreKeyFromItem(deleteItemResponse.attributes()))
|
||||
.toFuture()
|
||||
.thenApply(Optional::ofNullable)
|
||||
.whenComplete((maybeKey, throwable) -> {
|
||||
sample.stop(Metrics.timer(takeKeyTimerName, KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent())));
|
||||
keysConsideredForTakeDistributionSummary.record(keysConsidered.get());
|
||||
keysConsideredForTakeDistributionSummary.record(deletionAttempts.get());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -310,7 +321,7 @@ public class SingleUseECPreKeyStore {
|
||||
}
|
||||
|
||||
private ECPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
|
||||
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
|
||||
final long keyId = getKeyIdFromItem(item);
|
||||
final byte[] publicKey = AttributeValues.extractByteArray(item.get(ATTR_PUBLIC_KEY), PARSE_BYTE_ARRAY_COUNTER_NAME);
|
||||
|
||||
try {
|
||||
@@ -320,4 +331,8 @@ public class SingleUseECPreKeyStore {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static long getKeyIdFromItem(final Map<String, AttributeValue> item) {
|
||||
return item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class UnexpectedExistingPhoneNumberException extends RuntimeException {
|
||||
}
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
class FoundationDbMessagePublisher {
|
||||
|
||||
private final Database database;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
|
||||
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
|
||||
private final KeySelector endKeyExclusive;
|
||||
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
|
||||
enum State {
|
||||
/// Messages are likely available in the queue. Initial state.
|
||||
MESSAGES_AVAILABLE,
|
||||
/// We're actively fetching messages from FoundationDB.
|
||||
FETCHING_MESSAGES,
|
||||
/// We have read all available messages in the queue.
|
||||
QUEUE_EMPTY,
|
||||
/// The message available watch triggered while other stuff was going on. We record it as a state so that we can
|
||||
/// fetch new messages at a more opportune time.
|
||||
MESSAGE_AVAILABLE_SIGNAL_BUFFERED,
|
||||
/// Waiting for the message available watch to trigger that signals new messages have arrived.
|
||||
AWAITING_NEW_MESSAGES,
|
||||
/// Terminal state indicating no more messages will be published. Either we have successfully published all messages
|
||||
/// in the case of a finite publisher, or the subscriber has indicated that it has terminated.
|
||||
TERMINATED,
|
||||
/// Terminal state reached when there is an error fetching or publishing messages.
|
||||
ERROR
|
||||
}
|
||||
|
||||
enum Event {
|
||||
/// Downstream subscriber requested more items.
|
||||
DEMAND_REQUESTED,
|
||||
/// The FoundationDB range query returned less than the batch size.
|
||||
FETCHED_ALL_AVAILABLE_MESSAGES,
|
||||
/// We have successfully fetched and published a message batch
|
||||
PUBLISHED_MESSAGES,
|
||||
/// The message available watch triggered indicating new messages have arrived.
|
||||
MESSAGE_AVAILABLE_WATCH_TRIGGERED,
|
||||
/// Internal self-trigger used to immediately transition to the next state.
|
||||
INTERNAL_TRIGGER,
|
||||
/// An error occurred during fetching from FoundationDB or publishing messages to the sink.
|
||||
FETCH_OR_PUBLISH_ERROR_OCCURRED
|
||||
}
|
||||
|
||||
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
|
||||
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
|
||||
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
|
||||
@Nullable private final byte[] messagesAvailableWatchKey;
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
private final Flux<MessageStreamEntry.Envelope> messagePublisher;
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
|
||||
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
|
||||
private State state = State.MESSAGES_AVAILABLE;
|
||||
/// Reference to the sink we publishes messages to.
|
||||
private volatile FluxSink<MessageStreamEntry.Envelope> emitter;
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
FoundationDbMessagePublisher(
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener) {
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.database = database;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.messagePublisher = Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
emitter.onDispose(this::onDispose);
|
||||
});
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
|
||||
/// yields the last message that was present in the queue at the time the publisher was created. This is helpful in
|
||||
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
|
||||
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
|
||||
public static FoundationDbMessagePublisher createFinitePublisher(
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan) {
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive, endKeyExclusive, database, maxMessagesPerScan, null, null);
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
|
||||
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
|
||||
/// messages and is now waiting for a live stream of new messages.
|
||||
public static FoundationDbMessagePublisher createInfinitePublisher(
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive, endKeyExclusive, database, maxMessagesPerScan, messagesAvailableWatchKey, null);
|
||||
}
|
||||
|
||||
private synchronized void setState(final State newState, final Event event) {
|
||||
LOGGER.debug("Transitioned from state {} to state {} on event {}", state, newState, event);
|
||||
final State oldState = state;
|
||||
state = newState;
|
||||
stateChangeListener.accept(oldState, newState);
|
||||
}
|
||||
|
||||
/// Called when an event occurs. Transitions the current state to a new state if this is a defined transition.
|
||||
///
|
||||
/// @param event the {@link Event} that has occurred
|
||||
protected synchronized void transitionStateOnEvent(final Event event) {
|
||||
assert emitter != null;
|
||||
boolean knownTransition = true;
|
||||
switch (state) {
|
||||
case MESSAGES_AVAILABLE -> {
|
||||
switch (event) {
|
||||
case DEMAND_REQUESTED -> {
|
||||
setState(State.FETCHING_MESSAGES, event);
|
||||
emitMessages();
|
||||
}
|
||||
case INTERNAL_TRIGGER -> {
|
||||
if (emitter.requestedFromDownstream() > 0) {
|
||||
setState(State.FETCHING_MESSAGES, event);
|
||||
emitMessages();
|
||||
}
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
case FETCHING_MESSAGES -> {
|
||||
switch (event) {
|
||||
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.QUEUE_EMPTY, event);
|
||||
case PUBLISHED_MESSAGES -> {
|
||||
setState(State.MESSAGES_AVAILABLE, event);
|
||||
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
case FETCH_OR_PUBLISH_ERROR_OCCURRED -> setState(State.ERROR, event);
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
case QUEUE_EMPTY -> {
|
||||
if (terminateOnQueueEmpty) {
|
||||
switch (event) {
|
||||
case PUBLISHED_MESSAGES -> {
|
||||
setState(State.TERMINATED, event);
|
||||
emitter.complete();
|
||||
}
|
||||
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.ERROR, event);
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
} else {
|
||||
switch (event) {
|
||||
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> setState(State.MESSAGE_AVAILABLE_SIGNAL_BUFFERED, event);
|
||||
case PUBLISHED_MESSAGES -> setState(State.AWAITING_NEW_MESSAGES, event);
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
case MESSAGE_AVAILABLE_SIGNAL_BUFFERED -> {
|
||||
switch (event) {
|
||||
case PUBLISHED_MESSAGES -> {
|
||||
setState(State.MESSAGES_AVAILABLE, event);
|
||||
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
case AWAITING_NEW_MESSAGES -> {
|
||||
switch (event) {
|
||||
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> {
|
||||
setState(State.MESSAGES_AVAILABLE, event);
|
||||
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
}
|
||||
default -> knownTransition = false;
|
||||
}
|
||||
if (!knownTransition) {
|
||||
LOGGER.debug("Unhandled event {} on state {}", event, state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
|
||||
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
|
||||
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans
|
||||
///
|
||||
/// @return a future of a list of [MessageStreamEntry] with a max size of [#maxMessagesPerScan]
|
||||
private CompletableFuture<List<MessageStreamEntry.Envelope>> getMessagesBatch() {
|
||||
return database.runAsync(transaction -> getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first().ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
|
||||
final List<MessageStreamEntry.Envelope> items = lastKeyReadAndItems.second();
|
||||
if (items.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
if (!terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
|
||||
///
|
||||
/// @param transaction the FoundationDB transaction in which to perform the read query
|
||||
/// @param beginInclusive the range start key (inclusive)
|
||||
/// @param endExclusive the range end key (exclusive)
|
||||
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
|
||||
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
|
||||
private static CompletableFuture<Pair<Optional<byte[]>, List<MessageStreamEntry.Envelope>>> getItemsInRange(
|
||||
final Transaction transaction,
|
||||
final KeySelector beginInclusive,
|
||||
final KeySelector endExclusive,
|
||||
final int maxMessagesPerScan) {
|
||||
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
|
||||
? Optional.empty()
|
||||
: Optional.of(keyValues.getLast().getKey());
|
||||
final List<MessageStreamEntry.Envelope> messages = keyValues.stream()
|
||||
.map(keyValue -> {
|
||||
try {
|
||||
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.toList();
|
||||
return new Pair<>(lastKeyRead, messages);
|
||||
});
|
||||
}
|
||||
|
||||
/// Fetch and publish messages. Messages are fetched in batches of [#maxMessagesPerScan] to avoid excessive memory
|
||||
/// consumption. After each fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading
|
||||
/// from. If the fetch operation returns fewer items than the batch size, we infer that we have fetched all available
|
||||
/// messages and [Event#FETCHED_ALL_AVAILABLE_MESSAGES] is sent to the state machine. See [#getMessagesBatch()]
|
||||
/// for details. Additionally, after we successfully publish the batch of messages, {@link Event#PUBLISHED_MESSAGES}
|
||||
/// is emitted. If there's an error while fetching or publishing, [Event#FETCH_OR_PUBLISH_ERROR_OCCURRED] is emitted
|
||||
/// instead.
|
||||
private void emitMessages() {
|
||||
getMessagesBatch()
|
||||
.thenAccept(messageStreamEntries -> {
|
||||
messageStreamEntries.forEach(emitter::next);
|
||||
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
|
||||
})
|
||||
.exceptionally(t -> {
|
||||
transitionStateOnEvent(Event.FETCH_OR_PUBLISH_ERROR_OCCURRED);
|
||||
emitter.error(t);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// Get the stream of messages.
|
||||
///
|
||||
/// @return [Flux] of messages
|
||||
public Flux<MessageStreamEntry.Envelope> getMessages() {
|
||||
return this.messagePublisher;
|
||||
}
|
||||
|
||||
private synchronized void setWatch(final Transaction transaction) {
|
||||
assert messagesAvailableWatchKey != null;
|
||||
// Set a watch that will be triggered when new messages arrive. When it is triggered, we attempt to fetch messages
|
||||
// again (if there is demand). When we run out of messages, this method will be called again, setting another watch,
|
||||
// and so on, thus achieving a "watch for new messages -> read -> publish" loop.
|
||||
watchFuture = transaction.watch(messagesAvailableWatchKey);
|
||||
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
|
||||
}
|
||||
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
}
|
||||
|
||||
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
|
||||
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
|
||||
private synchronized void cancelWatch() {
|
||||
if (watchFuture != null) {
|
||||
watchFuture.cancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -22,6 +22,8 @@ import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
@@ -246,6 +248,18 @@ public class FoundationDbMessageStore {
|
||||
}, executor);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
|
||||
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice, final int maxMessagesPerScan) {
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
getShardForAci(aci),
|
||||
maxMessagesPerScan);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/// A [MessageStream] implementation that fetches messages from FoundationDB
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final Database database;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace, final byte[] messagesAvailableWatchKey,
|
||||
final Database database, final int maxMessagesPerScan) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.database = database;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return this.messageStreamPublisher;
|
||||
}
|
||||
|
||||
/// Create a message publisher
|
||||
///
|
||||
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
|
||||
/// @implNote The message publisher is stitched together by concatenating:
|
||||
/// 1. **A finite message publisher**: On initial request, we record the current end-of-queue key in the device mailbox.
|
||||
/// Then, we fetch all messages in order until the recorded key and finally complete the stream
|
||||
/// 2. **A queue-empty signal** is emitted
|
||||
/// 3. **An infinite message publisher**: We start reading from where the finite publisher left off. When all messages
|
||||
/// are read, we wait for new messages, publish them, then wait again in a loop forever (until the flux is canceled
|
||||
/// explicitly or due to an error). This is accomplished by setting a FoundationDB [watch](https://github.com/apple/foundationdb/wiki/An-Overview-how-Watches-Work)
|
||||
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
|
||||
/// See [FoundationDbMessageStore] for more details on the message insert process.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
|
||||
.flatMapMany(maybeEndOfQueueKeyExclusive -> {
|
||||
final Flux<MessageStreamEntry.Envelope> finitePublisher = maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive, database, maxMessagesPerScan).getMessages())
|
||||
.orElseGet(Flux::empty);
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
|
||||
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
final Flux<MessageStreamEntry.Envelope> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
infinitePublisherBeginKey, KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
database, maxMessagesPerScan, messagesAvailableWatchKey).getMessages();
|
||||
return Flux.concat(
|
||||
finitePublisher,
|
||||
Mono.just(new MessageStreamEntry.QueueEmpty()),
|
||||
infinitePublisher
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows
|
||||
/// us to query keys up to and including the greatest key, and sets us up to begin reading from the next key in
|
||||
/// a subsequent scan.
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
|
||||
return database.runAsync(
|
||||
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
|
||||
.thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
assert items.size() == 1;
|
||||
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
|
||||
throw new UnsupportedOperationException("Not implemented");
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -130,12 +130,13 @@ public class AppleAppStoreClient {
|
||||
try {
|
||||
return getAllSubscriptionsHelper(defaultEnvironment, originalTransactionId);
|
||||
} catch (final APIException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", e.getApiError().name())).increment();
|
||||
final APIError apiError = e.getApiError();
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", apiError != null ? apiError.name() : "http_" + e.getHttpStatusCode())).increment();
|
||||
throw switch (e.getApiError()) {
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
default -> throw e;
|
||||
case null, default -> throw e;
|
||||
};
|
||||
} catch (final IOException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
|
||||
@@ -183,7 +184,7 @@ public class AppleAppStoreClient {
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
|
||||
default -> false;
|
||||
case null, default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+22
-7
@@ -433,33 +433,48 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
private Subscription endSubscription(Subscription subscription) {
|
||||
@VisibleForTesting
|
||||
void endSubscription(Subscription subscription) {
|
||||
|
||||
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
|
||||
return switch (status) {
|
||||
switch (status) {
|
||||
// The payment for this period has not processed yet, we should immediately cancel to prevent any payment from
|
||||
// going through.
|
||||
case UNPAID, PAST_DUE, INCOMPLETE -> cancelSubscriptionImmediately(subscription);
|
||||
// Otherwise, set the subscription to cancel at the current period end. If the subscription is active, it may
|
||||
// continue to be used until the end of the period.
|
||||
default -> cancelSubscriptionAtEndOfCurrentPeriod(subscription);
|
||||
default -> {
|
||||
|
||||
final Price price = getPriceForSubscription(subscription);
|
||||
|
||||
if (supportedCurrenciesByPaymentMethod.values().stream()
|
||||
.noneMatch(supported -> supported.contains(price.getCurrency()))) {
|
||||
|
||||
// This currency is no longer supported. Cancel-at-period-end will fail, so we must cancel immediately.
|
||||
cancelSubscriptionImmediately(subscription);
|
||||
} else {
|
||||
|
||||
cancelSubscriptionAtEndOfCurrentPeriod(subscription);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Subscription cancelSubscriptionImmediately(Subscription subscription) {
|
||||
private void cancelSubscriptionImmediately(Subscription subscription) {
|
||||
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
try {
|
||||
return stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private Subscription cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.setCancelAtPeriodEnd(true)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
|
||||
@@ -55,6 +55,10 @@ public final class HeaderUtils {
|
||||
return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static String bearerAuthHeader(final String token) {
|
||||
return "Bearer " + token;
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static String getTimestampHeader() {
|
||||
return TIMESTAMP_HEADER + ":" + System.currentTimeMillis();
|
||||
|
||||
+7
-2
@@ -7,8 +7,10 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
@@ -55,12 +57,14 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this(accountsManager,
|
||||
disconnectionRequestManager,
|
||||
asnInfoProviderSupplier,
|
||||
clientReleaseManager,
|
||||
(account, device, client) -> new WebSocketConnection(receiptSender,
|
||||
messagesManager,
|
||||
@@ -80,6 +84,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
@VisibleForTesting AuthenticatedConnectListener(
|
||||
final AccountsManager accountsManager,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final WebSocketConnectionBuilder webSocketConnectionBuilder) {
|
||||
|
||||
@@ -87,8 +92,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.webSocketConnectionBuilder = webSocketConnectionBuilder;
|
||||
|
||||
this.openAuthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-authenticated", clientReleaseManager);
|
||||
this.openUnauthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-unauthenticated", clientReleaseManager);
|
||||
this.openAuthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-authenticated", asnInfoProviderSupplier, clientReleaseManager);
|
||||
this.openUnauthenticatedWebSocketCounter = new OpenWebSocketCounter("rpc-unauthenticated", asnInfoProviderSupplier, clientReleaseManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+4
-1
@@ -14,6 +14,8 @@ import java.util.Optional;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
@@ -48,13 +50,14 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
|
||||
private final Duration timeout;
|
||||
|
||||
public ProvisioningConnectListener(final ProvisioningManager provisioningManager,
|
||||
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final ScheduledExecutorService timeoutExecutor,
|
||||
final Duration timeout) {
|
||||
this.provisioningManager = provisioningManager;
|
||||
this.timeoutExecutor = timeoutExecutor;
|
||||
this.timeout = timeout;
|
||||
this.openWebSocketCounter = new OpenWebSocketCounter("provisioning", clientReleaseManager);
|
||||
this.openWebSocketCounter = new OpenWebSocketCounter("provisioning", asnInfoProviderSupplier, clientReleaseManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+52
-4
@@ -10,17 +10,35 @@ import io.dropwizard.core.cli.ServerCommand;
|
||||
import io.dropwizard.core.server.DefaultServerFactory;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.jetty.HttpsConnectorFactory;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagePersister;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import reactor.core.publisher.Hooks;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerConfiguration> {
|
||||
|
||||
private static final String WORKER_COUNT = "workers";
|
||||
@Nullable
|
||||
private ExecutorService persistQueueExecutorService;
|
||||
|
||||
@Nullable
|
||||
private Scheduler persistQueueScheduler;
|
||||
|
||||
private static final String MAX_CONCURRENCY = "maxConcurrency";
|
||||
private static final String SCAN_COUNT = "scanCount";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersisterServiceCommand.class);
|
||||
|
||||
public MessagePersisterServiceCommand() {
|
||||
super(new Application<>() {
|
||||
@@ -35,11 +53,20 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
// This is a deliberate misnomer for consistency with other service commands that expect a worker count
|
||||
subparser.addArgument("--workers")
|
||||
.type(Integer.class)
|
||||
.dest(WORKER_COUNT)
|
||||
.dest(MAX_CONCURRENCY)
|
||||
.required(true)
|
||||
.help("The number of worker threads");
|
||||
.help("The maximum number of concurrent Redis/DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--scan-count")
|
||||
.type(Integer.class)
|
||||
.dest(SCAN_COUNT)
|
||||
.required(false)
|
||||
.setDefault(1024)
|
||||
.help("The COUNT argument for the Redis SCAN operation that finds message queues");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -47,6 +74,7 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
throws Exception {
|
||||
|
||||
UncaughtExceptionHandler.register();
|
||||
Hooks.onErrorDropped(e -> logger.warn("Dropped message persistence error", e));
|
||||
|
||||
final CommandDependencies deps = CommandDependencies.build("message-persister-service", environment, configuration);
|
||||
MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager());
|
||||
@@ -60,16 +88,36 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
});
|
||||
}
|
||||
|
||||
persistQueueExecutorService = Executors.newVirtualThreadPerTaskExecutor();
|
||||
persistQueueScheduler = Schedulers.fromExecutorService(persistQueueExecutorService, "persistQueue");
|
||||
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(),
|
||||
deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.dynamicConfigurationManager(),
|
||||
persistQueueScheduler,
|
||||
Clock.systemUTC(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(WORKER_COUNT));
|
||||
namespace.getInt(MAX_CONCURRENCY),
|
||||
namespace.getInt(SCAN_COUNT));
|
||||
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void cleanup() {
|
||||
super.cleanup();
|
||||
|
||||
Hooks.resetOnErrorDropped();
|
||||
|
||||
if (persistQueueScheduler != null) {
|
||||
persistQueueScheduler.dispose();
|
||||
}
|
||||
|
||||
if (persistQueueExecutorService != null) {
|
||||
persistQueueExecutorService.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -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();
|
||||
}
|
||||
}
|
||||
+93
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ 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 {
|
||||
@@ -87,7 +89,7 @@ message DeleteAccountResponse {
|
||||
|
||||
message SetRegistrationLockRequest {
|
||||
// The new registration lock secret for the authenticated account.
|
||||
bytes registration_lock = 1;
|
||||
bytes registration_lock = 1 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
message SetRegistrationLockResponse {
|
||||
@@ -100,8 +102,9 @@ message ClearRegistrationLockResponse {
|
||||
}
|
||||
|
||||
message ReserveUsernameHashRequest {
|
||||
// A prioritized list of username hashes to attempt to reserve.
|
||||
repeated bytes username_hashes = 1;
|
||||
// A prioritized list of username hashes to attempt to reserve. Each hash must
|
||||
// be exactly 32 bytes.
|
||||
repeated bytes username_hashes = 1 [(require.size) = {min: 1, max: 20}];
|
||||
}
|
||||
|
||||
message UsernameNotAvailable {}
|
||||
@@ -113,21 +116,21 @@ 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"];
|
||||
}
|
||||
}
|
||||
|
||||
message ConfirmUsernameHashRequest {
|
||||
// The username hash to claim for the authenticated account.
|
||||
bytes username_hash = 1;
|
||||
bytes username_hash = 1 [(require.exactlySize) = 32];
|
||||
|
||||
// A zero-knowledge proof that the given username hash was generated by the
|
||||
// Signal username algorithm.
|
||||
bytes zk_proof = 2;
|
||||
bytes zk_proof = 2 [(require.nonEmpty) = true];
|
||||
|
||||
// The ciphertext of the chosen username for use in public-facing contexts
|
||||
// (e.g. links and QR codes).
|
||||
bytes username_ciphertext = 3;
|
||||
bytes username_ciphertext = 3 [(require.size) = {min: 1, max: 128}];
|
||||
}
|
||||
|
||||
message ConfirmUsernameHashResponse {
|
||||
@@ -144,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"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +163,7 @@ message DeleteUsernameHashResponse {
|
||||
|
||||
message SetUsernameLinkRequest {
|
||||
// The username ciphertext for which to generate a new link handle.
|
||||
bytes username_ciphertext = 1;
|
||||
bytes username_ciphertext = 1 [(require.size) = {min: 1, max: 128}];
|
||||
|
||||
// If true and the account already had an encrypted username stored, the
|
||||
// existing link handle will be reused. Otherwise a new link handle will be
|
||||
@@ -175,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"];
|
||||
|
||||
}
|
||||
}
|
||||
@@ -214,7 +217,7 @@ message SetDiscoverableByPhoneNumberResponse {
|
||||
|
||||
message SetRegistrationRecoveryPasswordRequest {
|
||||
// The new registration recovery password for the authenticated account.
|
||||
bytes registration_recovery_password = 1;
|
||||
bytes registration_recovery_password = 1 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
message SetRegistrationRecoveryPasswordResponse {
|
||||
@@ -233,7 +236,7 @@ message CheckAccountExistenceResponse {
|
||||
|
||||
message LookupUsernameHashRequest {
|
||||
// A 32-byte username hash for which to find an account.
|
||||
bytes username_hash = 1;
|
||||
bytes username_hash = 1 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
message LookupUsernameHashResponse {
|
||||
@@ -242,14 +245,14 @@ 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"];
|
||||
}
|
||||
}
|
||||
|
||||
message LookupUsernameLinkRequest {
|
||||
// The link handle for which to find an encrypted username. Link handles are
|
||||
// 16-byte representations of UUIDs.
|
||||
bytes username_link_handle = 1;
|
||||
bytes username_link_handle = 1 [(require.exactlySize) = 16];
|
||||
}
|
||||
|
||||
message LookupUsernameLinkResponse {
|
||||
@@ -259,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"];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.attachments;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
service Attachments {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Retrieve an upload form that can be used to perform a resumable upload
|
||||
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
|
||||
}
|
||||
|
||||
message GetUploadFormRequest {
|
||||
// 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 {
|
||||
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;
|
||||
|
||||
@@ -202,22 +202,22 @@ service BackupsAnonymous {
|
||||
message SignedPresentation {
|
||||
// Presentation of a BackupAuthCredential previously retrieved from
|
||||
// GetBackupAuthCredentials on the authenticated channel
|
||||
bytes presentation = 1;
|
||||
bytes presentation = 1 [(require.nonEmpty) = true];
|
||||
|
||||
// The presentation signed with the private key corresponding to the public
|
||||
// key set with SetPublicKey
|
||||
bytes presentation_signature = 2;
|
||||
bytes presentation_signature = 2 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
message SetPublicKeyRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
// The public key, serialized in libsignal's elliptic-curve public key format.
|
||||
bytes public_key = 2;
|
||||
bytes public_key = 2 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
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,25 +363,14 @@ 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 {
|
||||
message UploadForm {
|
||||
// Indicates the CDN type. 3 indicates resumable uploads using TUS
|
||||
uint32 cdn = 1;
|
||||
|
||||
// The location within the specified cdn where the finished upload can be found
|
||||
string key = 2;
|
||||
|
||||
// A map of headers to include with all upload requests. Potentially contains
|
||||
// time-limited upload credentials
|
||||
map<string, string> headers = 3;
|
||||
|
||||
// The URL to upload to with the appropriate protocol
|
||||
string signed_upload_location = 4;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
UploadForm upload_form = 1;
|
||||
oneof response {
|
||||
common.UploadForm upload_form = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
@@ -392,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 +410,7 @@ message CopyMediaRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
// Items to copy
|
||||
repeated CopyMediaItem items = 2;
|
||||
repeated CopyMediaItem items = 2 [(require.size) = {min: 1, max: 1000}];
|
||||
}
|
||||
|
||||
message CopyMediaResponse {
|
||||
@@ -437,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;
|
||||
|
||||
@@ -448,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"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,7 +453,7 @@ message ListMediaRequest {
|
||||
optional string cursor = 2;
|
||||
|
||||
// If provided, the maximum number of entries to return in a page
|
||||
uint32 limit = 3 [(require.range) = {min: 0, max: 10000}];
|
||||
uint32 limit = 3 [(require.range) = {min: 1, max: 10000}];
|
||||
}
|
||||
message ListMediaResponse {
|
||||
message ListEntry {
|
||||
@@ -497,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
|
||||
@@ -512,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;
|
||||
|
||||
@@ -529,17 +517,17 @@ message DeleteMediaItem {
|
||||
uint32 cdn = 1;
|
||||
|
||||
// The media_id of the object to delete
|
||||
bytes media_id = 2;
|
||||
bytes media_id = 2 [(require.exactlySize) = 15];
|
||||
}
|
||||
|
||||
message DeleteMediaRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
repeated DeleteMediaItem items = 2;
|
||||
repeated DeleteMediaItem items = 2 [(require.size) = {min: 1, max: 1000}];
|
||||
}
|
||||
|
||||
message DeleteMediaResponse {
|
||||
oneof outcome {
|
||||
oneof response {
|
||||
DeleteMediaItem deleted_item = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
|
||||
@@ -9,6 +9,8 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.common;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
enum IdentityType {
|
||||
IDENTITY_TYPE_UNSPECIFIED = 0;
|
||||
IDENTITY_TYPE_ACI = 1;
|
||||
@@ -20,7 +22,7 @@ message ServiceIdentifier {
|
||||
IdentityType identity_type = 1;
|
||||
|
||||
// The UUID of the identity represented by this service identifier.
|
||||
bytes uuid = 2;
|
||||
bytes uuid = 2 [(require.exactlySize) = 16];
|
||||
}
|
||||
|
||||
message AccountIdentifiers {
|
||||
@@ -36,35 +38,40 @@ message AccountIdentifiers {
|
||||
}
|
||||
|
||||
message EcPreKey {
|
||||
// A locally-unique identifier for this key.
|
||||
uint64 key_id = 1;
|
||||
// A locally-unique identifier for this key, which will be provided by
|
||||
// peers using this key to encrypt messages so the private key can be looked
|
||||
// up.
|
||||
uint32 key_id = 1;
|
||||
|
||||
// The serialized form of the public key.
|
||||
bytes public_key = 2;
|
||||
// The public key, serialized in libsignal's elliptic-curve public key format.
|
||||
bytes public_key = 2 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
message EcSignedPreKey {
|
||||
// A locally-unique identifier for this key.
|
||||
uint64 key_id = 1;
|
||||
// A locally-unique identifier for this key, which will be provided by
|
||||
// peers using this key to encrypt messages so the private key can be looked
|
||||
// up.
|
||||
uint32 key_id = 1;
|
||||
|
||||
// The serialized form of the public key.
|
||||
bytes public_key = 2;
|
||||
// The public key, serialized in libsignal's elliptic-curve public key format.
|
||||
bytes public_key = 2 [(require.nonEmpty) = true];
|
||||
|
||||
// A signature of the public key, verifiable with the identity key for the
|
||||
// account/identity associated with this pre-key.
|
||||
bytes signature = 3;
|
||||
bytes signature = 3 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
message KemSignedPreKey {
|
||||
// A locally-unique identifier for this key.
|
||||
uint64 key_id = 1;
|
||||
// An locally-unique identifier for this key, which will be provided by peers
|
||||
// using this key to encrypt messages so the private key can be looked up.
|
||||
uint32 key_id = 1;
|
||||
|
||||
// The serialized form of the public key.
|
||||
bytes public_key = 2;
|
||||
// The public key, serialized in libsignal's Kyber1024 public key format.
|
||||
bytes public_key = 2 [(require.nonEmpty) = true];
|
||||
|
||||
// A signature of the public key, verifiable with the identity key for the
|
||||
// account/identity associated with this pre-key.
|
||||
bytes signature = 3;
|
||||
bytes signature = 3 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
enum DeviceCapability {
|
||||
@@ -87,6 +94,22 @@ message ZkCredential {
|
||||
/*
|
||||
* The ZK credential, using libsignal's serialization
|
||||
*/
|
||||
bytes credential = 2;
|
||||
bytes credential = 2 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
// An upload location and credentials which may be used to upload an object
|
||||
// to an external CDN
|
||||
message UploadForm {
|
||||
// Indicates the CDN type. 3 indicates resumable uploads using TUS
|
||||
uint32 cdn = 1;
|
||||
|
||||
// The location within the specified cdn where the finished upload can be found
|
||||
string key = 2;
|
||||
|
||||
// A map of headers to include with all upload requests. Potentially contains
|
||||
// time-limited upload credentials
|
||||
map<string, string> headers = 3;
|
||||
|
||||
// The URL to upload to with the appropriate protocol
|
||||
string signed_upload_location = 4;
|
||||
}
|
||||
@@ -7,6 +7,8 @@ syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
package org.signal.chat.credentials;
|
||||
|
||||
// Provides methods for obtaining and verifying credentials for "external" services
|
||||
@@ -69,7 +71,7 @@ message CheckSvrCredentialsRequest {
|
||||
// A list of credentials from previously made calls to `ExternalServiceCredentials.GetExternalServiceCredentials()`
|
||||
// for `EXTERNAL_SERVICE_TYPE_SVR`. This list may contain credentials generated by different users. Up to 10 credentials
|
||||
// can be checked.
|
||||
repeated string passwords = 2;
|
||||
repeated string passwords = 2 [(require.nonEmpty) = true, (require.size) = {max: 10}];
|
||||
}
|
||||
|
||||
// For each of the credentials tokens in the `CheckSvrCredentialsRequest` contains the result of the check.
|
||||
|
||||
@@ -83,7 +83,7 @@ message RemoveDeviceRequest {
|
||||
message SetDeviceNameRequest {
|
||||
// A sequence of bytes that encodes an encrypted human-readable name for this
|
||||
// device.
|
||||
bytes name = 1 [(require.size) = {min: 1, max: 256}];
|
||||
bytes name = 1 [(require.size) = {min: 1, max: 225}];
|
||||
|
||||
// The identifier for the device for which to set a name.
|
||||
uint32 id = 2;
|
||||
|
||||
@@ -9,8 +9,12 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.keys;
|
||||
|
||||
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 {
|
||||
@@ -111,6 +115,9 @@ message GetPreKeysAnonymousRequest {
|
||||
|
||||
// A group send endorsement token for the targeted account.
|
||||
bytes group_send_token = 3;
|
||||
|
||||
// The destination account allows unrestricted unidentified access
|
||||
google.protobuf.Empty unrestricted_access = 4;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,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"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,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"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,7 +177,7 @@ message SetOneTimeEcPreKeysRequest {
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
// The unsigned EC pre-keys to be stored.
|
||||
repeated common.EcPreKey pre_keys = 2;
|
||||
repeated common.EcPreKey pre_keys = 2 [(require.size) = {min: 1, max: 100}];
|
||||
}
|
||||
|
||||
message SetOneTimeKemSignedPreKeysRequest {
|
||||
@@ -179,7 +186,7 @@ message SetOneTimeKemSignedPreKeysRequest {
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
// The KEM pre-keys to be stored.
|
||||
repeated common.KemSignedPreKey pre_keys = 2;
|
||||
repeated common.KemSignedPreKey pre_keys = 2 [(require.size) = {min: 1, max: 100}];
|
||||
}
|
||||
|
||||
message SetEcSignedPreKeyRequest {
|
||||
@@ -187,7 +194,7 @@ message SetEcSignedPreKeyRequest {
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
// The signed EC pre-key itself.
|
||||
common.EcSignedPreKey signed_pre_key = 2;
|
||||
common.EcSignedPreKey signed_pre_key = 2 [(require.present) = true];
|
||||
}
|
||||
|
||||
message SetKemLastResortPreKeyRequest {
|
||||
@@ -195,7 +202,7 @@ message SetKemLastResortPreKeyRequest {
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
// The signed KEM pre-key itself.
|
||||
common.KemSignedPreKey signed_pre_key = 2;
|
||||
common.KemSignedPreKey signed_pre_key = 2 [(require.present) = true];
|
||||
}
|
||||
|
||||
message SetPreKeyResponse {
|
||||
@@ -205,7 +212,7 @@ message CheckIdentityKeyRequest {
|
||||
// The service identifier of the account for which we want to check the associated identity key fingerprint.
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
// The most significant 4 bytes of the SHA-256 hash of the identity key associated with the target account/identity type.
|
||||
bytes fingerprint = 2;
|
||||
bytes fingerprint = 2 [(require.exactlySize) = 4];
|
||||
}
|
||||
|
||||
message CheckIdentityKeyResponse {
|
||||
|
||||
@@ -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"];
|
||||
|
||||
}
|
||||
}
|
||||
@@ -198,10 +199,13 @@ message SendSealedSenderMessageRequest {
|
||||
oneof authorization {
|
||||
|
||||
// The unidentified access key (UAK) for the destination account.
|
||||
bytes unidentified_access_key = 5;
|
||||
bytes unidentified_access_key = 5 [(require.exactlySize) = 16];
|
||||
|
||||
// A group send endorsement token for the destination account.
|
||||
bytes group_send_token = 6;
|
||||
|
||||
// The destination account allows unrestricted unidentified access
|
||||
google.protobuf.Empty unrestricted_access = 7;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,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"];
|
||||
|
||||
}
|
||||
}
|
||||
@@ -304,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"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +362,7 @@ message ChallengeRequired {
|
||||
|
||||
// An opaque token identifying this challenge request. Clients must generally
|
||||
// submit this token when submitting a challenge response.
|
||||
bytes token = 1;
|
||||
string token = 1;
|
||||
|
||||
// A list of challenge types callers may choose to complete to resolve the
|
||||
// challenge requirement. May be empty, in which case callers cannot resolve
|
||||
|
||||
@@ -14,8 +14,9 @@ import "google/protobuf/descriptor.proto";
|
||||
extend google.protobuf.FieldOptions {
|
||||
/*
|
||||
* Requires a field to have content of non-zero size/length.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
* it's considered to be empty.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set
|
||||
* or has a default value, it's considered to be empty. This does not apply
|
||||
* to fields that are contained in a `oneof`.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
@@ -57,8 +58,10 @@ extend google.protobuf.FieldOptions {
|
||||
|
||||
/*
|
||||
* Requires a size/length of a field to be within certain boundaries.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
* its size considered to be zero.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set
|
||||
* or has a default value, its size considered to be zero. However, if the
|
||||
* field is contained in a `oneof` and is not set, this annotation does not
|
||||
* apply.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
@@ -76,9 +79,11 @@ extend google.protobuf.FieldOptions {
|
||||
optional SizeConstraint size = 70003;
|
||||
|
||||
/*
|
||||
* Requires a size/length of a field to be one of the specified values.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set or has a default value,
|
||||
* its size considered to be zero.
|
||||
* Requires a size/length of a field to be within certain boundaries.
|
||||
* Applies to both `optional` and regular fields, i.e. if the field is not set
|
||||
* or has a default value, its size considered to be zero. However, if the
|
||||
* field is contained in a `oneof` and is not set, this annotation does not
|
||||
* apply.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
@@ -130,7 +135,8 @@ extend google.protobuf.FieldOptions {
|
||||
* Require a value of a message field to be present.
|
||||
*
|
||||
* Applies to both `optional` and regular fields (both of which have explicit
|
||||
* presence for the message type anyways)
|
||||
* presence for the message type anyways). This does not apply to fields that
|
||||
* are contained in a `oneof`.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user