Compare commits

...
Author SHA1 Message Date
Ravi Khadiwala 9dfe51eac4 Forbid linked devices from setting backup-ids 2025-06-18 11:07:52 -05:00
andrew-signal 5de848bf38 Instrument request/response sizes 2025-06-17 11:16:57 -04:00
Ravi Khadiwala 295cedc075 remove experiment configuration for low urgency pushes 2025-06-17 09:43:35 -05:00
Jon Chambers 4f1cab407f Simplify WebSocket authentication failure handling 2025-06-17 10:41:29 -04:00
Ravi Khadiwala 626a7fdad7 Add docs to /v1/donations/redeem-receipt 2025-06-12 17:07:19 -05:00
Jon Chambers 9a1da23bdb Add an isEphemeral dimension to message delivery latency metrics 2025-06-10 17:05:46 -05:00
ravi-signal 4ffd164461 Wire up the direct noise tunnel 2025-06-10 16:56:31 -05:00
Jon Chambers 904cc63a72 Clarify that OutgoingMessageEntity#toEnvelope is a test-only method 2025-06-10 16:55:13 -05:00
Ravi Khadiwala 177c36b0d6 Fix backup metric names and use remote aggregation 2025-06-10 16:54:45 -05:00
Jon Chambers 5fc6bdd478 Add a device capability for sparse post-quantum ratchet (SPQR) 2025-06-10 16:54:30 -05:00
Jon Chambers ca6e5fb0a8 Hide model validation methods in API docs 2025-06-06 16:19:48 -04:00
Jon Chambers 1a7a446150 Regenerate phone number identifiers when regenerating secondary table data 2025-06-05 15:12:33 -04:00
Ameya Lokare 981d929f50 Extend ChannelCircuitBreakerHandler with ChannelOutboundHandlerAdapter
instead of ChannelDuplexHandler
2025-06-05 12:00:21 -05:00
Ravi Khadiwala 4a3eb642c0 Remove unused S3Client 2025-06-05 11:49:03 -05:00
61 changed files with 512 additions and 283 deletions

No files matched your search

+2 -1
View File
@@ -491,7 +491,8 @@ linkDevice:
secret: secret://linkDevice.secret
noiseTunnel:
port: 8443
webSocketPort: 8444
directPort: 8445
tlsKeyStoreFile: /path/to/file.p12
tlsKeyStoreEntryAlias: example.com
tlsKeyStorePassword: secret://noiseTunnel.tlsKeyStorePassword
@@ -43,7 +43,7 @@ import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfigurat
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.NoiseWebSocketTunnelConfiguration;
import org.whispersystems.textsecuregcm.configuration.NoiseTunnelConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.RegistrationServiceClientFactory;
@@ -304,7 +304,7 @@ public class WhisperServerConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private NoiseWebSocketTunnelConfiguration noiseTunnel;
private NoiseTunnelConfiguration noiseTunnel;
@Valid
@NotNull
@@ -514,7 +514,7 @@ public class WhisperServerConfiguration extends Configuration {
return virtualThread;
}
public NoiseWebSocketTunnelConfiguration getNoiseWebSocketTunnelConfiguration() {
public NoiseTunnelConfiguration getNoiseTunnelConfiguration() {
return noiseTunnel;
}
@@ -154,6 +154,7 @@ import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
import org.whispersystems.textsecuregcm.grpc.net.ManagedDefaultEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.ManagedLocalGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.ManagedNioEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.noisedirect.NoiseDirectTunnelServer;
import org.whispersystems.textsecuregcm.grpc.net.websocket.NoiseWebSocketTunnelServer;
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
@@ -270,7 +271,7 @@ import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerF
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
import org.whispersystems.textsecuregcm.workers.RegenerateAccountConstraintDataCommand;
import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
@@ -286,12 +287,10 @@ import org.whispersystems.websocket.setup.WebSocketEnvironment;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.http.crt.AwsCrtHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
public class WhisperServerService extends Application<WhisperServerConfiguration> {
@@ -339,7 +338,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
"Processes scheduled jobs to send notifications to idle devices",
new IdleDeviceNotificationSchedulerFactory()));
bootstrap.addCommand(new RegenerateAccountConstraintDataCommand());
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
}
@Override
@@ -642,7 +641,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
apnSender, fcmSender, accountsManager, 0, 0);
PushNotificationManager pushNotificationManager =
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler, experimentEnrollmentManager);
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
WebSocketConnectionEventManager webSocketConnectionEventManager =
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
@@ -751,12 +750,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.lifecycle().manage(virtualThreadPinEventMonitor);
environment.lifecycle().manage(accountsManager);
final S3Client cdnS3Client = S3Client.builder()
.credentialsProvider(cdnCredentialsProvider)
.region(Region.of(config.getCdnConfiguration().region()))
.httpClientBuilder(AwsCrtHttpClient.builder())
.build();
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
config.getGcpAttachmentsConfiguration().domain(),
config.getGcpAttachmentsConfiguration().email(),
@@ -881,16 +874,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
@Nullable final X509Certificate[] noiseWebSocketTlsCertificateChain;
@Nullable final PrivateKey noiseWebSocketTlsPrivateKey;
if (config.getNoiseWebSocketTunnelConfiguration().tlsKeyStoreFile() != null &&
config.getNoiseWebSocketTunnelConfiguration().tlsKeyStoreEntryAlias() != null &&
config.getNoiseWebSocketTunnelConfiguration().tlsKeyStorePassword() != null) {
if (config.getNoiseTunnelConfiguration().tlsKeyStoreFile() != null &&
config.getNoiseTunnelConfiguration().tlsKeyStoreEntryAlias() != null &&
config.getNoiseTunnelConfiguration().tlsKeyStorePassword() != null) {
try (final FileInputStream websocketNoiseTunnelTlsKeyStoreInputStream = new FileInputStream(config.getNoiseWebSocketTunnelConfiguration().tlsKeyStoreFile())) {
try (final FileInputStream websocketNoiseTunnelTlsKeyStoreInputStream = new FileInputStream(config.getNoiseTunnelConfiguration().tlsKeyStoreFile())) {
final KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(websocketNoiseTunnelTlsKeyStoreInputStream, config.getNoiseWebSocketTunnelConfiguration().tlsKeyStorePassword().value().toCharArray());
keyStore.load(websocketNoiseTunnelTlsKeyStoreInputStream, config.getNoiseTunnelConfiguration().tlsKeyStorePassword().value().toCharArray());
final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(config.getNoiseWebSocketTunnelConfiguration().tlsKeyStoreEntryAlias(),
new KeyStore.PasswordProtection(config.getNoiseWebSocketTunnelConfiguration().tlsKeyStorePassword().value().toCharArray()));
final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(
config.getNoiseTunnelConfiguration().tlsKeyStoreEntryAlias(),
new KeyStore.PasswordProtection(config.getNoiseTunnelConfiguration().tlsKeyStorePassword().value().toCharArray()));
noiseWebSocketTlsCertificateChain =
Arrays.copyOf(privateKeyEntry.getCertificateChain(), privateKeyEntry.getCertificateChain().length, X509Certificate[].class);
@@ -909,27 +903,37 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.allowCoreThreadTimeOut(false)
.build();
final ManagedNioEventLoopGroup noiseWebSocketEventLoopGroup = new ManagedNioEventLoopGroup();
final ManagedNioEventLoopGroup noiseTunnelEventLoopGroup = new ManagedNioEventLoopGroup();
final NoiseWebSocketTunnelServer noiseWebSocketTunnelServer = new NoiseWebSocketTunnelServer(
config.getNoiseWebSocketTunnelConfiguration().port(),
config.getNoiseTunnelConfiguration().webSocketPort(),
noiseWebSocketTlsCertificateChain,
noiseWebSocketTlsPrivateKey,
noiseWebSocketEventLoopGroup,
noiseTunnelEventLoopGroup,
noiseWebSocketDelegatedTaskExecutor,
grpcClientConnectionManager,
clientPublicKeysManager,
config.getNoiseWebSocketTunnelConfiguration().noiseStaticKeyPair(),
config.getNoiseTunnelConfiguration().noiseStaticKeyPair(),
authenticatedGrpcServerAddress,
anonymousGrpcServerAddress,
config.getNoiseWebSocketTunnelConfiguration().recognizedProxySecret().value());
config.getNoiseTunnelConfiguration().recognizedProxySecret().value());
final NoiseDirectTunnelServer noiseDirectTunnelServer = new NoiseDirectTunnelServer(
config.getNoiseTunnelConfiguration().directPort(),
noiseTunnelEventLoopGroup,
grpcClientConnectionManager,
clientPublicKeysManager,
config.getNoiseTunnelConfiguration().noiseStaticKeyPair(),
authenticatedGrpcServerAddress,
anonymousGrpcServerAddress);
environment.lifecycle().manage(localEventLoopGroup);
environment.lifecycle().manage(dnsResolutionEventLoopGroup);
environment.lifecycle().manage(anonymousGrpcServer);
environment.lifecycle().manage(authenticatedGrpcServer);
environment.lifecycle().manage(noiseWebSocketEventLoopGroup);
environment.lifecycle().manage(noiseTunnelEventLoopGroup);
environment.lifecycle().manage(noiseWebSocketTunnelServer);
environment.lifecycle().manage(noiseDirectTunnelServer);
final List<Filter> filters = new ArrayList<>();
filters.add(remoteDeprecationFilter);
@@ -34,6 +34,7 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.util.Util;
@@ -85,6 +86,7 @@ public class BackupAuthManager {
* Store credential requests containing blinded backup-ids for future use.
*
* @param account The account using the backup-id
* @param device The device setting the account backup-id
* @param messagesBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
* message backups
* @param mediaBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
@@ -92,12 +94,17 @@ public class BackupAuthManager {
* @return A future that completes when the credentialRequest has been stored
* @throws RateLimitExceededException If too many backup-ids have been committed
*/
public CompletableFuture<Void> commitBackupId(final Account account,
public CompletableFuture<Void> commitBackupId(
final Account account,
final Device device,
final BackupAuthCredentialRequest messagesBackupCredentialRequest,
final BackupAuthCredentialRequest mediaBackupCredentialRequest) {
if (configuredBackupLevel(account).isEmpty()) {
throw Status.PERMISSION_DENIED.withDescription("Backups not allowed on account").asRuntimeException();
}
if (!device.isPrimary()) {
throw Status.PERMISSION_DENIED.withDescription("Only primary device can set backup-id").asRuntimeException();
}
final byte[] serializedMessageCredentialRequest = messagesBackupCredentialRequest.serialize();
final byte[] serializedMediaCredentialRequest = mediaBackupCredentialRequest.serialize();
@@ -22,6 +22,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
@@ -31,6 +32,7 @@ import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -85,9 +87,9 @@ public class BackupsDb {
private final SecureRandom secureRandom;
private static final String NUM_OBJECTS_SUMMARY_NAME = "numObjects";
private static final String BYTES_USED_SUMMARY_NAME = "bytesUsed";
private static final String BACKUPS_COUNTER_NAME = "backups";
private static final String NUM_OBJECTS_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "numObjects");
private static final String BYTES_USED_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "bytesUsed");
private static final String BACKUPS_COUNTER_NAME = MetricsUtil.name(BackupsDb.class, "backups");
// The backups table
@@ -285,8 +287,17 @@ public class BackupsDb {
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("tier", backupUser.backupLevel().name()));
Metrics.summary(NUM_OBJECTS_SUMMARY_NAME, tags).record(mediaCount);
Metrics.summary(BYTES_USED_SUMMARY_NAME, tags).record(bytesUsed);
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(mediaCount);
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(mediaCount);
// Report that the backup is out of quota if it cannot store a max size media object
final boolean quotaExhausted = bytesUsed >=
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.configuration;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotBlank;
@@ -57,6 +58,7 @@ public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
}
@AssertTrue
@Schema(hidden = true)
public boolean isClientTtlShorterThanRequestedTtl() {
return clientCredentialTtl.compareTo(requestedCredentialTtl) <= 0;
}
@@ -10,12 +10,13 @@ import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public record NoiseWebSocketTunnelConfiguration(@Positive int port,
@Nullable String tlsKeyStoreFile,
@Nullable String tlsKeyStoreEntryAlias,
@Nullable SecretString tlsKeyStorePassword,
@NotNull SecretBytes noiseStaticPrivateKey,
@NotNull SecretString recognizedProxySecret) {
public record NoiseTunnelConfiguration(@Positive int webSocketPort,
@Positive int directPort,
@Nullable String tlsKeyStoreFile,
@Nullable String tlsKeyStoreEntryAlias,
@Nullable SecretString tlsKeyStorePassword,
@NotNull SecretBytes noiseStaticPrivateKey,
@NotNull SecretString recognizedProxySecret) {
public ECKeyPair noiseStaticKeyPair() throws InvalidKeyException {
final ECPrivateKey privateKey = Curve.decodePrivatePoint(noiseStaticPrivateKey().value());
@@ -135,13 +135,14 @@ public class ArchiveController {
""")
@ApiResponse(responseCode = "204", description = "The backup-id was set")
@ApiResponse(responseCode = "400", description = "The provided backup auth credential request was invalid")
@ApiResponse(responseCode = "403", description = "The device did not have permission to set the backup-id. Only the primary device can set the backup-id for an account")
@ApiResponse(responseCode = "429", description = "Rate limited. Too many attempts to change the backup-id have been made")
public CompletionStage<Response> setBackupId(
@Mutable @Auth final AuthenticatedDevice account,
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest) throws RateLimitExceededException {
return this.backupAuthManager
.commitBackupId(account.getAccount(), setBackupIdRequest.messagesBackupAuthCredentialRequest,
.commitBackupId(account.getAccount(), account.getAuthenticatedDevice(),
setBackupIdRequest.messagesBackupAuthCredentialRequest,
setBackupIdRequest.mediaBackupAuthCredentialRequest)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
@@ -6,6 +6,8 @@
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
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;
@@ -70,21 +72,40 @@ public class DonationController {
@Path("/redeem-receipt")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
@Operation(
summary = "Redeem receipt",
description = """
Redeem a receipt acquired from /v1/subscription/{subscriberId}/receipt_credentials to add a badge to the
account. After successful redemption, profile responses will include the corresponding badge (if configured as
visible) until the expiration time on the receipt.
""")
@ApiResponse(responseCode = "200", description = "The receipt was redeemed")
@ApiResponse(responseCode = "400", description = """
The provided presentation or receipt was invalid, or the receipt was already redeemed for a different account. A
specific error message suitable for logging will be included as text/plain body
""")
@ApiResponse(responseCode = "429", description = "Rate limited.")
public CompletionStage<Response> redeemReceipt(
@Mutable @Auth final AuthenticatedDevice auth,
@NotNull @Valid final RedeemReceiptRequest request) {
return CompletableFuture.supplyAsync(() -> {
ReceiptCredentialPresentation receiptCredentialPresentation;
try {
receiptCredentialPresentation = receiptCredentialPresentationFactory.build(
request.getReceiptCredentialPresentation());
receiptCredentialPresentation = receiptCredentialPresentationFactory
.build(request.getReceiptCredentialPresentation());
} catch (InvalidInputException e) {
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST).entity("invalid receipt credential presentation").type(MediaType.TEXT_PLAIN_TYPE).build());
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
.entity("invalid receipt credential presentation")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException e) {
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST).entity("receipt credential presentation verification failed").type(MediaType.TEXT_PLAIN_TYPE).build());
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
.entity("receipt credential presentation verification failed")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
@@ -92,16 +113,19 @@ public class DonationController {
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
if (badgeId == null) {
return CompletableFuture.completedFuture(Response.serverError().entity("server does not recognize the requested receipt level").type(MediaType.TEXT_PLAIN_TYPE).build());
return CompletableFuture.completedFuture(Response.serverError()
.entity("server does not recognize the requested receipt level")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
return redeemedReceiptsManager.put(
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.getAccount().getUuid())
.thenCompose(receiptMatched -> {
if (!receiptMatched) {
return CompletableFuture.completedFuture(
Response.status(Status.BAD_REQUEST).entity("receipt serial is already redeemed")
.type(MediaType.TEXT_PLAIN_TYPE).build());
return CompletableFuture.completedFuture(Response.status(Status.BAD_REQUEST)
.entity("receipt serial is already redeemed")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
return accountsManager.updateAsync(auth.getAccount(), a -> {
@@ -111,7 +135,7 @@ public class DonationController {
}
})
.thenApply(ignored -> Response.ok().build());
});
});
}).thenCompose(Function.identity());
}
@@ -781,6 +781,10 @@ public class MessageController {
"rest",
auth.getAuthenticatedDevice().isPrimary(),
outgoingMessageEntity.urgent(),
// Messages fetched via this endpoint (as opposed to WebSocketConnection) are never ephemeral
// because, by definition, the client doesn't have a "live" connection via which to receive
// ephemeral messages.
false,
userAgent,
clientReleaseManager);
})
@@ -10,6 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Optional;
@@ -137,6 +138,7 @@ public class AccountAttributes {
}
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
}
@@ -76,6 +76,7 @@ public record ChangeNumberRequest(
}
@AssertTrue
@Schema(hidden = true)
public boolean isEachPniRegistrationIdValid() {
return pniRegistrationIds == null || pniRegistrationIds.values().stream().allMatch(RegistrationIdValidator::validRegistrationId);
}
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.protobuf.ByteString;
import com.webauthn4j.converter.jackson.deserializer.json.ByteArrayBase64Deserializer;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import javax.annotation.Nullable;
import jakarta.validation.constraints.NotNull;
@@ -69,6 +70,7 @@ public record IncomingMessage(int type,
}
@AssertTrue
@Schema(hidden = true)
public boolean isValidEnvelopeType() {
if (type() == MessageProtos.Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE ||
MessageProtos.Envelope.Type.forNumber(type()) == null) {
@@ -10,6 +10,7 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
@@ -46,6 +47,7 @@ public record IncomingMessageList(@NotNull
}
@AssertTrue
@Schema(hidden = true)
public boolean hasNoDuplicateRecipients() {
final boolean valid = messages.stream()
.filter(Objects::nonNull)
@@ -54,6 +54,7 @@ public record KeyTransparencySearchRequest(
@Positive long distinguishedTreeHeadSize
) {
@AssertTrue
@Schema(hidden = true)
public boolean isUnidentifiedAccessKeyProvidedWithE164() {
return unidentifiedAccessKey.isPresent() == e164.isPresent();
}
@@ -42,6 +42,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
}
@AssertTrue
@Schema(hidden = true)
public boolean hasExactlyOneMessageDeliveryChannel() {
if (accountAttributes.getFetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.util.Arrays;
import java.util.Objects;
@@ -37,7 +38,8 @@ public record OutgoingMessageEntity(UUID guid,
boolean story,
@Nullable byte[] reportSpamToken) {
public MessageProtos.Envelope toEnvelope() {
@VisibleForTesting
MessageProtos.Envelope toEnvelope() {
final MessageProtos.Envelope.Builder builder = MessageProtos.Envelope.newBuilder()
.setType(MessageProtos.Envelope.Type.forNumber(type()))
.setClientTimestamp(timestamp())
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.entities;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.ws.rs.ClientErrorException;
import java.util.Base64;
@@ -25,6 +26,7 @@ public interface PhoneVerificationRequest {
// for the @AssertTrue to work with bean validation, method name must follow 'isSmth()'/'getSmth()' naming convention
@AssertTrue
@Schema(hidden = true)
default boolean isValid() {
// checking that exactly one of sessionId/recoveryPassword is non-empty
return isNotBlank(sessionId()) ^ (recoveryPassword() != null && recoveryPassword().length > 0);
@@ -7,12 +7,16 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
public class RedeemReceiptRequest {
@Schema(description = "Presentation of a ZK receipt encoded in standard padded base64", implementation = String.class)
private final byte[] receiptCredentialPresentation;
@Schema(description = "If true, the corresponding badge should be visible on the profile")
private final boolean visible;
@Schema(description = "if true, and the new badge is visible, it should be the primary badge on the profile")
private final boolean primary;
@JsonCreator
@@ -111,6 +111,7 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@VisibleForTesting
@AssertTrue
@Schema(hidden = true)
boolean hasExactlyOneMessageDeliveryChannel() {
if (accountAttributes.getFetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
@@ -32,6 +32,7 @@ import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Mono;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@@ -60,9 +61,15 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
BackupAuthCredentialRequest::new,
request.getMediaBackupAuthCredentialRequest().toByteArray());
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return authenticatedAccount()
.flatMap(account -> Mono.fromFuture(
backupAuthManager.commitBackupId(account, messagesCredentialRequest, mediaCredentialRequest)))
.flatMap(account -> {
final Device device = account
.getDevice(authenticatedDevice.deviceId())
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
return Mono.fromFuture(
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest));
})
.thenReturn(SetBackupIdResponse.getDefaultInstance());
}
@@ -20,6 +20,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_DELETE_SYNC -> DeviceCapability.DELETE_SYNC;
case DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION -> DeviceCapability.STORAGE_SERVICE_RECORD_KEY_ROTATION;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Unrecognized device capability").asRuntimeException();
};
}
@@ -31,6 +32,7 @@ public class DeviceCapabilityUtil {
case DELETE_SYNC -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC;
case STORAGE_SERVICE_RECORD_KEY_ROTATION -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION;
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
};
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.limits;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import java.time.Duration;
@@ -15,6 +16,7 @@ public record RateLimiterConfig(int bucketSize, Duration permitRegenerationDurat
}
@AssertTrue
@Schema(hidden = true)
public boolean hasPositiveRegenerationRate() {
try {
return permitRegenerationDuration.toNanos() > 0;
@@ -72,14 +72,16 @@ public final class MessageMetrics {
final String channel,
final boolean isPrimaryDevice,
final boolean isUrgent,
final boolean isEphemeral,
final String userAgent,
final ClientReleaseManager clientReleaseManager) {
final List<Tag> tags = new ArrayList<>(4);
final List<Tag> tags = new ArrayList<>();
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
tags.add(Tag.of("channel", channel));
tags.add(Tag.of("isPrimary", String.valueOf(isPrimaryDevice)));
tags.add(Tag.of("isUrgent", String.valueOf(isUrgent)));
tags.add(Tag.of("isEphemeral", String.valueOf(isEphemeral)));
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
@@ -59,6 +59,10 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
public static final String REQUEST_COUNTER_NAME = MetricsRequestEventListener.REQUEST_COUNTER_NAME;
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricsRequestEventListener.REQUESTS_BY_VERSION_COUNTER_NAME;
@VisibleForTesting
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME;
@VisibleForTesting
static final String REQUEST_BYTES_COUNTER_NAME = MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME;
@VisibleForTesting
static final String URI_INFO_PROPERTY_NAME = MetricsHttpChannelListener.class.getName() + ".uriInfo";
@VisibleForTesting
@@ -141,6 +145,9 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(request.getResponse().getContentCount());
meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(request.getContentRead());
UserAgentTagUtil.getClientVersionTag(requestInfo.userAgent(), clientReleaseManager).ifPresent(
clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(requestInfo.userAgent()))).increment());
@@ -15,8 +15,11 @@ import io.micrometer.core.instrument.Tags;
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.logging.UriInfoUtil;
import org.whispersystems.websocket.WebSocketResourceProvider;
import javax.annotation.Nullable;
import java.util.ArrayList;
@@ -24,14 +27,19 @@ import java.util.List;
import java.util.Optional;
/**
* Gathers and reports request-level metrics.
* Gathers and reports request-level metrics for WebSocket traffic only.
* For HTTP traffic, use {@link MetricsHttpChannelListener}.
*/
public class MetricsRequestEventListener implements RequestEventListener {
private static final Logger logger = LoggerFactory.getLogger(MetricsRequestEventListener.class);
private final ClientReleaseManager clientReleaseManager;
public static final String REQUEST_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "request");
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "requestByVersion");
public static final String RESPONSE_BYTES_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "responseBytes");
public static final String REQUEST_BYTES_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "requestBytes");
@VisibleForTesting
static final String PATH_TAG = "path";
@@ -50,6 +58,10 @@ public class MetricsRequestEventListener implements RequestEventListener {
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
if (trafficSource == TrafficSource.HTTP) {
logger.warn("Use {} for HTTP traffic", MetricsHttpChannelListener.class.getName());
}
}
@VisibleForTesting
@@ -85,6 +97,18 @@ public class MetricsRequestEventListener implements RequestEventListener {
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.REQUEST_LENGTH_PROPERTY))
.filter(Integer.class::isInstance)
.map(Integer.class::cast)
.filter(bytes -> bytes >= 0)
.ifPresent(bytes -> meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(bytes));
Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.RESPONSE_LENGTH_PROPERTY))
.filter(Integer.class::isInstance)
.map(Integer.class::cast)
.filter(bytes -> bytes >= 0)
.ifPresent(bytes -> meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(bytes));
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(userAgent)))
@@ -17,7 +17,6 @@ import java.util.function.BiConsumer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -29,9 +28,6 @@ public class PushNotificationManager {
private final APNSender apnSender;
private final FcmSender fcmSender;
private final PushNotificationScheduler pushNotificationScheduler;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
public static final String SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT = "scheduleLowUregencyFcmPush";
private static final String SENT_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "sentPushNotification");
private static final String FAILED_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "failedPushNotification");
@@ -42,14 +38,12 @@ public class PushNotificationManager {
public PushNotificationManager(final AccountsManager accountsManager,
final APNSender apnSender,
final FcmSender fcmSender,
final PushNotificationScheduler pushNotificationScheduler,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
final PushNotificationScheduler pushNotificationScheduler) {
this.accountsManager = accountsManager;
this.apnSender = apnSender;
this.fcmSender = fcmSender;
this.pushNotificationScheduler = pushNotificationScheduler;
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
public CompletableFuture<Optional<SendPushNotificationResult>> sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
@@ -107,7 +101,7 @@ public class PushNotificationManager {
@VisibleForTesting
CompletableFuture<Optional<SendPushNotificationResult>> sendNotification(final PushNotification pushNotification) {
if (shouldScheduleNotification(pushNotification)) {
if (!pushNotification.urgent()) {
// Schedule a notification for some time in the future (possibly even now!) rather than sending a notification
// directly
return pushNotificationScheduler
@@ -156,16 +150,6 @@ public class PushNotificationManager {
.thenApply(Optional::of);
}
private boolean shouldScheduleNotification(final PushNotification pushNotification) {
return !pushNotification.urgent() && switch (pushNotification.tokenType()) {
// APNs imposes a per-device limit on background push notifications
case APN -> true;
case FCM -> experimentEnrollmentManager.isEnrolled(
pushNotification.destination().getUuid(),
SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT);
};
}
private static <T> BiConsumer<T, Throwable> logErrors() {
return (ignored, throwable) -> {
if (throwable != null) {
@@ -19,8 +19,8 @@ import io.lettuce.core.protocol.RedisCommand;
import io.lettuce.core.resource.NettyCustomizer;
import io.micrometer.core.instrument.Tags;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import java.net.SocketAddress;
import java.util.Collection;
@@ -120,7 +120,7 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
channel.pipeline().addBefore(commandHandlerName, null, channelCircuitBreakerHandler);
}
static final class ChannelCircuitBreakerHandler extends ChannelDuplexHandler {
static final class ChannelCircuitBreakerHandler extends ChannelOutboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(ChannelCircuitBreakerHandler.class);
@@ -1472,7 +1472,7 @@ public class Accounts {
.build();
}
public CompletableFuture<Void> regenerateConstraints(final Account account) {
CompletableFuture<Void> regenerateConstraints(final Account account) {
final List<CompletableFuture<?>> constraintFutures = new ArrayList<>();
constraintFutures.add(writeConstraint(phoneNumberConstraintTableName,
@@ -12,7 +12,8 @@ public enum DeviceCapability {
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALL_DEVICES, true, true),
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true);
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true);
public enum AccountCapabilityMode {
/**
@@ -0,0 +1,37 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.concurrent.CompletableFuture;
/**
* The DynamoDB recovery manager regenerates data for secondary tables in a disaster recovery scenario. In a disaster
* recovery scenario, there is no guarantee that table backups will be consistent, and so we need to derive or update
* some tables from a "core" data source to ensure consistency.
*/
public class DynamoDbRecoveryManager {
private final Accounts accounts;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
public DynamoDbRecoveryManager(final Accounts accounts, final PhoneNumberIdentifiers phoneNumberIdentifiers) {
this.accounts = accounts;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
}
/**
* Regenerates secondary data (i.e. uniqueness constraints) for a given account.
*
* @param account the account for which to regenerate secondary data
*
* @return a future that completes when secondary for the given account has been regenerated
*/
public CompletableFuture<Void> regenerateData(final Account account) {
return CompletableFuture.allOf(
accounts.regenerateConstraints(account),
phoneNumberIdentifiers.regeneratePhoneNumberIdentifierMappings(account));
}
}
@@ -244,11 +244,8 @@ public class MessagePersister implements Managed {
} while (!messages.isEmpty());
final boolean inSkipExperiment = device.getGcmId() != null && experimentEnrollmentManager.isEnrolled(
accountUuid,
PushNotificationManager.SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT);
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
.tags(Tags.of(platformTag).and("lowUrgencySkip", Boolean.toString(inSkipExperiment)))
.tags(Tags.of(platformTag))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(messageCount);
@@ -10,33 +10,24 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
@@ -93,7 +84,7 @@ public class PhoneNumberIdentifiers {
* UUID was not previously assigned as a PNI by {@link #getPhoneNumberIdentifier(String)}, the
* returned list will be empty.
*
* @param UUID a phone number identifier
* @param phoneNumberIdentifier a phone number identifier
* @return the list of all e164s associated with the given phone number identifier
*/
public CompletableFuture<List<String>> getPhoneNumber(final UUID phoneNumberIdentifier) {
@@ -110,12 +101,9 @@ public class PhoneNumberIdentifiers {
":pni", AttributeValues.fromUUID(phoneNumberIdentifier)
))
.build())
.thenApply(response -> {
return response.items().stream().map(item -> item.get(KEY_E164).s()).toList();
});
.thenApply(response -> response.items().stream().map(item -> item.get(KEY_E164).s()).toList());
}
@VisibleForTesting
static <T, E extends Exception> CompletableFuture<T> retry(
final int numRetries, final Class<E> exceptionToRetry, final Supplier<CompletableFuture<T>> supplier) {
@@ -256,4 +244,9 @@ public class PhoneNumberIdentifiers {
item -> AttributeValues.getUUID(item, ATTR_PHONE_NUMBER_IDENTIFIER, null))))
.whenComplete((ignored, throwable) -> sample.stop(GET_PNI_TIMER));
}
CompletableFuture<Void> regeneratePhoneNumberIdentifierMappings(final Account account) {
return setPni(account.getNumber(), Util.getAlternateForms(account.getNumber()), account.getIdentifier(IdentityType.PNI))
.thenRun(Util.NOOP);
}
}
@@ -13,7 +13,7 @@ import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.websocket.ReusableAuth;
import org.whispersystems.websocket.auth.AuthenticationException;
import org.whispersystems.websocket.auth.InvalidCredentialsException;
import org.whispersystems.websocket.auth.PrincipalSupplier;
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
@@ -22,7 +22,6 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
private static final ReusableAuth<AuthenticatedDevice> CREDENTIALS_NOT_PRESENTED = ReusableAuth.anonymous();
private static final ReusableAuth<AuthenticatedDevice> INVALID_CREDENTIALS_PRESENTED = ReusableAuth.invalid();
private final AccountAuthenticator accountAuthenticator;
private final PrincipalSupplier<AuthenticatedDevice> principalSupplier;
@@ -34,23 +33,17 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
@Override
public ReusableAuth<AuthenticatedDevice> authenticate(final UpgradeRequest request)
throws AuthenticationException {
try {
return authenticatedAccountFromHeaderAuth(request.getHeader(HttpHeaders.AUTHORIZATION));
} catch (final Exception e) {
// this will be handled and logged upstream
// the most likely exception is a transient error connecting to account storage
throw new AuthenticationException(e);
}
}
throws InvalidCredentialsException {
@Nullable final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader) {
if (authHeader == null) {
return CREDENTIALS_NOT_PRESENTED;
}
return basicCredentialsFromAuthHeader(authHeader)
.flatMap(accountAuthenticator::authenticate)
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
.orElse(INVALID_CREDENTIALS_PRESENTED);
.orElseThrow(InvalidCredentialsException::new);
}
}
@@ -255,6 +255,7 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
"websocket",
auth.getAuthenticatedDevice().isPrimary(),
message.getUrgent(),
message.getEphemeral(),
client.getUserAgent(),
clientReleaseManager);
}
@@ -337,13 +338,8 @@ public class WebSocketConnection implements WebSocketConnectionEventListener {
// Cleared the queue! Send a queue empty message if we need to
consecutiveRetries.set(0);
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
final boolean inSkipExperiment = auth.getAuthenticatedDevice().getGcmId() != null && experimentEnrollmentManager.isEnrolled(
auth.getAccount().getUuid(),
PushNotificationManager.SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT);
final Tags tags = Tags
.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()))
.and("lowUrgencySkip", Boolean.toString(inSkipExperiment));
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
final long drainDuration = System.currentTimeMillis() - queueDrainStartTime.get();
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(sentMessageCounter.sum());
@@ -33,15 +33,14 @@ import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.push.APNSender;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -52,6 +51,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeys;
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.DynamoDbRecoveryManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesCache;
@@ -77,7 +77,6 @@ import software.amazon.awssdk.services.s3.S3AsyncClient;
* Construct utilities commonly used by worker commands
*/
record CommandDependencies(
Accounts accounts,
AccountsManager accountsManager,
ProfilesManager profilesManager,
ReportMessageManager reportMessageManager,
@@ -97,7 +96,8 @@ record CommandDependencies(
IssuedReceiptsManager issuedReceiptsManager,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
DynamoDbAsyncClient dynamoDbAsyncClient,
PhoneNumberIdentifiers phoneNumberIdentifiers) {
PhoneNumberIdentifiers phoneNumberIdentifiers,
DynamoDbRecoveryManager dynamoDbRecoveryManager) {
static CommandDependencies build(
final String name,
@@ -117,9 +117,6 @@ record CommandDependencies(
new DynamicConfigurationManager<>(
configuration.getDynamicConfig().build(awsCredentialsProvider, dynamicConfigurationExecutor), DynamicConfiguration.class);
dynamicConfigurationManager.start();
final ExperimentEnrollmentManager experimentEnrollmentManager =
new ExperimentEnrollmentManager(dynamicConfigurationManager);
final ClientResources.Builder redisClientResourcesBuilder = ClientResources.builder();
FaultTolerantRedisClusterClient cacheCluster = configuration.getCacheClusterConfiguration()
@@ -285,7 +282,7 @@ record CommandDependencies(
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
apnSender, fcmSender, accountsManager, 0, 0);
PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager,
apnSender, fcmSender, pushNotificationScheduler, experimentEnrollmentManager);
apnSender, fcmSender, pushNotificationScheduler);
PushNotificationExperimentSamples pushNotificationExperimentSamples =
new PushNotificationExperimentSamples(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
@@ -294,13 +291,15 @@ record CommandDependencies(
WebSocketConnectionEventManager webSocketConnectionEventManager =
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
final DynamoDbRecoveryManager dynamoDbRecoveryManager =
new DynamoDbRecoveryManager(accounts, phoneNumberIdentifiers);
environment.lifecycle().manage(apnSender);
environment.lifecycle().manage(disconnectionRequestManager);
environment.lifecycle().manage(webSocketConnectionEventManager);
environment.lifecycle().manage(new ManagedAwsCrt());
return new CommandDependencies(
accounts,
accountsManager,
profilesManager,
reportMessageManager,
@@ -320,7 +319,8 @@ record CommandDependencies(
issuedReceiptsManager,
dynamicConfigurationManager,
dynamoDbAsyncClient,
phoneNumberIdentifiers
phoneNumberIdentifiers,
dynamoDbRecoveryManager
);
}
@@ -12,12 +12,12 @@ import java.time.Duration;
import net.sourceforge.argparse4j.inf.Subparser;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.DynamoDbRecoveryManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
public class RegenerateAccountConstraintDataCommand extends AbstractSinglePassCrawlAccountsCommand {
public class RegenerateSecondaryDynamoDbTableDataCommand extends AbstractSinglePassCrawlAccountsCommand {
@VisibleForTesting
static final String DRY_RUN_ARGUMENT = "dry-run";
@@ -29,10 +29,10 @@ public class RegenerateAccountConstraintDataCommand extends AbstractSinglePassCr
static final String RETRIES_ARGUMENT = "retries";
private static final String PROCESSED_ACCOUNTS_COUNTER_NAME =
MetricsUtil.name(RegenerateAccountConstraintDataCommand.class, "processedAccounts");
MetricsUtil.name(RegenerateSecondaryDynamoDbTableDataCommand.class, "processedAccounts");
public RegenerateAccountConstraintDataCommand() {
super("regenerate-account-constraint-data", "Regenerates account constraint data from a core account table");
public RegenerateSecondaryDynamoDbTableDataCommand() {
super("regenerate-secondary-dynamodb-table-data", "Regenerates secondary DynamoDB table data from core tables");
}
@Override
@@ -65,7 +65,7 @@ public class RegenerateAccountConstraintDataCommand extends AbstractSinglePassCr
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
final int maxRetries = getNamespace().getInt(RETRIES_ARGUMENT);
final Accounts accounts = getCommandDependencies().accounts();
final DynamoDbRecoveryManager dynamoDbRecoveryManager = getCommandDependencies().dynamoDbRecoveryManager();
final Counter processedAccountsCounter = Metrics.counter(PROCESSED_ACCOUNTS_COUNTER_NAME,
"dryRun", String.valueOf(dryRun));
@@ -74,7 +74,7 @@ public class RegenerateAccountConstraintDataCommand extends AbstractSinglePassCr
.doOnNext(ignored -> processedAccountsCounter.increment())
.flatMap(account -> dryRun
? Mono.empty()
: Mono.fromFuture(() -> accounts.regenerateConstraints(account))
: Mono.fromFuture(() -> dynamoDbRecoveryManager.regenerateData(account))
.retryWhen(Retry.backoff(maxRetries, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4))
.onRetryExhaustedThrow((spec, rs) -> rs.failure())),
maxConcurrency)
@@ -101,6 +101,7 @@ enum DeviceCapability {
reserved 4;
DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION = 5;
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
}
message ZkCredential {
@@ -61,6 +61,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.tests.util.ExperimentHelper;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
@@ -119,7 +120,7 @@ public class BackupAuthManagerTest {
final BackupAuthCredentialRequest messagesCredentialRequest = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
final BackupAuthCredentialRequest mediaCredentialRequest = backupAuthTestUtil.getRequest(mediaBackupKey, aci);
authManager.commitBackupId(account, messagesCredentialRequest, mediaCredentialRequest).join();
authManager.commitBackupId(account, primaryDevice(), messagesCredentialRequest, mediaCredentialRequest).join();
verify(account).setBackupCredentialRequests(messagesCredentialRequest.serialize(), mediaCredentialRequest.serialize());
}
@@ -135,6 +136,7 @@ public class BackupAuthManagerTest {
final ThrowableAssert.ThrowingCallable commit = () ->
authManager.commitBackupId(account,
primaryDevice(),
backupAuthTestUtil.getRequest(messagesBackupKey, aci),
backupAuthTestUtil.getRequest(mediaBackupKey, aci)).join();
if (backupLevel == null) {
@@ -147,6 +149,24 @@ public class BackupAuthManagerTest {
}
}
@Test
void commitRequiresPrimary() {
final BackupAuthManager authManager = create(BackupLevel.FREE);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
final ThrowableAssert.ThrowingCallable commit = () ->
authManager.commitBackupId(account,
linkedDevice(),
backupAuthTestUtil.getRequest(messagesBackupKey, aci),
backupAuthTestUtil.getRequest(mediaBackupKey, aci)).join();
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(commit)
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.PERMISSION_DENIED);
}
@CartesianTest
void getBackupAuthCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
@CartesianTest.Enum final BackupCredentialType credentialType) {
@@ -504,7 +524,7 @@ public class BackupAuthManagerTest {
: storedMediaCredential;
final boolean expectRateLimit = (changeMedia || changeMessage) && rateLimitBackupId;
final CompletableFuture<Void> future = authManager.commitBackupId(account, newMessagesCredential, newMediaCredential);
final CompletableFuture<Void> future = authManager.commitBackupId(account, primaryDevice(), newMessagesCredential, newMediaCredential);
if (expectRateLimit) {
CompletableFutureTestUtil.assertFailsWithCause(RateLimitExceededException.class, future);
} else {
@@ -538,7 +558,7 @@ public class BackupAuthManagerTest {
// We should get rate limited iff we are out of paid media changes and we changed the media backup-id
final boolean expectRateLimit = changeMedia && paid && rateLimitPaidMedia;
final CompletableFuture<Void> future = authManager.commitBackupId(account, newMessagesCredential, newMediaCredential);
final CompletableFuture<Void> future = authManager.commitBackupId(account, primaryDevice(), newMessagesCredential, newMediaCredential);
if (expectRateLimit) {
CompletableFutureTestUtil.assertFailsWithCause(RateLimitExceededException.class, future);
} else {
@@ -562,6 +582,17 @@ public class BackupAuthManagerTest {
return account;
}
private Device primaryDevice() {
final Device device = mock(Device.class);
when(device.isPrimary()).thenReturn(true);
return device;
}
private Device linkedDevice() {
final Device device = mock(Device.class);
when(device.isPrimary()).thenReturn(false);
return device;
}
private static String experimentName(@Nullable BackupLevel backupLevel) {
return switch (backupLevel) {
@@ -157,7 +157,7 @@ public class ArchiveControllerTest {
@Test
public void setBackupId() {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
final Response response = resources.getJerseyTest()
.target("v1/archives/backupid")
@@ -170,7 +170,7 @@ public class ArchiveControllerTest {
assertThat(response.getStatus()).isEqualTo(204);
verify(backupAuthManager).commitBackupId(AuthHelper.VALID_ACCOUNT,
verify(backupAuthManager).commitBackupId(AuthHelper.VALID_ACCOUNT, AuthHelper.VALID_DEVICE,
backupAuthTestUtil.getRequest(messagesBackupKey, aci),
backupAuthTestUtil.getRequest(mediaBackupKey, aci));
}
@@ -275,9 +275,9 @@ public class ArchiveControllerTest {
@MethodSource
public void setBackupIdException(final Exception ex, final boolean sync, final int expectedStatus) {
if (sync) {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenThrow(ex);
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenThrow(ex);
} else {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
}
final Response response = resources.getJerseyTest()
.target("v1/archives/backupid")
@@ -57,6 +57,7 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@@ -69,7 +70,8 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
backupAuthTestUtil.getRequest(mediaBackupKey, AUTHENTICATED_ACI);
final BackupAuthCredentialRequest messagesAuthCredRequest =
backupAuthTestUtil.getRequest(messagesBackupKey, AUTHENTICATED_ACI);
private final Account account = mock(Account.class);
private Account account;
private Device device;
@Mock
private BackupAuthManager backupAuthManager;
@@ -83,14 +85,19 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
@BeforeEach
void setup() {
account = mock(Account.class);
device = mock(Device.class);
when(device.isPrimary()).thenReturn(true);
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(account.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(device));
}
@Test
void setBackupId() {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(backupAuthManager.commitBackupId(any(), any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
authenticatedServiceStub().setBackupId(
SetBackupIdRequest.newBuilder()
@@ -98,7 +105,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
.build());
verify(backupAuthManager).commitBackupId(account, messagesAuthCredRequest, mediaAuthCredRequest);
verify(backupAuthManager).commitBackupId(account, device, messagesAuthCredRequest, mediaAuthCredRequest);
}
@Test
@@ -147,9 +154,10 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
@MethodSource
void setBackupIdException(final Exception ex, final boolean sync, final Status expected) {
if (sync) {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenThrow(ex);
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenThrow(ex);
} else {
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
when(backupAuthManager.commitBackupId(any(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(ex));
}
GrpcTestUtils.assertStatusException(
@@ -435,7 +435,8 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@CartesianTest.Values(booleans = {true, false}) final boolean storage,
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
@CartesianTest.Values(booleans = {true, false}) final boolean deleteSync,
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill) {
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill,
@CartesianTest.Values(booleans = {true, false}) final boolean spqr) {
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
@@ -460,6 +461,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL);
}
if (spqr) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET);
}
final SetCapabilitiesResponse ignored = authenticatedServiceStub().setCapabilities(requestBuilder.build());
final Set<DeviceCapability> expectedCapabilities = new HashSet<>();
@@ -480,6 +485,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
expectedCapabilities.add(DeviceCapability.ATTACHMENT_BACKFILL);
}
if (spqr) {
expectedCapabilities.add(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET);
}
verify(device).setCapabilities(expectedCapabilities);
}
}
@@ -46,6 +46,7 @@ import java.security.Principal;
import java.time.Duration;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -83,7 +84,9 @@ class MetricsHttpChannelListenerIntegrationTest {
private static final TrafficSource TRAFFIC_SOURCE = TrafficSource.HTTP;
private static final MeterRegistry METER_REGISTRY = mock(MeterRegistry.class);
private static final Counter COUNTER = mock(Counter.class);
private static final Counter REQUEST_COUNTER = mock(Counter.class);
private static final Counter RESPONSE_BYTES_COUNTER = mock(Counter.class);
private static final Counter REQUEST_BYTES_COUNTER = mock(Counter.class);
private static final AtomicReference<CountDownLatch> COUNT_DOWN_LATCH_FUTURE_REFERENCE = new AtomicReference<>();
private static final DropwizardAppExtension<Configuration> EXTENSION = new DropwizardAppExtension<>(
@@ -92,7 +95,9 @@ class MetricsHttpChannelListenerIntegrationTest {
@AfterEach
void teardown() {
reset(METER_REGISTRY);
reset(COUNTER);
reset(REQUEST_COUNTER);
reset(RESPONSE_BYTES_COUNTER);
reset(REQUEST_BYTES_COUNTER);
}
@ParameterizedTest
@@ -105,11 +110,13 @@ class MetricsHttpChannelListenerIntegrationTest {
COUNT_DOWN_LATCH_FUTURE_REFERENCE.set(countDownLatch);
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
final Map<String, Counter> counterMap = Map.of(
MetricsHttpChannelListener.REQUEST_COUNTER_NAME, REQUEST_COUNTER,
MetricsHttpChannelListener.RESPONSE_BYTES_COUNTER_NAME, RESPONSE_BYTES_COUNTER,
MetricsHttpChannelListener.REQUEST_BYTES_COUNTER_NAME, REQUEST_BYTES_COUNTER
);
when(METER_REGISTRY.counter(anyString(), any(Iterable.class)))
.thenAnswer(a -> MetricsHttpChannelListener.REQUEST_COUNTER_NAME.equals(a.getArgument(0, String.class))
? COUNTER
: mock(Counter.class))
.thenReturn(COUNTER);
.thenAnswer(a -> counterMap.getOrDefault(a.getArgument(0, String.class), mock(Counter.class)));
Client client = EXTENSION.client();
@@ -141,7 +148,7 @@ class MetricsHttpChannelListenerIntegrationTest {
assertTrue(countDownLatch.await(1000, TimeUnit.MILLISECONDS));
verify(METER_REGISTRY).counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
verify(COUNTER).increment();
verify(REQUEST_COUNTER).increment();
final Iterable<Tag> tagIterable = tagCaptor.getValue();
final Set<Tag> tags = new HashSet<>();
@@ -186,11 +193,13 @@ class MetricsHttpChannelListenerIntegrationTest {
COUNT_DOWN_LATCH_FUTURE_REFERENCE.set(countDownLatch);
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
final Map<String, Counter> counterMap = Map.of(
MetricsHttpChannelListener.REQUEST_COUNTER_NAME, REQUEST_COUNTER,
MetricsHttpChannelListener.RESPONSE_BYTES_COUNTER_NAME, RESPONSE_BYTES_COUNTER,
MetricsHttpChannelListener.REQUEST_BYTES_COUNTER_NAME, REQUEST_BYTES_COUNTER
);
when(METER_REGISTRY.counter(anyString(), any(Iterable.class)))
.thenAnswer(a -> MetricsHttpChannelListener.REQUEST_COUNTER_NAME.equals(a.getArgument(0, String.class))
? COUNTER
: mock(Counter.class))
.thenReturn(COUNTER);
.thenAnswer(a -> counterMap.getOrDefault(a.getArgument(0, String.class), mock(Counter.class)));
client.connect(new WebSocketListener() {
@Override
@@ -203,7 +212,7 @@ class MetricsHttpChannelListenerIntegrationTest {
assertTrue(countDownLatch.await(1000, TimeUnit.MILLISECONDS));
verify(METER_REGISTRY).counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
verify(COUNTER).increment();
verify(REQUEST_COUNTER).increment();
final Iterable<Tag> tagIterable = tagCaptor.getValue();
final Set<Tag> tags = new HashSet<>();
@@ -39,6 +39,8 @@ class MetricsHttpChannelListenerTest {
private MeterRegistry meterRegistry;
private Counter requestCounter;
private Counter requestsByVersionCounter;
private Counter responseBytesCounter;
private Counter requestBytesCounter;
private ClientReleaseManager clientReleaseManager;
private MetricsHttpChannelListener listener;
@@ -47,6 +49,8 @@ class MetricsHttpChannelListenerTest {
meterRegistry = mock(MeterRegistry.class);
requestCounter = mock(Counter.class);
requestsByVersionCounter = mock(Counter.class);
responseBytesCounter = mock(Counter.class);
requestBytesCounter = mock(Counter.class);
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), any(Iterable.class)))
.thenReturn(requestCounter);
@@ -54,6 +58,12 @@ class MetricsHttpChannelListenerTest {
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUESTS_BY_VERSION_COUNTER_NAME), any(Iterable.class)))
.thenReturn(requestsByVersionCounter);
when(meterRegistry.counter(eq(MetricsHttpChannelListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(responseBytesCounter);
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(requestBytesCounter);
clientReleaseManager = mock(ClientReleaseManager.class);
listener = new MetricsHttpChannelListener(meterRegistry, clientReleaseManager, Collections.emptySet());
@@ -76,7 +86,9 @@ class MetricsHttpChannelListenerTest {
final Response response = mock(Response.class);
when(response.getStatus()).thenReturn(statusCode);
when(response.getContentCount()).thenReturn(1024L);
when(request.getResponse()).thenReturn(response);
when(request.getContentRead()).thenReturn(512L);
final ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class);
when(request.getAttribute(MetricsHttpChannelListener.URI_INFO_PROPERTY_NAME)).thenReturn(extendedUriInfo);
when(extendedUriInfo.getMatchedTemplates()).thenReturn(List.of(new UriTemplate(path)));
@@ -87,6 +99,9 @@ class MetricsHttpChannelListenerTest {
verify(requestCounter).increment();
verify(responseBytesCounter).increment(1024L);
verify(requestBytesCounter).increment(512L);
verify(meterRegistry).counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
final Set<Tag> tags = new HashSet<>();
@@ -123,7 +138,9 @@ class MetricsHttpChannelListenerTest {
final Response response = mock(Response.class);
when(response.getStatus()).thenReturn(statusCode);
when(response.getContentCount()).thenReturn(1024L);
when(request.getResponse()).thenReturn(response);
when(request.getContentRead()).thenReturn(512L);
final ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class);
when(request.getAttribute(MetricsHttpChannelListener.URI_INFO_PROPERTY_NAME)).thenReturn(extendedUriInfo);
when(extendedUriInfo.getMatchedTemplates()).thenReturn(List.of(new UriTemplate(path)));
@@ -62,6 +62,8 @@ class MetricsRequestEventListenerTest {
private MeterRegistry meterRegistry;
private Counter counter;
private Counter responseBytesCounter;
private Counter requestBytesCounter;
private MetricsRequestEventListener listener;
private static final TrafficSource TRAFFIC_SOURCE = TrafficSource.HTTP;
@@ -70,6 +72,8 @@ class MetricsRequestEventListenerTest {
void setup() {
meterRegistry = mock(MeterRegistry.class);
counter = mock(Counter.class);
responseBytesCounter = mock(Counter.class);
requestBytesCounter = mock(Counter.class);
final ClientReleaseManager clientReleaseManager = mock(ClientReleaseManager.class);
when(clientReleaseManager.isVersionActive(any(), any())).thenReturn(false);
@@ -91,6 +95,8 @@ class MetricsRequestEventListenerTest {
when(request.getMethod()).thenReturn(method);
when(request.getRequestHeader(HttpHeaders.USER_AGENT)).thenReturn(
Collections.singletonList("Signal-Android/7.6.2 Android/34 libsignal/0.46.0"));
when(request.getProperty(WebSocketResourceProvider.REQUEST_LENGTH_PROPERTY)).thenReturn(512);
when(request.getProperty(WebSocketResourceProvider.RESPONSE_LENGTH_PROPERTY)).thenReturn(1024);
final ContainerResponse response = mock(ContainerResponse.class);
when(response.getStatus()).thenReturn(statusCode);
@@ -104,10 +110,17 @@ class MetricsRequestEventListenerTest {
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class)))
.thenReturn(counter);
when(meterRegistry.counter(eq(MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(responseBytesCounter);
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(requestBytesCounter);
listener.onEvent(event);
verify(meterRegistry).counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), tagCaptor.capture());
verify(counter).increment();
verify(responseBytesCounter).increment(1024L);
verify(requestBytesCounter).increment(512L);
final Iterable<Tag> tagIterable = tagCaptor.getValue();
final Set<Tag> tags = new HashSet<>();
@@ -155,6 +168,10 @@ class MetricsRequestEventListenerTest {
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class)))
.thenReturn(counter);
when(meterRegistry.counter(eq(MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(responseBytesCounter);
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(requestBytesCounter);
provider.onWebSocketConnect(session);
@@ -216,6 +233,10 @@ class MetricsRequestEventListenerTest {
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_COUNTER_NAME), any(Iterable.class))).thenReturn(
counter);
when(meterRegistry.counter(eq(MetricsRequestEventListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(responseBytesCounter);
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
.thenReturn(requestBytesCounter);
provider.onWebSocketConnect(session);
@@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -36,7 +35,6 @@ class PushNotificationManagerTest {
private APNSender apnSender;
private FcmSender fcmSender;
private PushNotificationScheduler pushNotificationScheduler;
private ExperimentEnrollmentManager experimentEnrollmentManager;
private PushNotificationManager pushNotificationManager;
@@ -46,17 +44,15 @@ class PushNotificationManagerTest {
apnSender = mock(APNSender.class);
fcmSender = mock(FcmSender.class);
pushNotificationScheduler = mock(PushNotificationScheduler.class);
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
AccountsHelper.setupMockUpdate(accountsManager);
pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender,
pushNotificationScheduler, experimentEnrollmentManager);
pushNotificationScheduler);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void sendNewMessageNotification(final boolean urgent) throws NotPushRegisteredException {
@Test
void sendNewUrgentMessageNotification() throws NotPushRegisteredException {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
@@ -66,13 +62,30 @@ class PushNotificationManagerTest {
when(device.getGcmId()).thenReturn(deviceToken);
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(fcmSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, urgent);
verify(fcmSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent));
when(fcmSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, true);
verify(fcmSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true));
}
@Test
void sendNewNonUrgentMessageNotification() throws NotPushRegisteredException {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final String deviceToken = "token";
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(device.getGcmId()).thenReturn(deviceToken);
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(pushNotificationScheduler.scheduleBackgroundNotification(any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(null));
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, false);
verify(pushNotificationScheduler).scheduleBackgroundNotification(PushNotification.TokenType.FCM, account, device);
}
@Test
void sendRegistrationChallengeNotification() {
final String deviceToken = "token";
@@ -135,9 +148,8 @@ class PushNotificationManagerTest {
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testSendNotificationFcm(final boolean urgent) {
@Test
void testSendNotificationFcm() {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
@@ -145,7 +157,7 @@ class PushNotificationManagerTest {
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
when(fcmSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
@@ -162,10 +174,9 @@ class PushNotificationManagerTest {
@CartesianTest
void testSendOrScheduleNotification(
@CartesianTest.Enum(PushNotification.TokenType.class) PushNotification.TokenType tokenType,
@CartesianTest.Values(booleans = {false, true}) final boolean urgent,
@CartesianTest.Values(booleans = {false, true}) final boolean inExperiment) {
@CartesianTest.Values(booleans = {false, true}) final boolean urgent) {
final boolean expectSchedule = !urgent && (tokenType == PushNotification.TokenType.APN || inExperiment);
final boolean expectSchedule = !urgent;
final Account account = mock(Account.class);
final Device device = mock(Device.class);
@@ -175,9 +186,6 @@ class PushNotificationManagerTest {
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(experimentEnrollmentManager.isEnrolled(aci, PushNotificationManager.SCHEDULE_LOW_URGENCY_FCM_PUSH_EXPERIMENT))
.thenReturn(inExperiment);
final PushNotification pushNotification = new PushNotification(
"token", tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
@@ -8,12 +8,16 @@ package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
@@ -21,6 +25,7 @@ import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
@@ -200,4 +205,25 @@ class PhoneNumberIdentifiersTest {
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
assertEquals(List.of(number), phoneNumberIdentifiers.getPhoneNumber(pni).join());
}
@Test
void regeneratePhoneNumberIdentifierMappings() {
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
final UUID phoneNumberIdentifier = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getNumber()).thenReturn(newFormatBeninE164);
when(account.getIdentifier(IdentityType.PNI)).thenReturn(phoneNumberIdentifier);
phoneNumberIdentifiers.regeneratePhoneNumberIdentifierMappings(account).join();
assertEquals(phoneNumberIdentifier, phoneNumberIdentifiers.getPhoneNumberIdentifier(newFormatBeninE164).join());
assertEquals(phoneNumberIdentifier, phoneNumberIdentifiers.getPhoneNumberIdentifier(oldFormatBeninE164).join());
assertEquals(Set.of(newFormatBeninE164, oldFormatBeninE164),
new HashSet<>(phoneNumberIdentifiers.getPhoneNumber(phoneNumberIdentifier).join()));
}
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.websocket;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -26,7 +27,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.websocket.ReusableAuth;
import org.whispersystems.websocket.auth.InvalidCredentialsException;
import org.whispersystems.websocket.auth.PrincipalSupplier;
class WebSocketAccountAuthenticatorTest {
@@ -73,10 +74,11 @@ class WebSocketAccountAuthenticatorTest {
accountAuthenticator,
mock(PrincipalSupplier.class));
final ReusableAuth<AuthenticatedDevice> result = webSocketAuthenticator.authenticate(upgradeRequest);
assertEquals(expectAccount, result.ref().isPresent());
assertEquals(expectInvalid, result.invalidCredentialsProvided());
if (expectInvalid) {
assertThrows(InvalidCredentialsException.class, () -> webSocketAuthenticator.authenticate(upgradeRequest));
} else {
assertEquals(expectAccount, webSocketAuthenticator.authenticate(upgradeRequest).ref().isPresent());
}
}
private static Stream<Arguments> testAuthenticate() {
@@ -58,10 +58,10 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.push.WebSocketConnectionEventManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
@@ -151,7 +151,6 @@ class WebSocketConnectionTest {
when(upgradeRequest.getParameterMap()).thenReturn(Map.of());
account = webSocketAuthenticator.authenticate(upgradeRequest);
assertFalse(account.ref().isPresent());
assertFalse(account.invalidCredentialsProvided());
connectListener.onWebSocketConnect(sessionContext);
verify(sessionContext, times(2)).addWebsocketClosedListener(
@@ -64,8 +64,7 @@ class FinishPushNotificationExperimentCommandTest {
new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", "test"));
});
commandDependencies = new CommandDependencies(null,
accountsManager,
commandDependencies = new CommandDependencies(accountsManager,
null,
null,
null,
@@ -84,6 +83,7 @@ class FinishPushNotificationExperimentCommandTest {
null,
null,
null,
null,
null);
//noinspection unchecked
@@ -51,7 +51,6 @@ class NotifyIdleDevicesCommandTest {
null,
null,
null,
null,
messagesManager,
null,
null,
@@ -66,6 +65,7 @@ class NotifyIdleDevicesCommandTest {
null,
null,
null,
null,
null);
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
@@ -19,19 +19,20 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.DynamoDbRecoveryManager;
import reactor.core.publisher.Flux;
class RegenerateAccountConstraintDataCommandTest {
class RegenerateSecondaryDynamoDbTableDataCommandTest {
private Accounts accounts;
private DynamoDbRecoveryManager dynamoDbRecoveryManager;
private static class TestRegenerateAccountConstraintDataCommand extends RegenerateAccountConstraintDataCommand {
private static class TestRegenerateSecondaryDynamoDbTableDataCommand extends RegenerateSecondaryDynamoDbTableDataCommand {
private final CommandDependencies commandDependencies;
private final Namespace namespace;
TestRegenerateAccountConstraintDataCommand(final Accounts accounts, final boolean dryRun) {
commandDependencies = new CommandDependencies(accounts,
TestRegenerateSecondaryDynamoDbTableDataCommand(final DynamoDbRecoveryManager dynamoDbRecoveryManager, final boolean dryRun) {
commandDependencies = new CommandDependencies(null,
null,
null,
null,
@@ -51,12 +52,12 @@ class RegenerateAccountConstraintDataCommandTest {
null,
null,
null,
null);
dynamoDbRecoveryManager);
namespace = new Namespace(Map.of(
RegenerateAccountConstraintDataCommand.DRY_RUN_ARGUMENT, dryRun,
RegenerateAccountConstraintDataCommand.MAX_CONCURRENCY_ARGUMENT, 16,
RegenerateAccountConstraintDataCommand.RETRIES_ARGUMENT, 3));
RegenerateSecondaryDynamoDbTableDataCommand.DRY_RUN_ARGUMENT, dryRun,
RegenerateSecondaryDynamoDbTableDataCommand.MAX_CONCURRENCY_ARGUMENT, 16,
RegenerateSecondaryDynamoDbTableDataCommand.RETRIES_ARGUMENT, 3));
}
@Override
@@ -72,9 +73,9 @@ class RegenerateAccountConstraintDataCommandTest {
@BeforeEach
void setUp() {
accounts = mock(Accounts.class);
dynamoDbRecoveryManager = mock(DynamoDbRecoveryManager.class);
when(accounts.regenerateConstraints(any())).thenReturn(CompletableFuture.completedFuture(null));
when(dynamoDbRecoveryManager.regenerateData(any())).thenReturn(CompletableFuture.completedFuture(null));
}
@ParameterizedTest
@@ -82,15 +83,15 @@ class RegenerateAccountConstraintDataCommandTest {
void crawlAccounts(final boolean dryRun) {
final Account account = mock(Account.class);
final RegenerateAccountConstraintDataCommand regenerateAccountConstraintDataCommand =
new TestRegenerateAccountConstraintDataCommand(accounts, dryRun);
final RegenerateSecondaryDynamoDbTableDataCommand regenerateSecondaryDynamoDbTableDataCommand =
new TestRegenerateSecondaryDynamoDbTableDataCommand(dynamoDbRecoveryManager, dryRun);
regenerateAccountConstraintDataCommand.crawlAccounts(Flux.just(account));
regenerateSecondaryDynamoDbTableDataCommand.crawlAccounts(Flux.just(account));
if (!dryRun) {
verify(accounts).regenerateConstraints(account);
verify(dynamoDbRecoveryManager).regenerateData(account);
}
verifyNoMoreInteractions(accounts);
verifyNoMoreInteractions(dynamoDbRecoveryManager);
}
}
@@ -64,7 +64,6 @@ class StartPushNotificationExperimentCommandTest {
null,
null,
null,
null,
pushNotificationExperimentSamples,
null,
null,
@@ -73,6 +72,7 @@ class StartPushNotificationExperimentCommandTest {
null,
null,
null,
null,
null);
}
+2 -1
View File
@@ -485,7 +485,8 @@ linkDevice:
secret: secret://linkDevice.secret
noiseTunnel:
port: 8443
webSocketPort: 8444
directPort: 8445
noiseStaticPrivateKey: secret://noiseTunnel.noiseStaticPrivateKey
recognizedProxySecret: secret://noiseTunnel.recognizedProxySecret
@@ -59,14 +59,6 @@ public abstract sealed class ReusableAuth<T extends Principal> {
*/
public abstract Optional<MutableRef<T>> mutableRef();
public boolean invalidCredentialsProvided() {
return switch (this) {
case Invalid<T> ignored -> true;
case ReusableAuth.Anonymous<T> ignored -> false;
case ReusableAuth.Authenticated<T> ignored-> false;
};
}
/**
* @return A {@link ReusableAuth} indicating no credential were provided
*/
@@ -75,14 +67,6 @@ public abstract sealed class ReusableAuth<T extends Principal> {
return (ReusableAuth<T>) Anonymous.ANON_RESULT;
}
/**
* @return A {@link ReusableAuth} indicating that invalid credentials were provided
*/
public static <T extends Principal> ReusableAuth<T> invalid() {
//noinspection unchecked
return (ReusableAuth<T>) Invalid.INVALID_RESULT;
}
/**
* Create a successfully authenticated {@link ReusableAuth}
*
@@ -96,23 +80,6 @@ public abstract sealed class ReusableAuth<T extends Principal> {
return new Authenticated<>(principal, principalSupplier);
}
private static final class Invalid<T extends Principal> extends ReusableAuth<T> {
@SuppressWarnings({"rawtypes"})
private static final ReusableAuth INVALID_RESULT = new Invalid();
@Override
public Optional<T> ref() {
return Optional.empty();
}
@Override
public Optional<MutableRef<T>> mutableRef() {
return Optional.empty();
}
}
private static final class Anonymous<T extends Principal> extends ReusableAuth<T> {
@SuppressWarnings({"rawtypes"})
@@ -173,18 +173,32 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
* {@link org.whispersystems.websocket.ReusableAuth.MutableRef} for us to close when the request is finished
*/
public static final String RESOLVED_PRINCIPAL_PROPERTY = WebSocketResourceProvider.class.getName() + ".resolvedPrincipal";
/**
* The property name where request byte count is stored for metrics collection
*/
public static final String REQUEST_LENGTH_PROPERTY = WebSocketResourceProvider.class.getName() + ".requestBytes";
/**
* The property name where response byte count is stored for metrics collection
*/
public static final String RESPONSE_LENGTH_PROPERTY = WebSocketResourceProvider.class.getName() + ".responseBytes";
private void handleRequest(WebSocketRequestMessage requestMessage) {
ContainerRequest containerRequest = new ContainerRequest(null, URI.create(requestMessage.getPath()),
requestMessage.getVerb(), new WebSocketSecurityContext(new ContextPrincipal(context)),
new MapPropertiesDelegate(new HashMap<>()), jerseyHandler.getConfiguration());
containerRequest.headers(getCombinedHeaders(session.getUpgradeRequest().getHeaders(), requestMessage.getHeaders()));
final int requestBytes = requestMessage.getBody().map(body -> body.length).orElse(0);
if (requestMessage.getBody().isPresent()) {
containerRequest.setEntityStream(new ByteArrayInputStream(requestMessage.getBody().get()));
}
containerRequest.setProperty(remoteAddressPropertyName, remoteAddress);
containerRequest.setProperty(REUSABLE_AUTH_PROPERTY, reusableAuth);
containerRequest.setProperty(REQUEST_LENGTH_PROPERTY, requestBytes);
ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
CompletableFuture<ContainerResponse> responseFuture = (CompletableFuture<ContainerResponse>) jerseyHandler.apply(
@@ -203,6 +217,8 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
})
.thenAccept(response -> {
try {
final int responseBytes = responseBody.size();
containerRequest.setProperty(RESPONSE_LENGTH_PROPERTY, responseBytes);
sendResponse(requestMessage, response, responseBody);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -213,6 +229,7 @@ public class WebSocketResourceProvider<T extends Principal> implements WebSocket
logger.warn("Websocket Error: " + requestMessage.getVerb() + " " + requestMessage.getPath() + "\n"
+ requestMessage.getBody(), exception);
try {
containerRequest.setProperty(RESPONSE_LENGTH_PROPERTY, 0);
sendErrorResponse(requestMessage, Response.status(500).build());
} catch (IOException e) {
logger.warn("Failed to send error response", e);
@@ -22,7 +22,7 @@ import org.glassfish.jersey.CommonProperties;
import org.glassfish.jersey.server.ApplicationHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.websocket.auth.AuthenticationException;
import org.whispersystems.websocket.auth.InvalidCredentialsException;
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
import org.whispersystems.websocket.auth.WebsocketAuthValueFactoryProvider;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
@@ -45,7 +45,7 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends Jetty
this.environment = environment;
environment.jersey().register(new WebSocketSessionContextValueFactoryProvider.Binder());
environment.jersey().register(new WebsocketAuthValueFactoryProvider.Binder<T>(principalClass));
environment.jersey().register(new WebsocketAuthValueFactoryProvider.Binder<>(principalClass));
environment.jersey().register(new JacksonMessageBodyProvider(environment.getObjectMapper()));
// Jersey buffers responses (by default up to 8192 bytes) just so it can add a content length to responses. We
@@ -64,17 +64,9 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends Jetty
try {
Optional<WebSocketAuthenticator<T>> authenticator = Optional.ofNullable(environment.getAuthenticator());
final ReusableAuth<T> authenticated;
if (authenticator.isPresent()) {
authenticated = authenticator.get().authenticate(request);
if (authenticated.invalidCredentialsProvided()) {
response.sendForbidden("Unauthorized");
return null;
}
} else {
authenticated = ReusableAuth.anonymous();
}
final ReusableAuth<T> authenticated = authenticator.isPresent()
? authenticator.get().authenticate(request)
: ReusableAuth.anonymous();
Optional.ofNullable(environment.getAuthenticatedWebSocketUpgradeFilter())
.ifPresent(filter -> filter.handleAuthentication(authenticated, request, response));
@@ -87,11 +79,19 @@ public class WebSocketResourceProviderFactory<T extends Principal> extends Jetty
this.environment.getMessageFactory(),
ofNullable(this.environment.getConnectListener()),
this.environment.getIdleTimeout());
} catch (AuthenticationException | IOException e) {
} catch (final InvalidCredentialsException e) {
try {
response.sendForbidden("Unauthorized");
} catch (final IOException ignored) {
}
return null;
} catch (final Exception e) {
// Authentication may fail for non-incorrect-credential reasons (e.g. we couldn't read from the account database).
// If that happens, we don't want to incorrectly tell clients that they provided bad credentials.
logger.warn("Authentication failure", e);
try {
response.sendError(500, "Failure");
} catch (IOException ignored) {
} catch (final IOException ignored) {
}
return null;
}
@@ -1,17 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.websocket.auth;
public class AuthenticationException extends Exception {
public AuthenticationException(String s) {
super(s);
}
public AuthenticationException(Exception e) {
super(e);
}
}
@@ -0,0 +1,12 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.websocket.auth;
public class InvalidCredentialsException extends Exception {
public InvalidCredentialsException() {
super(null, null, true, false);
}
}
@@ -5,10 +5,9 @@
package org.whispersystems.websocket.auth;
import java.security.Principal;
import java.util.Optional;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.whispersystems.websocket.ReusableAuth;
public interface WebSocketAuthenticator<T extends Principal> {
ReusableAuth<T> authenticate(UpgradeRequest request) throws AuthenticationException;
ReusableAuth<T> authenticate(UpgradeRequest request) throws InvalidCredentialsException;
}
@@ -25,7 +25,7 @@ import org.eclipse.jetty.websocket.server.JettyWebSocketServletFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.whispersystems.websocket.auth.AuthenticationException;
import org.whispersystems.websocket.auth.InvalidCredentialsException;
import org.whispersystems.websocket.auth.PrincipalSupplier;
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
import org.whispersystems.websocket.auth.WebSocketAuthenticator;
@@ -55,9 +55,9 @@ public class WebSocketResourceProviderFactoryTest {
}
@Test
void testUnauthorized() throws AuthenticationException, IOException {
void testUnauthorized() throws InvalidCredentialsException, IOException {
when(environment.getAuthenticator()).thenReturn(authenticator);
when(authenticator.authenticate(eq(request))).thenReturn(ReusableAuth.invalid());
when(authenticator.authenticate(eq(request))).thenThrow(new InvalidCredentialsException());
when(environment.jersey()).thenReturn(jerseyEnvironment);
WebSocketResourceProviderFactory<?> factory = new WebSocketResourceProviderFactory<>(environment, Account.class,
@@ -70,7 +70,7 @@ public class WebSocketResourceProviderFactoryTest {
}
@Test
void testValidAuthorization() throws AuthenticationException {
void testValidAuthorization() throws InvalidCredentialsException {
Account account = new Account();
when(environment.getAuthenticator()).thenReturn(authenticator);
@@ -96,9 +96,9 @@ public class WebSocketResourceProviderFactoryTest {
}
@Test
void testErrorAuthorization() throws AuthenticationException, IOException {
void testErrorAuthorization() throws InvalidCredentialsException, IOException {
when(environment.getAuthenticator()).thenReturn(authenticator);
when(authenticator.authenticate(eq(request))).thenThrow(new AuthenticationException("database failure"));
when(authenticator.authenticate(eq(request))).thenThrow(new RuntimeException("database failure"));
when(environment.jersey()).thenReturn(jerseyEnvironment);
WebSocketResourceProviderFactory<Account> factory = new WebSocketResourceProviderFactory<>(environment,
@@ -127,7 +127,7 @@ public class WebSocketResourceProviderFactoryTest {
}
@Test
void testAuthenticatedWebSocketUpgradeFilter() throws AuthenticationException {
void testAuthenticatedWebSocketUpgradeFilter() throws InvalidCredentialsException {
final Account account = new Account();
final ReusableAuth<Account> reusableAuth =
ReusableAuth.authenticated(account, PrincipalSupplier.forImmutablePrincipal());