Compare commits

..
Author SHA1 Message Date
ravi-signal eaabbd5188 Add nested message validation 2026-01-05 16:23:11 -06:00
ravi-signal 9c4047a90b Remove row-based one-time PQ key store 2025-12-10 16:22:03 -06:00
Katherine Yen 33f506a431 Add registration ID to GetPreKeysResponse 2025-12-10 16:21:34 -06:00
Jon Chambers 7fd0cb32f6 Revert "Include client version in the large message counter tags"
This reverts commit 3ac7a41f9b.
2025-12-10 17:21:26 -05:00
ravi-signal fecb032d8f Ignore failures to update cache after a read 2025-12-10 16:21:18 -06:00
Jon Chambers 1913dbf6f9 Update to the latest version of the spam filter 2025-12-10 11:18:36 -05:00
Jon Chambers de09de895b Update to the latest version of the spam filter 2025-12-10 11:03:04 -05:00
sunday 09942b17a0 feat: add static factory for custom S3 endpoint in S3ObjectMonitor for local testing 2025-12-10 10:52:19 -05:00
Jon Chambers 1d74ecf092 Update to the latest version of the spam filter 2025-12-10 09:56:34 -05:00
Jon Chambers 3ac7a41f9b Include client version in the large message counter tags 2025-12-10 09:46:15 -05:00
Jon Chambers e1c901c5cf Increment a counter when we receive large-but-not-disallowed messages 2025-12-10 09:46:15 -05:00
Jon Chambers 9c35ad0722 Introduce RegistrationFraudChecker#checkSendVerificationCodeAttempt 2025-12-10 09:42:29 -05:00
Jon Chambers 5f25b6a412 Use long instead of int for rate limiter permits 2025-12-10 09:41:51 -05:00
Jon Chambers 77d04ccb70 Rename "dynamic rate limiter" to "leaky bucket rate limiter" 2025-12-10 09:29:44 -05:00
Jonathan Klabunde Tomer 504310cc14 handle Logstash markers in otel logs 2025-12-10 09:29:23 -05:00
Jon Chambers 62798229bf Fix a very (survery?) small typo 2025-12-10 09:29:04 -05:00
Jordan Rose 730e0205f8 Update to libsignal v0.86.6 2025-12-05 11:01:38 -05:00
Katherine 31d6ac71a4 Retire creation timestamp from device endpoints 2025-12-05 10:55:20 -05:00
Chris Eager b887d1f7c0 Fix potentially null errorCode in switch 2025-12-05 10:54:58 -05:00
Jon Chambers 92f8623ad8 Update to the latest version of the spam filter 2025-12-04 09:38:39 -05:00
Jon Chambers 7445225906 Update to the latest version of the spam filter 2025-12-03 16:50:27 -05:00
Jon Chambers 0d2bee7599 Update to the latest version of the spam filter 2025-12-03 15:07:06 -05:00
Jon Chambers 78aa81dd56 Pass client-provided route optimization data to registration service 2025-12-03 14:55:43 -05:00
62 changed files with 881 additions and 1098 deletions

No files matched your search

+9 -1
View File
@@ -14,6 +14,14 @@
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>signal-build-artifacts</id>
<name>Signal Build Artifacts</name>
<url>https://build-artifacts.signal.org/libraries/maven</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
@@ -286,7 +294,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.80.3</version>
<version>0.86.6</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
-2
View File
@@ -108,8 +108,6 @@ dynamoDbTables:
tableName: Example_Keys
ecSignedPreKeys:
tableName: Example_EC_Signed_Pre_Keys
pqKeys:
tableName: Example_PQ_Keys
pagedPqKeys:
tableName: Example_PQ_Paged_Keys
pqLastResortKeys:
+1 -1
View File
@@ -205,7 +205,7 @@
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<version>2.19.0-alpha</version>
<version>2.22.0-alpha</version>
<exclusions>
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
<exclusion>
@@ -243,7 +243,6 @@ import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
@@ -469,7 +468,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.build();
KeysManager keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getEcKeys().getTableName()),
new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemKeys().getTableName()),
new PagedSingleUseKEMPreKeyStore(
dynamoDbAsyncClient,
asyncKeysS3Client,
@@ -58,7 +58,6 @@ public class DynamoDbTables {
private final IssuedReceiptsTableConfiguration issuedReceipts;
private final Table ecKeys;
private final Table ecSignedPreKeys;
private final Table kemKeys;
private final Table kemLastResortKeys;
private final Table pagedKemKeys;
private final TableWithExpiration messages;
@@ -87,7 +86,6 @@ public class DynamoDbTables {
@JsonProperty("issuedReceipts") final IssuedReceiptsTableConfiguration issuedReceipts,
@JsonProperty("ecKeys") final Table ecKeys,
@JsonProperty("ecSignedPreKeys") final Table ecSignedPreKeys,
@JsonProperty("pqKeys") final Table kemKeys,
@JsonProperty("pqLastResortKeys") final Table kemLastResortKeys,
@JsonProperty("pagedPqKeys") final Table pagedKemKeys,
@JsonProperty("messages") final TableWithExpiration messages,
@@ -115,7 +113,6 @@ public class DynamoDbTables {
this.issuedReceipts = issuedReceipts;
this.ecKeys = ecKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
this.kemKeys = kemKeys;
this.pagedKemKeys = pagedKemKeys;
this.kemLastResortKeys = kemLastResortKeys;
this.messages = messages;
@@ -199,12 +196,6 @@ public class DynamoDbTables {
return ecSignedPreKeys;
}
@NotNull
@Valid
public Table getKemKeys() {
return kemKeys;
}
@NotNull
@Valid
public Table getPagedKemKeys() {
@@ -7,16 +7,19 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeName;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.s3.S3ObjectMonitor;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import javax.annotation.Nullable;
@JsonTypeName("default")
public record MonitoredS3ObjectConfiguration(
@NotBlank String s3Region,
@NotBlank String s3Bucket,
@NotBlank String objectKey,
@Nullable URI endpointOverride,
Long maxSize,
Duration refreshInterval) implements S3ObjectMonitorFactory {
@@ -36,6 +39,10 @@ public record MonitoredS3ObjectConfiguration(
public S3ObjectMonitor build(final AwsCredentialsProvider awsCredentialsProvider,
final ScheduledExecutorService refreshExecutorService) {
if (endpointOverride != null && !endpointOverride.toString().isEmpty()) {
return new S3ObjectMonitor(awsCredentialsProvider, endpointOverride, s3Region, s3Bucket, objectKey,
maxSize, refreshExecutorService, refreshInterval);
}
return new S3ObjectMonitor(awsCredentialsProvider, s3Region, s3Bucket, objectKey, maxSize, refreshExecutorService,
refreshInterval);
}
@@ -50,7 +50,7 @@ public class CallQualitySurveyController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@RateLimitedByIp(RateLimiters.For.SUBMIT_CALL_QUALITY_SURVERY)
@RateLimitedByIp(RateLimiters.For.SUBMIT_CALL_QUALITY_SURVEY)
public void submitCallQualitySurvey(@Auth final Optional<AuthenticatedDevice> authenticatedDevice,
@RequestBody(description = "A serialized survey response protobuf entity")
@NotNull final byte[] surveyResponse,
@@ -115,9 +115,6 @@ public class DeviceController {
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
private static final String RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME = MetricsUtil.name(DeviceController.class, "recordTransferArchiveUploaded");
private static final String HAS_REGISTRATION_ID_TAG_NAME = "hasRegistrationId";
@VisibleForTesting
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
@@ -537,14 +534,7 @@ public class DeviceController {
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
public CompletionStage<Void> recordTransferArchiveUploaded(@Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
Metrics.counter(RECORD_TRANSFER_ARCHIVE_UPLOADED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
io.micrometer.core.instrument.Tag.of(
HAS_REGISTRATION_ID_TAG_NAME,
String.valueOf(transferArchiveUploadedRequest.destinationDeviceRegistrationId().isPresent()))
)).increment();
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
return rateLimiters.getUploadTransferArchiveLimiter()
.validateAsync(authenticatedDevice.accountIdentifier())
.thenCompose(ignored -> accounts.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
@@ -554,7 +544,6 @@ public class DeviceController {
return accounts.recordTransferArchiveUpload(account,
transferArchiveUploadedRequest.destinationDeviceId(),
transferArchiveUploadedRequest.destinationDeviceCreated().map(Instant::ofEpochMilli),
transferArchiveUploadedRequest.destinationDeviceRegistrationId(),
transferArchiveUploadedRequest.transferArchive());
});
@@ -193,6 +193,8 @@ public class VerificationController {
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber, sourceHost,
accountsManager.getByE164(request.number()).isPresent(),
request.updateVerificationSessionRequest().mcc(),
request.updateVerificationSessionRequest().mnc(),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CancellationException e) {
@@ -532,10 +534,21 @@ public class VerificationController {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(in = ParameterIn.HEADER, description = "Ordered list of languages in which the client prefers to receive SMS or voice verification messages") @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE)
final Optional<String> acceptLanguage,
@NotNull @Valid final VerificationCodeRequest verificationCodeRequest) throws Throwable {
@NotNull @Valid final VerificationCodeRequest verificationCodeRequest,
@Context final ContainerRequestContext requestContext) throws Throwable {
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
final VerificationSession verificationSession;
{
final VerificationSession storedVerificationSession = retrieveVerificationSession(registrationServiceSession);
verificationSession =
registrationFraudChecker.checkSendVerificationCodeAttempt(requestContext, storedVerificationSession,
registrationServiceSession.number())
.updatedSession()
.orElse(storedVerificationSession);
}
if (registrationServiceSession.verified()) {
throw new ClientErrorException(
@@ -21,13 +21,6 @@ public record DeviceInfo(long id,
long lastSeen,
@Deprecated
@Schema(description = """
The time in milliseconds since epoch when the device was linked.
Deprecated in favor of `createdAtCiphertext`.
""", deprecated = true)
long created,
@Schema(description = "The registration ID of the given device.")
int registrationId,
@@ -40,7 +33,7 @@ public record DeviceInfo(long id,
byte[] createdAtCiphertext) {
public static DeviceInfo forDevice(final Device device) {
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getCreated(), device.getRegistrationId(
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getRegistrationId(
IdentityType.ACI), device.getCreatedAtCiphertext());
}
}
@@ -22,15 +22,8 @@ public record TransferArchiveUploadedRequest(
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
byte destinationDeviceId,
@Schema(description = """
The timestamp, in milliseconds since the epoch, at which the destination device was created.
Deprecated in favor of `destinationDeviceRegistrationId`.
""", deprecated = true)
@Deprecated
Optional<@Positive Long> destinationDeviceCreated,
@Schema(description = "The registration ID of the destination device")
Optional<@Min(0) @Max(Device.MAX_REGISTRATION_ID) Integer> destinationDeviceRegistrationId,
@Min(0) @Max(Device.MAX_REGISTRATION_ID) int destinationDeviceRegistrationId,
@NotNull
@Valid
@@ -39,9 +32,4 @@ public record TransferArchiveUploadedRequest(
the upload has failed and the destination device should stop waiting
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
TransferArchiveResult transferArchive) {
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneDisambiguatorProvided() {
return destinationDeviceCreated.isPresent() ^ destinationDeviceRegistrationId.isPresent();
}
}
@@ -35,28 +35,32 @@ class KeysGrpcHelper {
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
return devices
.flatMap(device -> Mono
.fromFuture(keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.map(devicePreKeys -> {
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))
.build());
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build()));
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
return Tuples.of((int) device.getId(), builder.build());
}))
.flatMap(device -> {
final int registrationId = device.getRegistrationId(targetServiceIdentifier.identityType());
return Mono
.fromFuture(keysManager.takeDevicePreKeys(device.getId(), targetServiceIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.map(devicePreKeys -> {
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.ecSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKeyId(devicePreKeys.kemSignedPreKey().keyId())
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature()))
.build())
.setRegistrationId(registrationId);
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build()));
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
return Tuples.of((int) device.getId(), builder.build());
});
})
// If there were no devices with valid prekey bundles in the account, the account is gone
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.collectMap(Tuple2::getT1, Tuple2::getT2)
@@ -15,6 +15,7 @@ import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.StatusException;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValidator;
@@ -81,12 +82,28 @@ public class ValidatingInterceptor implements ServerInterceptor {
for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry: fd.getOptions().getAllFields().entrySet()) {
final Descriptors.FieldDescriptor extensionFieldDescriptor = entry.getKey();
final String extensionName = extensionFieldDescriptor.getFullName();
// first validate the field
final FieldValidator validator = fieldValidators.get(extensionName);
// not all extensions are validators, so `validator` value here could legitimately be `null`
if (validator != null) {
validator.validate(entry.getValue(), fd, msg);
}
}
// Recursively validate the field's value(s) if it is a message or a repeated field
// gRPC's proto deserialization limits nesting to 100 so this has bounded stack usage
if (fd.isRepeated() && msg.getField(fd) instanceof List list) {
// Checking for repeated fields also handles maps, because maps are syntax sugar for repeated MapEntries
// which themselves are Messages that will be recursively descended.
for (final Object o : list) {
validateMessage(o);
}
} else if (fd.hasPresence() && msg.hasField(fd)) {
// If the field has presence information and is present, recursively validate it. Not all fields have
// presence, but we only validate Message type fields anyway, which always have explicit presence.
validateMessage(msg.getField(fd));
}
}
} catch (final StatusException e) {
throw e;
@@ -62,6 +62,6 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
final Clock clock) {
final Supplier<RateLimiterConfig> configResolver =
() -> dynamicConfigurationManager.getConfiguration().getLimits().getOrDefault(descriptor.id(), descriptor.defaultConfig());
return new DynamicRateLimiter(descriptor.id(), configResolver, validateScript, cacheCluster, retryExecutor, clock);
return new LeakyBucketRateLimiter(descriptor.id(), configResolver, validateScript, cacheCluster, retryExecutor, clock);
}
}
@@ -24,7 +24,7 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
public class DynamicRateLimiter implements RateLimiter {
public class LeakyBucketRateLimiter implements RateLimiter {
private final String name;
private final Supplier<RateLimiterConfig> configResolver;
@@ -38,9 +38,20 @@ public class DynamicRateLimiter implements RateLimiter {
private final Clock clock;
private static final String RETRY_NAME = ResilienceUtil.name(DynamicRateLimiter.class);
private static final String RETRY_NAME = ResilienceUtil.name(LeakyBucketRateLimiter.class);
public DynamicRateLimiter(
public LeakyBucketRateLimiter(
final String name,
final RateLimiterConfig rateLimiterConfig,
final ClusterLuaScript validateScript,
final FaultTolerantRedisClusterClient cluster,
final ScheduledExecutorService retryExecutor,
final Clock clock) {
this(name, () -> rateLimiterConfig, validateScript, cluster, retryExecutor, clock);
}
public LeakyBucketRateLimiter(
final String name,
final Supplier<RateLimiterConfig> configResolver,
final ClusterLuaScript validateScript,
@@ -57,7 +68,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public void validate(final String key, final int amount) throws RateLimitExceededException {
public void validate(final String key, final long amount) throws RateLimitExceededException {
final RateLimiterConfig config = config();
try {
final long deficitPermitsAmount = executeValidateScript(config, key, amount, true);
@@ -79,7 +90,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public CompletionStage<Void> validateAsync(final String key, final int amount) {
public CompletionStage<Void> validateAsync(final String key, final long amount) {
final RateLimiterConfig config = config();
return executeValidateScriptAsync(config, key, amount, true)
@@ -106,7 +117,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public boolean hasAvailablePermits(final String key, final int permits) {
public boolean hasAvailablePermits(final String key, final long permits) {
final RateLimiterConfig config = config();
try {
final long deficitPermitsAmount = executeValidateScript(config, key, permits, false);
@@ -121,7 +132,7 @@ public class DynamicRateLimiter implements RateLimiter {
}
@Override
public CompletionStage<Boolean> hasAvailablePermitsAsync(final String key, final int amount) {
public CompletionStage<Boolean> hasAvailablePermitsAsync(final String key, final long amount) {
final RateLimiterConfig config = config();
return executeValidateScriptAsync(config, key, amount, false)
.thenApply(deficitPermitsAmount -> deficitPermitsAmount == 0)
@@ -151,7 +162,7 @@ public class DynamicRateLimiter implements RateLimiter {
return configResolver.get();
}
private long executeValidateScript(final RateLimiterConfig config, final String key, final int amount, final boolean applyChanges) {
private long executeValidateScript(final RateLimiterConfig config, final String key, final long amount, final boolean applyChanges) {
final List<String> keys = List.of(bucketName(name, key));
final List<String> arguments = List.of(
String.valueOf(config.bucketSize()),
@@ -163,7 +174,7 @@ public class DynamicRateLimiter implements RateLimiter {
return (Long) validateScript.execute(keys, arguments);
}
private CompletionStage<Long> executeValidateScriptAsync(final RateLimiterConfig config, final String key, final int amount, final boolean applyChanges) {
private CompletionStage<Long> executeValidateScriptAsync(final RateLimiterConfig config, final String key, final long amount, final boolean applyChanges) {
final List<String> keys = List.of(bucketName(name, key));
final List<String> arguments = List.of(
String.valueOf(config.bucketSize()),
@@ -13,13 +13,13 @@ import reactor.core.publisher.Mono;
public interface RateLimiter {
void validate(String key, int amount) throws RateLimitExceededException;
void validate(String key, long amount) throws RateLimitExceededException;
CompletionStage<Void> validateAsync(String key, int amount);
CompletionStage<Void> validateAsync(String key, long amount);
boolean hasAvailablePermits(String key, int permits);
boolean hasAvailablePermits(String key, long permits);
CompletionStage<Boolean> hasAvailablePermitsAsync(String key, int amount);
CompletionStage<Boolean> hasAvailablePermitsAsync(String key, long amount);
void clear(String key);
@@ -35,7 +35,7 @@ public interface RateLimiter {
validate(accountUuid.toString());
}
default void validate(final UUID accountUuid, final int permits) throws RateLimitExceededException {
default void validate(final UUID accountUuid, final long permits) throws RateLimitExceededException {
validate(accountUuid.toString(), permits);
}
@@ -63,11 +63,11 @@ public interface RateLimiter {
return validateReactive(accountUuid.toString());
}
default boolean hasAvailablePermits(final UUID accountUuid, final int permits) {
default boolean hasAvailablePermits(final UUID accountUuid, final long permits) {
return hasAvailablePermits(accountUuid.toString(), permits);
}
default CompletionStage<Boolean> hasAvailablePermitsAsync(final UUID accountUuid, final int permits) {
default CompletionStage<Boolean> hasAvailablePermitsAsync(final UUID accountUuid, final long permits) {
return hasAvailablePermitsAsync(accountUuid.toString(), permits);
}
@@ -9,7 +9,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import java.time.Duration;
public record RateLimiterConfig(int bucketSize, Duration permitRegenerationDuration, boolean failOpen) {
public record RateLimiterConfig(long bucketSize, Duration permitRegenerationDuration, boolean failOpen) {
public double leakRatePerMillis() {
return 1.0 / (permitRegenerationDuration.toNanos() / 1e6);
@@ -56,7 +56,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
RECORD_DEVICE_TRANSFER_REQUEST("recordDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
WAIT_FOR_DEVICE_TRANSFER_REQUEST("waitForDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
SUBMIT_CALL_QUALITY_SURVERY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true))
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true))
;
private final String id;
@@ -224,6 +224,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
}
public RateLimiter getSubmitCallQualitySurveyLimiter() {
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVERY);
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVEY);
}
}
@@ -33,7 +33,7 @@ public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggi
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
appender.setCaptureCodeAttributes(true);
appender.setCaptureLoggerContext(true);
appender.setCaptureMarkerAttribute(true);
appender.setCaptureLogstashMarkerAttributes(true);
// The installation of an OpenTelemetry configuration happens in
// WhisperServerService (or CommandDependencies), in order to let us tie
@@ -21,9 +21,9 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import kotlin.Pair;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.util.Pair;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
@@ -54,6 +54,7 @@ public class MessageSender {
// Note that these names deliberately reference `MessageController` for metric continuity
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageSender.class, "rejectOversizeMessage");
private static final String OVERSIZE_MESSAGE_WARNING_COUNTER_NAME = name(MessageSender.class, "oversizeMessageWarning");
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageSender.class, "messageContentSize");
private static final String EMPTY_MESSAGE_LIST_COUNTER_NAME = MetricsUtil.name(MessageSender.class, "emptyMessageList");
@@ -69,6 +70,8 @@ public class MessageSender {
@VisibleForTesting
public static final int MAX_MESSAGE_SIZE = (int) DataSize.kibibytes(256).toBytes();
private static final int OVERSIZE_MESSAGE_WARNING_THRESHOLD = (int) DataSize.kibibytes(96).toBytes();
@VisibleForTesting
static final byte NO_EXCLUDED_DEVICE_ID = -1;
@@ -186,7 +189,7 @@ public class MessageSender {
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceId);
final Map<Byte, Integer> registrationIdsByDeviceId = recipient.getDevicesAndRegistrationIds()
.collect(Collectors.toMap(Pair::first, pair -> (int) pair.second()));
.collect(Collectors.toMap(Pair::getFirst, pair -> (int) pair.getSecond()));
getMismatchedDevices(account, serviceIdentifier, registrationIdsByDeviceId, NO_EXCLUDED_DEVICE_ID)
.ifPresent(mismatchedDevices ->
@@ -324,6 +327,14 @@ public class MessageSender {
.register(Metrics.globalRegistry)
.record(contentLength);
if (contentLength > OVERSIZE_MESSAGE_WARNING_THRESHOLD) {
Metrics.counter(OVERSIZE_MESSAGE_WARNING_COUNTER_NAME, Tags.of(platformTag,
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
Tag.of("story", String.valueOf(isStory))))
.increment();
}
if (oversize) {
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(platformTag,
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
@@ -94,7 +94,12 @@ public class RegistrationServiceClient implements Managed {
}
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
final Phonenumber.PhoneNumber phoneNumber, final String sourceHost, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
final Phonenumber.PhoneNumber phoneNumber,
final String sourceHost,
final boolean accountExistsWithPhoneNumber,
@javax.annotation.Nullable final String clientMcc,
@javax.annotation.Nullable final String clientMnc,
final Duration timeout) {
final long e164 = Long.parseLong(
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
@@ -105,6 +110,8 @@ public class RegistrationServiceClient implements Managed {
.setE164(e164)
.setAccountExistsWithE164(accountExistsWithPhoneNumber)
.setRateLimitCollationKey(rateLimitCollationKey)
.setMcc(clientMcc != null ? clientMcc : "")
.setMnc(clientMnc != null ? clientMnc : "")
.build()), callbackExecutor)
.thenApply(response -> switch (response.getResponseCase()) {
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.s3;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
@@ -21,10 +22,13 @@ import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import javax.annotation.Nullable;
/**
* An S3 object monitor watches a specific object in an S3 bucket and notifies a listener if that object changes.
@@ -65,6 +69,29 @@ public class S3ObjectMonitor {
refreshInterval);
}
// construction with s3Endpoint
public S3ObjectMonitor(final AwsCredentialsProvider awsCredentialsProvider,
final URI s3Endpoint,
final String s3Region,
final String s3Bucket,
final String objectKey,
final long maxObjectSize,
final ScheduledExecutorService refreshExecutorService,
final Duration refreshInterval) {
this(S3Client.builder()
.region(Region.of(s3Region))
.credentialsProvider(awsCredentialsProvider)
.endpointOverride(s3Endpoint)
.serviceConfiguration(S3Configuration.builder()
.pathStyleAccessEnabled(true).build())
.build(),
s3Bucket,
objectKey,
maxObjectSize,
refreshExecutorService,
refreshInterval);
}
@VisibleForTesting
S3ObjectMonitor(
final S3Client s3Client,
@@ -11,7 +11,9 @@ import org.whispersystems.textsecuregcm.registration.VerificationSession;
public interface RegistrationFraudChecker {
record VerificationCheck(Optional<VerificationSession> updatedSession, Optional<Float> scoreThreshold) {}
record VerificationCheck(Optional<VerificationSession> updatedSession, Optional<Float> scoreThreshold) {
public static VerificationCheck DEFAULT = new VerificationCheck(Optional.empty(), Optional.empty());
}
/**
* Determine if a registration attempt is suspicious
@@ -20,8 +22,9 @@ public interface RegistrationFraudChecker {
* @param verificationSession The target verification session
* @param e164 The target phone number
* @param request The information to add to the verification session
* @return A SessionUpdate including updates to the verification session that should be persisted to the caller along
* with other constraints to enforce when evaluating the UpdateVerificationSessionRequest.
*
* @return a VerificationCheck including updates to the verification session that should be sent to the caller
* along with other constraints to enforce when evaluating the UpdateVerificationSessionRequest
*/
VerificationCheck checkVerificationAttempt(
final ContainerRequestContext requestContext,
@@ -29,9 +32,38 @@ public interface RegistrationFraudChecker {
final String e164,
final UpdateVerificationSessionRequest request);
/**
* Determine if an attempt to send a verification code is suspicious
*
* @param requestContext The request context for a "send code" attempt
* @param verificationSession The target verification session
* @param e164 The target phone number
*
* @return a VerificationCheck including updates to the verification session that should be sent to the caller
* along with other constraints to enforce when evaluating the request to send a verification code
*/
VerificationCheck checkSendVerificationCodeAttempt(
final ContainerRequestContext requestContext,
final VerificationSession verificationSession,
final String e164);
static RegistrationFraudChecker noop() {
return (ignoredContext, ignoredSession, ignoredE164, ignoredRequest) -> new VerificationCheck(
Optional.empty(),
Optional.empty());
return new RegistrationFraudChecker() {
@Override
public VerificationCheck checkVerificationAttempt(final ContainerRequestContext requestContext,
final VerificationSession verificationSession, final String e164,
final UpdateVerificationSessionRequest request) {
return VerificationCheck.DEFAULT;
}
@Override
public VerificationCheck checkSendVerificationCodeAttempt(final ContainerRequestContext requestContext,
final VerificationSession verificationSession, final String e164) {
return VerificationCheck.DEFAULT;
}
};
}
}
@@ -37,7 +37,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -51,7 +50,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@@ -115,7 +113,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
private static final String COUNTRY_CODE_TAG_NAME = "country";
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class, "timestampRedisKeyCounter");
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class,"registrationIdRedisKeyCounter");
private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class);
@@ -205,14 +202,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private interface DeviceIdentifier {}
private record TimestampDeviceIdentifier(UUID accountIdentifier, byte deviceId, Instant deviceCreationTimestamp)
implements DeviceIdentifier {
}
private record RegistrationIdDeviceIdentifier(UUID accountIdentifier, byte deviceId,
int registrationId) implements DeviceIdentifier {
private record DeviceIdentifier(UUID accountIdentifier, byte deviceId,
int registrationId) {
}
public AccountsManager(final Accounts accounts,
@@ -1319,7 +1310,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Optional<Account> account = resolveFromRedis.get();
if (account.isEmpty()) {
account = resolveFromAccounts.get();
account.ifPresent(this::redisSet);
try {
account.ifPresent(this::redisSet);
} catch (RedisException e) {
logger.warn("Failed to cache retrieved account", e);
}
}
return account;
});
@@ -1337,7 +1332,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.map(accountFromRedis -> CompletableFuture.completedFuture(maybeAccountFromRedis))
.orElseGet(() -> resolveFromAccounts.get()
.thenCompose(maybeAccountFromAccounts -> maybeAccountFromAccounts
.map(account -> redisSetAsync(account).thenApply(ignored -> maybeAccountFromAccounts))
.map(account -> redisSetAsync(account)
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
logger.warn("Failed to cache retrieved account", e);
return null;
}))
.thenApply(ignored -> maybeAccountFromAccounts))
.orElseGet(() -> CompletableFuture.completedFuture(maybeAccountFromAccounts)))))
.whenComplete((ignored, throwable) -> sample.stop(overallTimer));
}
@@ -1352,7 +1352,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
logger.warn("Deserialization error", e);
return Optional.empty();
} catch (RedisException e) {
logger.warn("Redis failure", e);
logger.warn("Failed fetching account from cache by secondary key", e);
return Optional.empty();
}
});
@@ -1384,7 +1384,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return parseAccountJson(json, uuid);
} catch (final RedisException e) {
logger.warn("Redis failure", e);
logger.warn("Failed to retrieve account from cache", e);
return Optional.empty();
}
});
@@ -1469,21 +1469,14 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
linkDeviceTokenIdentifier, getLinkedDeviceKey(linkDeviceTokenIdentifier), timeout, this::handleDeviceAdded);
return deviceAdded.thenCompose(maybeDeviceInfo -> maybeDeviceInfo.map(deviceInfo -> {
// The device finished linking, we now want to make sure the client has fetched messages that could
// have come in before the device's mailbox was set up.
// The device finished linking, we now want to make sure the primary client has fetched messages that could
// have come in before the linked device's mailbox was set up. This avoids a race where the linked device
// misses out on messages that were sent before its mailbox was set up but received by the primary *after*
// creating its backup for the linked device.
// A worst case estimate of the wall clock time at which the linked device was added to the account record
Instant deviceLinked = Instant.ofEpochMilli(deviceInfo.created()).plus(MAX_SERVER_CLOCK_DRIFT);
Instant now = clock.instant();
// We know at `now` the device finished linking, so if we waited for all the messages before now it would be
// sufficient. However, now might be much later that the device was linked, so we don't want to force
// the client to wait for messages that are past our worst case estimate of when the device was linked
Instant messageEpoch = Collections.min(List.of(deviceLinked, now));
// We assume that any message with a timestamp after the messageEpoch made it into the linked device's queues
return waitForPreLinkMessagesToBeFetched(accountIdentifier, linkingDevice, deviceInfo, messageEpoch, deadline);
// We know the device finished linking at the current time, so waiting for all messages
// before now is sufficient.
return waitForPreLinkMessagesToBeFetched(accountIdentifier, linkingDevice, deviceInfo, clock.instant(), deadline);
})
.orElseGet(() -> CompletableFuture.completedFuture(maybeDeviceInfo)));
}
@@ -1547,59 +1540,24 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
final DeviceIdentifier timestampDeviceIdentifier = new TimestampDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
final String timestampTransferArchiveKey = getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), Instant.ofEpochMilli(device.getCreated()));
final DeviceIdentifier registrationIdDeviceIdentifier = new RegistrationIdDeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final DeviceIdentifier deviceIdentifier = new DeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final CompletableFuture<Optional<TransferArchiveResult>> timestampFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
timestampDeviceIdentifier,
timestampTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
final CompletableFuture<Optional<TransferArchiveResult>> registrationIdFuture = waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
registrationIdDeviceIdentifier,
return waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
deviceIdentifier,
registrationIdTransferArchiveKey,
timeout,
this::handleTransferArchiveAdded);
return firstSuccessfulTransferArchiveFuture(List.of(timestampFuture, registrationIdFuture));
}
@VisibleForTesting
static CompletableFuture<Optional<TransferArchiveResult>> firstSuccessfulTransferArchiveFuture(
final List<CompletableFuture<Optional<TransferArchiveResult>>> futures) {
final CompletableFuture<Optional<TransferArchiveResult>> result = new CompletableFuture<>();
final AtomicInteger remaining = new AtomicInteger(futures.size());
for (CompletableFuture<Optional<TransferArchiveResult>> future : futures) {
future.whenComplete((value, _) -> {
if (value.isPresent()) {
result.complete(value);
} else if (remaining.decrementAndGet() == 0) {
result.complete(Optional.empty());
}
});
}
return result;
}
public CompletableFuture<Void> recordTransferArchiveUpload(final Account account,
final byte destinationDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Instant> destinationDeviceCreationTimestamp,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Integer> maybeRegistrationId,
final int registrationId,
final TransferArchiveResult transferArchiveResult) {
try {
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
final String key = destinationDeviceCreationTimestamp
.map(timestamp -> getTimestampTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, timestamp))
.orElseGet(() -> maybeRegistrationId
.map(registrationId -> getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId))
// We validate the request object so this should never happen
.orElseThrow(() -> new AssertionError("No creation timestamp or registration ID provided")));
final String key = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId);
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection -> connection.async()
@@ -1622,16 +1580,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
private static String getTimestampTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final Instant destinationDeviceCreationTimestamp) {
Metrics.counter(TIMESTAMP_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME).increment();
return TRANSFER_ARCHIVE_PREFIX + accountIdentifier.toString() +
":" + destinationDeviceId +
":" + destinationDeviceCreationTimestamp.toEpochMilli();
}
private static String getRegistrationIdTransferArchiveKey(final UUID accountIdentifier,
final byte destinationDeviceId,
final int registrationId) {
@@ -1734,8 +1682,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final String[] deviceIdentifierComponents =
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 4);
if (deviceIdentifierComponents.length != 3 && deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count");
if (deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count: {}",
deviceIdentifierComponents.length);
return;
}
@@ -1745,24 +1694,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final UUID accountIdentifier = UUID.fromString(deviceIdentifierComponents[0]);
final byte deviceId = Byte.parseByte(deviceIdentifierComponents[1]);
if (deviceIdentifierComponents.length == 3) {
// Parse the old transfer archive Redis key format
final Instant deviceCreationTimestamp = Instant.ofEpochMilli(Long.parseLong(deviceIdentifierComponents[2]));
deviceIdentifier = new TimestampDeviceIdentifier(accountIdentifier, deviceId, deviceCreationTimestamp);
transferArchiveKey = getTimestampTransferArchiveKey(accountIdentifier, deviceId, deviceCreationTimestamp);
} else {
final String maybeRegistrationIdPattern = deviceIdentifierComponents[2];
if (!maybeRegistrationIdPattern.equals(TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN)) {
throw new IllegalArgumentException("Could not parse Redis key with pattern " + maybeRegistrationIdPattern);
}
final int registrationId = Integer.parseInt(deviceIdentifierComponents[3]);
if (!RegistrationIdValidator.validRegistrationId(registrationId)) {
throw new IllegalArgumentException("Invalid registration ID: " + registrationId);
}
deviceIdentifier = new RegistrationIdDeviceIdentifier(accountIdentifier, deviceId, registrationId);
transferArchiveKey = getRegistrationIdTransferArchiveKey(accountIdentifier, deviceId, registrationId);
final String registrationIdPattern = deviceIdentifierComponents[2];
if (!registrationIdPattern.equals(TRANSFER_ARCHIVE_REGISTRATION_ID_PATTERN)) {
throw new IllegalArgumentException("Could not parse Redis key with pattern " + registrationIdPattern);
}
final int registrationId = Integer.parseInt(deviceIdentifierComponents[3]);
if (!RegistrationIdValidator.validRegistrationId(registrationId)) {
throw new IllegalArgumentException("Invalid registration ID: " + registrationId);
}
deviceIdentifier = new DeviceIdentifier(accountIdentifier, deviceId, registrationId);
transferArchiveKey = getRegistrationIdTransferArchiveKey(accountIdentifier, deviceId, registrationId);
Optional.ofNullable(waitForTransferArchiveFuturesByDeviceIdentifier.remove(deviceIdentifier))
.ifPresent(future -> pubSubRedisClient.withConnection(connection -> connection.async().get(transferArchiveKey))
@@ -7,12 +7,13 @@ package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
@@ -23,14 +24,12 @@ import org.whispersystems.textsecuregcm.util.Futures;
import org.whispersystems.textsecuregcm.util.Optionals;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import javax.annotation.Nullable;
public class KeysManager {
// KeysController for backwards compatibility
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysManager.class, "getKeys");
private final SingleUseECPreKeyStore ecPreKeys;
private final SingleUseKEMPreKeyStore pqPreKeys;
private final PagedSingleUseKEMPreKeyStore pagedPqPreKeys;
private final RepeatedUseECSignedPreKeyStore ecSignedPreKeys;
private final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys;
@@ -39,12 +38,10 @@ public class KeysManager {
public KeysManager(
final SingleUseECPreKeyStore ecPreKeys,
final SingleUseKEMPreKeyStore pqPreKeys,
final PagedSingleUseKEMPreKeyStore pagedPqPreKeys,
final RepeatedUseECSignedPreKeyStore ecSignedPreKeys,
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys) {
this.ecPreKeys = ecPreKeys;
this.pqPreKeys = pqPreKeys;
this.pagedPqPreKeys = pagedPqPreKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
this.pqLastResortKeys = pqLastResortKeys;
@@ -109,9 +106,7 @@ public class KeysManager {
public CompletableFuture<Void> storeKemOneTimePreKeys(final UUID identifier, final byte deviceId,
final List<KEMSignedPreKey> preKeys) {
// Unconditionally delete keys in old format keystore, then write to the pagedPqPreKeys store
return pqPreKeys.delete(identifier, deviceId)
.thenCompose(_ -> pagedPqPreKeys.store(identifier, deviceId, preKeys));
return pagedPqPreKeys.store(identifier, deviceId, preKeys);
}
@@ -124,16 +119,12 @@ public class KeysManager {
CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE)
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(ignored -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW)))
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
.map(singleUsePreKey -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.map(_ -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT)));
}
private enum PQSource {
PAGE,
ROW,
LAST_RESORT
}
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source) {
@@ -163,15 +154,12 @@ public class KeysManager {
}
public CompletableFuture<Integer> getPqCount(final UUID identifier, final byte deviceId) {
// We only return the paged prekey count to encourage clients to upload more prekeys if they only have prekeys
// stored in the previous key store format
return pagedPqPreKeys.getCount(identifier, deviceId);
}
public CompletableFuture<Void> deleteSingleUsePreKeys(final UUID identifier) {
return CompletableFuture.allOf(
ecPreKeys.delete(identifier),
pqPreKeys.delete(identifier),
pagedPqPreKeys.delete(identifier)
);
}
@@ -179,7 +167,6 @@ public class KeysManager {
public CompletableFuture<Void> deleteSingleUsePreKeys(final UUID accountUuid, final byte deviceId) {
return CompletableFuture.allOf(
ecPreKeys.delete(accountUuid, deviceId),
pqPreKeys.delete(accountUuid, deviceId),
pagedPqPreKeys.delete(accountUuid, deviceId)
);
}
@@ -51,11 +51,11 @@ import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Object;
/**
* @implNote This version of a {@link SingleUsePreKeyStore} store bundles prekeys into "pages", which are stored in on
* @implNote This an analog of {@link SingleUseECPreKeyStore} store bundles prekeys into "pages", which are stored in on
* an object store and referenced via dynamodb. Each device may only have a single active page at a time. Crashes or
* errors may leave orphaned pages which are no longer referenced by the database. A background process must
* periodically check for orphaned pages and remove them.
* @see SingleUsePreKeyStore
* @see SingleUseECPreKeyStore
*/
public class PagedSingleUseKEMPreKeyStore {
@@ -22,6 +22,7 @@ import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
@@ -114,7 +115,11 @@ public class ProfilesManager {
if (profile.isEmpty()) {
profile = profiles.get(uuid, version);
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile));
try {
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile));
} catch (RedisException e) {
logger.warn("Failed to cache retrieved profile", e);
}
}
return profile;
@@ -126,7 +131,12 @@ public class ProfilesManager {
.map(versionedProfile -> CompletableFuture.completedFuture(maybeVersionedProfile))
.orElseGet(() -> profiles.getAsync(uuid, version)
.thenCompose(maybeVersionedProfileFromDynamo -> maybeVersionedProfileFromDynamo
.map(profile -> redisSetAsync(uuid, profile).thenApply(ignored -> maybeVersionedProfileFromDynamo))
.map(profile -> redisSetAsync(uuid, profile)
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
logger.warn("Failed to cache retrieved profile", e);
return null;
}))
.thenApply(ignored -> maybeVersionedProfileFromDynamo))
.orElseGet(() -> CompletableFuture.completedFuture(maybeVersionedProfileFromDynamo)))));
}
@@ -161,7 +171,7 @@ public class ProfilesManager {
return parseProfileJson(json);
} catch (RedisException e) {
logger.warn("Redis exception", e);
logger.warn("Failed to retrieve profile from cache", e);
return Optional.empty();
}
}
@@ -5,30 +5,305 @@
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static org.whispersystems.textsecuregcm.storage.AbstractDynamoDbStore.DYNAMO_DB_MAX_BATCH_SIZE;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import java.util.Map;
import java.util.UUID;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
/**
* A single-use EC pre-key store stores single-use EC prekeys. Keys returned by a single-use pre-key
* store's {@link #take(UUID, byte)} method are guaranteed to be returned exactly once, and repeated calls will never
* yield the same key.
* <p/>
* Each {@link Account} may have one or more {@link Device devices}. Clients <em>should</em> regularly check their
* supply of single-use pre-keys (see {@link #getCount(UUID, byte)}) and upload new keys when their supply runs low. In
* the event that a party wants to begin a session with a device that has no single-use pre-keys remaining, that party
* may fall back to using the device's repeated-use ("last-resort") signed pre-key instead.
*/
public class SingleUseECPreKeyStore {
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
private final Timer getKeyCountTimer = Metrics.timer(name(getClass(), "getCount"));
private final Timer storeKeyTimer = Metrics.timer(name(getClass(), "storeKey"));
private final Timer storeKeyBatchTimer = Metrics.timer(name(getClass(), "storeKeyBatch"));
private final Timer deleteForDeviceTimer = Metrics.timer(name(getClass(), "deleteForDevice"));
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
private final Counter noKeyCountAvailableCounter = Metrics.counter(name(getClass(), "noKeyCountAvailable"));
final DistributionSummary keysConsideredForTakeDistributionSummary = DistributionSummary
.builder(name(getClass(), "keysConsideredForTake"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.register(Metrics.globalRegistry);
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
.builder(name(getClass(), "availableKeyCount"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.register(Metrics.globalRegistry);
public class SingleUseECPreKeyStore extends SingleUsePreKeyStore<ECPreKey> {
private static final String PARSE_BYTE_ARRAY_COUNTER_NAME = name(SingleUseECPreKeyStore.class, "parseByteArray");
private final String takeKeyTimerName = name(getClass(), "takeKey");
private static final String KEY_PRESENT_TAG_NAME = "keyPresent";
static final String KEY_ACCOUNT_UUID = "U";
static final String KEY_DEVICE_ID_KEY_ID = "DK";
static final String ATTR_PUBLIC_KEY = "P";
static final String ATTR_REMAINING_KEYS = "R";
public SingleUseECPreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
super(dynamoDbAsyncClient, tableName);
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
}
@Override
protected Map<String, AttributeValue> getItemFromPreKey(final UUID identifier,
/**
* Stores a batch of single-use pre-keys for a specific device. All previously-stored keys for the device are cleared
* before storing new keys.
*
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
* @param preKeys a collection of single-use pre-keys to store for the target device
*
* @return a future that completes when all previously-stored keys have been removed and the given collection of
* pre-keys has been stored in its place
*/
public CompletableFuture<Void> store(final UUID identifier, final byte deviceId, final List<ECPreKey> preKeys) {
final Timer.Sample sample = Timer.start();
return Mono.fromFuture(() -> delete(identifier, deviceId))
.thenMany(
Flux.fromIterable(preKeys)
.sort(Comparator.comparing(preKey -> preKey.keyId()))
.zipWith(Flux.range(0, preKeys.size()).map(i -> preKeys.size() - i))
.flatMap(preKeyAndRemainingCount -> Mono.fromFuture(() ->
store(identifier, deviceId, preKeyAndRemainingCount.getT1(), preKeyAndRemainingCount.getT2())),
DYNAMO_DB_MAX_BATCH_SIZE))
.then()
.toFuture()
.thenRun(() -> sample.stop(storeKeyBatchTimer));
}
private CompletableFuture<Void> store(final UUID identifier, final byte deviceId, final ECPreKey preKey, final int remainingKeys) {
final Timer.Sample sample = Timer.start();
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(getItemFromPreKey(identifier, deviceId, preKey, remainingKeys))
.build())
.thenRun(() -> sample.stop(storeKeyTimer));
}
/**
* Attempts to retrieve a single-use pre-key for a specific device. Keys may only be returned by this method at most
* once; once the key is returned, it is removed from the key store and subsequent calls to this method will never
* return the same key.
*
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
*
* @return a future that yields a single-use pre-key if one is available or empty if no single-use pre-keys are
* available for the target device
*/
public CompletableFuture<Optional<ECPreKey>> take(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
final AttributeValue partitionKey = getPartitionKey(identifier);
final AtomicInteger keysConsidered = new AtomicInteger(0);
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
.expressionAttributeValues(Map.of(
":uuid", partitionKey,
":sortprefix", getSortKeyPrefix(deviceId)))
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
.consistentRead(false)
.limit(1)
.build())
.items())
.map(item -> DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_ACCOUNT_UUID, partitionKey,
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)))
.returnValues(ReturnValue.ALL_OLD)
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), 1)
.doOnNext(deleteItemResponse -> keysConsidered.incrementAndGet())
.filter(DeleteItemResponse::hasAttributes)
.next()
.map(deleteItemResponse -> getPreKeyFromItem(deleteItemResponse.attributes()))
.toFuture()
.thenApply(Optional::ofNullable)
.whenComplete((maybeKey, throwable) -> {
sample.stop(Metrics.timer(takeKeyTimerName, KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent())));
keysConsideredForTakeDistributionSummary.record(keysConsidered.get());
});
}
/**
* Estimates the number of single-use pre-keys available for a given device.
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
* @return a future that yields the approximate number of single-use pre-keys currently available for the target
* device
*/
public CompletableFuture<Integer> getCount(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
return dynamoDbAsyncClient.query(QueryRequest.builder()
.tableName(tableName)
.consistentRead(false)
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
.expressionAttributeValues(Map.of(
":uuid", getPartitionKey(identifier),
":sortprefix", getSortKeyPrefix(deviceId)))
.projectionExpression(ATTR_REMAINING_KEYS)
.limit(1)
.build())
.thenApply(response -> {
if (response.count() > 0) {
final Map<String, AttributeValue> item = response.items().getFirst();
if (item.containsKey(ATTR_REMAINING_KEYS)) {
return Integer.parseInt(item.get(ATTR_REMAINING_KEYS).n());
} else {
// Some legacy keys sets may not have pre-counted keys; in that case, we'll tell the owners of those key
// sets that they have none remaining, prompting an upload of a fresh set that we'll pre-count. This has
// no effect on consumers of keys, which will still be able to take keys if any are actually present.
noKeyCountAvailableCounter.increment();
return 0;
}
} else {
return 0;
}
})
.whenComplete((keyCount, throwable) -> {
sample.stop(getKeyCountTimer);
if (throwable == null && keyCount != null) {
availableKeyCountDistributionSummary.record(keyCount);
}
});
}
/**
* Removes all single-use pre-keys for all devices associated with the given account/identity.
*
* @param identifier the identifier for the account/identity for which to remove single-use pre-keys
*
* @return a future that completes when all single-use pre-keys have been removed for all devices associated with the
* given account/identity
*/
public CompletableFuture<Void> delete(final UUID identifier) {
final Timer.Sample sample = Timer.start();
return deleteItems(getPartitionKey(identifier), Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(":uuid", getPartitionKey(identifier)))
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
.consistentRead(true)
.build())
.items()))
.thenRun(() -> sample.stop(deleteForAccountTimer));
}
/**
* Removes all single-use pre-keys for a specific device.
*
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
* @return a future that completes when all single-use pre-keys have been removed for the target device
*/
public CompletableFuture<Void> delete(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
return deleteItems(getPartitionKey(identifier), Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
.expressionAttributeValues(Map.of(
":uuid", getPartitionKey(identifier),
":sortprefix", getSortKeyPrefix(deviceId)))
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
.consistentRead(true)
.build())
.items()))
.thenRun(() -> sample.stop(deleteForDeviceTimer));
}
private CompletableFuture<Void> deleteItems(final AttributeValue partitionKey, final Flux<Map<String, AttributeValue>> items) {
return items
.map(item -> DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_ACCOUNT_UUID, partitionKey,
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)
))
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), DYNAMO_DB_MAX_BATCH_SIZE)
.then()
.toFuture()
.thenRun(Util.NOOP);
}
protected static AttributeValue getPartitionKey(final UUID accountUuid) {
return AttributeValues.fromUUID(accountUuid);
}
protected static AttributeValue getSortKey(final byte deviceId, final long keyId) {
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(deviceId);
byteBuffer.putLong(keyId);
return AttributeValues.fromByteBuffer(byteBuffer.flip());
}
private static AttributeValue getSortKeyPrefix(final byte deviceId) {
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
byteBuffer.putLong(deviceId);
return AttributeValues.fromByteBuffer(byteBuffer.flip());
}
private Map<String, AttributeValue> getItemFromPreKey(final UUID identifier,
final byte deviceId,
final ECPreKey preKey,
final int remainingKeys) {
return Map.of(
KEY_ACCOUNT_UUID, getPartitionKey(identifier),
KEY_DEVICE_ID_KEY_ID, getSortKey(deviceId, preKey.keyId()),
@@ -36,8 +311,7 @@ public class SingleUseECPreKeyStore extends SingleUsePreKeyStore<ECPreKey> {
ATTR_REMAINING_KEYS, AttributeValues.fromInt(remainingKeys));
}
@Override
protected ECPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
private ECPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
final byte[] publicKey = AttributeValues.extractByteArray(item.get(ATTR_PUBLIC_KEY), PARSE_BYTE_ARRAY_COUNTER_NAME);
@@ -1,50 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import java.util.Map;
import java.util.UUID;
public class SingleUseKEMPreKeyStore extends SingleUsePreKeyStore<KEMSignedPreKey> {
public SingleUseKEMPreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
super(dynamoDbAsyncClient, tableName);
}
@Override
protected Map<String, AttributeValue> getItemFromPreKey(final UUID identifier,
final byte deviceId,
final KEMSignedPreKey signedPreKey,
final int remainingKeys) {
return Map.of(
KEY_ACCOUNT_UUID, getPartitionKey(identifier),
KEY_DEVICE_ID_KEY_ID, getSortKey(deviceId, signedPreKey.keyId()),
ATTR_PUBLIC_KEY, AttributeValues.fromByteArray(signedPreKey.serializedPublicKey()),
ATTR_SIGNATURE, AttributeValues.fromByteArray(signedPreKey.signature()),
ATTR_REMAINING_KEYS, AttributeValues.fromInt(remainingKeys));
}
@Override
protected KEMSignedPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
final byte[] publicKey = item.get(ATTR_PUBLIC_KEY).b().asByteArray();
final byte[] signature = item.get(ATTR_SIGNATURE).b().asByteArray();
try {
return new KEMSignedPreKey(keyId, new KEMPublicKey(publicKey), signature);
} catch (final InvalidKeyException e) {
// This should never happen since we're serializing keys directly from `KEMPublicKey` instances on the way in
throw new IllegalArgumentException(e);
}
}
}
@@ -1,306 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static org.whispersystems.textsecuregcm.storage.AbstractDynamoDbStore.DYNAMO_DB_MAX_BATCH_SIZE;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.whispersystems.textsecuregcm.entities.PreKey;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
/**
* A single-use pre-key store stores single-use pre-keys of a specific type. Keys returned by a single-use pre-key
* store's {@link #take(UUID, byte)} method are guaranteed to be returned exactly once, and repeated calls will never
* yield the same key.
* <p/>
* Each {@link Account} may have one or more {@link Device devices}. Clients <em>should</em> regularly check their
* supply of single-use pre-keys (see {@link #getCount(UUID, byte)}) and upload new keys when their supply runs low. In
* the event that a party wants to begin a session with a device that has no single-use pre-keys remaining, that party
* may fall back to using the device's repeated-use ("last-resort") signed pre-key instead.
*/
public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
private final Timer getKeyCountTimer = Metrics.timer(name(getClass(), "getCount"));
private final Timer storeKeyTimer = Metrics.timer(name(getClass(), "storeKey"));
private final Timer storeKeyBatchTimer = Metrics.timer(name(getClass(), "storeKeyBatch"));
private final Timer deleteForDeviceTimer = Metrics.timer(name(getClass(), "deleteForDevice"));
private final Timer deleteForAccountTimer = Metrics.timer(name(getClass(), "deleteForAccount"));
private final Counter noKeyCountAvailableCounter = Metrics.counter(name(getClass(), "noKeyCountAvailable"));
final DistributionSummary keysConsideredForTakeDistributionSummary = DistributionSummary
.builder(name(getClass(), "keysConsideredForTake"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.register(Metrics.globalRegistry);
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
.builder(name(getClass(), "availableKeyCount"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofMinutes(10))
.register(Metrics.globalRegistry);
private final String takeKeyTimerName = name(getClass(), "takeKey");
private static final String KEY_PRESENT_TAG_NAME = "keyPresent";
static final String KEY_ACCOUNT_UUID = "U";
static final String KEY_DEVICE_ID_KEY_ID = "DK";
static final String ATTR_PUBLIC_KEY = "P";
static final String ATTR_SIGNATURE = "S";
static final String ATTR_REMAINING_KEYS = "R";
protected SingleUsePreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
}
/**
* Stores a batch of single-use pre-keys for a specific device. All previously-stored keys for the device are cleared
* before storing new keys.
*
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
* @param preKeys a collection of single-use pre-keys to store for the target device
*
* @return a future that completes when all previously-stored keys have been removed and the given collection of
* pre-keys has been stored in its place
*/
public CompletableFuture<Void> store(final UUID identifier, final byte deviceId, final List<K> preKeys) {
final Timer.Sample sample = Timer.start();
return Mono.fromFuture(() -> delete(identifier, deviceId))
.thenMany(
Flux.fromIterable(preKeys)
.sort(Comparator.comparing(preKey -> preKey.keyId()))
.zipWith(Flux.range(0, preKeys.size()).map(i -> preKeys.size() - i))
.flatMap(preKeyAndRemainingCount -> Mono.fromFuture(() ->
store(identifier, deviceId, preKeyAndRemainingCount.getT1(), preKeyAndRemainingCount.getT2())),
DYNAMO_DB_MAX_BATCH_SIZE))
.then()
.toFuture()
.thenRun(() -> sample.stop(storeKeyBatchTimer));
}
private CompletableFuture<Void> store(final UUID identifier, final byte deviceId, final K preKey, final int remainingKeys) {
final Timer.Sample sample = Timer.start();
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(getItemFromPreKey(identifier, deviceId, preKey, remainingKeys))
.build())
.thenRun(() -> sample.stop(storeKeyTimer));
}
/**
* Attempts to retrieve a single-use pre-key for a specific device. Keys may only be returned by this method at most
* once; once the key is returned, it is removed from the key store and subsequent calls to this method will never
* return the same key.
*
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
*
* @return a future that yields a single-use pre-key if one is available or empty if no single-use pre-keys are
* available for the target device
*/
public CompletableFuture<Optional<K>> take(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
final AttributeValue partitionKey = getPartitionKey(identifier);
final AtomicInteger keysConsidered = new AtomicInteger(0);
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
.expressionAttributeValues(Map.of(
":uuid", partitionKey,
":sortprefix", getSortKeyPrefix(deviceId)))
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
.consistentRead(false)
.limit(1)
.build())
.items())
.map(item -> DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_ACCOUNT_UUID, partitionKey,
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)))
.returnValues(ReturnValue.ALL_OLD)
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), 1)
.doOnNext(deleteItemResponse -> keysConsidered.incrementAndGet())
.filter(DeleteItemResponse::hasAttributes)
.next()
.map(deleteItemResponse -> getPreKeyFromItem(deleteItemResponse.attributes()))
.toFuture()
.thenApply(Optional::ofNullable)
.whenComplete((maybeKey, throwable) -> {
sample.stop(Metrics.timer(takeKeyTimerName, KEY_PRESENT_TAG_NAME, String.valueOf(maybeKey != null && maybeKey.isPresent())));
keysConsideredForTakeDistributionSummary.record(keysConsidered.get());
});
}
/**
* Estimates the number of single-use pre-keys available for a given device.
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
* @return a future that yields the approximate number of single-use pre-keys currently available for the target
* device
*/
public CompletableFuture<Integer> getCount(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
return dynamoDbAsyncClient.query(QueryRequest.builder()
.tableName(tableName)
.consistentRead(false)
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
.expressionAttributeValues(Map.of(
":uuid", getPartitionKey(identifier),
":sortprefix", getSortKeyPrefix(deviceId)))
.projectionExpression(ATTR_REMAINING_KEYS)
.limit(1)
.build())
.thenApply(response -> {
if (response.count() > 0) {
final Map<String, AttributeValue> item = response.items().getFirst();
if (item.containsKey(ATTR_REMAINING_KEYS)) {
return Integer.parseInt(item.get(ATTR_REMAINING_KEYS).n());
} else {
// Some legacy keys sets may not have pre-counted keys; in that case, we'll tell the owners of those key
// sets that they have none remaining, prompting an upload of a fresh set that we'll pre-count. This has
// no effect on consumers of keys, which will still be able to take keys if any are actually present.
noKeyCountAvailableCounter.increment();
return 0;
}
} else {
return 0;
}
})
.whenComplete((keyCount, throwable) -> {
sample.stop(getKeyCountTimer);
if (throwable == null && keyCount != null) {
availableKeyCountDistributionSummary.record(keyCount);
}
});
}
/**
* Removes all single-use pre-keys for all devices associated with the given account/identity.
*
* @param identifier the identifier for the account/identity for which to remove single-use pre-keys
*
* @return a future that completes when all single-use pre-keys have been removed for all devices associated with the
* given account/identity
*/
public CompletableFuture<Void> delete(final UUID identifier) {
final Timer.Sample sample = Timer.start();
return deleteItems(getPartitionKey(identifier), Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(":uuid", getPartitionKey(identifier)))
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
.consistentRead(true)
.build())
.items()))
.thenRun(() -> sample.stop(deleteForAccountTimer));
}
/**
* Removes all single-use pre-keys for a specific device.
*
* @param identifier the identifier for the account/identity with which the target device is associated
* @param deviceId the identifier for the device within the given account/identity
* @return a future that completes when all single-use pre-keys have been removed for the target device
*/
public CompletableFuture<Void> delete(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
return deleteItems(getPartitionKey(identifier), Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
.expressionAttributeValues(Map.of(
":uuid", getPartitionKey(identifier),
":sortprefix", getSortKeyPrefix(deviceId)))
.projectionExpression(KEY_DEVICE_ID_KEY_ID)
.consistentRead(true)
.build())
.items()))
.thenRun(() -> sample.stop(deleteForDeviceTimer));
}
private CompletableFuture<Void> deleteItems(final AttributeValue partitionKey, final Flux<Map<String, AttributeValue>> items) {
return items
.map(item -> DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_ACCOUNT_UUID, partitionKey,
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)
))
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), DYNAMO_DB_MAX_BATCH_SIZE)
.then()
.toFuture()
.thenRun(Util.NOOP);
}
protected static AttributeValue getPartitionKey(final UUID accountUuid) {
return AttributeValues.fromUUID(accountUuid);
}
protected static AttributeValue getSortKey(final byte deviceId, final long keyId) {
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(deviceId);
byteBuffer.putLong(keyId);
return AttributeValues.fromByteBuffer(byteBuffer.flip());
}
private static AttributeValue getSortKeyPrefix(final byte deviceId) {
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
byteBuffer.putLong(deviceId);
return AttributeValues.fromByteBuffer(byteBuffer.flip());
}
protected abstract Map<String, AttributeValue> getItemFromPreKey(final UUID identifier,
final byte deviceId,
final K preKey,
final int remainingKeys);
protected abstract K getPreKeyFromItem(final Map<String, AttributeValue> item);
}
@@ -230,7 +230,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
try {
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
} catch (StripeException e) {
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
final String errorCode = e.getCode() == null
? "unknown"
: e.getCode().toLowerCase(Locale.ROOT);
switch (errorCode) {
case "amount_too_small","amount_too_large" ->
throw ExceptionUtils.wrap(new SubscriptionInvalidAmountException(errorCode));
@@ -7,8 +7,8 @@ package org.whispersystems.textsecuregcm.util;
import java.util.Map;
public record Pair<T1, T2>(T1 first, T2 second) {
public Pair(org.signal.libsignal.protocol.util.Pair<T1, T2> p) {
this(p.first(), p.second());
public Pair(kotlin.Pair<T1, T2> p) {
this(p.getFirst(), p.getSecond());
}
public Pair(Map.Entry<T1, T2> e) {
@@ -72,7 +72,6 @@ import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
@@ -238,7 +237,6 @@ public record CommandDependencies(
configuration.getPagedSingleUseKEMPreKeyStore().bucket());
KeysManager keys = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, configuration.getDynamoDbTables().getEcKeys().getTableName()),
new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, configuration.getDynamoDbTables().getKemKeys().getTableName()),
pagedSingleUseKEMPreKeyStore,
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient,
configuration.getDynamoDbTables().getEcSignedPreKeys().getTableName()),
@@ -45,6 +45,16 @@ message CreateRegistrationSessionRequest {
* collated by this key.
*/
string rate_limit_collation_key = 3;
/**
* The MCC for the given `e164` as reported by the client.
*/
string mcc = 4;
/**
* The MNC for the given `e164` as reported by the client.
*/
string mnc = 5;
}
message CreateRegistrationSessionResponse {
@@ -408,7 +408,7 @@ message CopyMediaItem {
/**
* The attachment cdn of the object to copy into the backup
*/
int32 source_attachment_cdn = 1 [(require.present) = true];
int32 source_attachment_cdn = 1 [(require.range).min = 1, (require.range).max = 3];
/**
* The attachment key of the object to copy into the backup
@@ -198,6 +198,11 @@ message GetPreKeysResponse {
* account/device/identity.
*/
common.KemSignedPreKey kem_one_time_pre_key = 3;
/**
* The registration ID for the targeted account/device/identity.
*/
uint32 registration_id = 4;
}
/**
@@ -9,9 +9,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -29,7 +28,6 @@ import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.assertj.core.api.Assertions;
@@ -618,12 +616,12 @@ public class BackupAuthManagerTest {
final RateLimiters limiters = mock(RateLimiters.class);
final RateLimiter allowLimiter = mock(RateLimiter.class);
when(allowLimiter.hasAvailablePermitsAsync(eq(aci), anyInt())).thenReturn(CompletableFuture.completedFuture(true));
when(allowLimiter.hasAvailablePermitsAsync(eq(aci), anyLong())).thenReturn(CompletableFuture.completedFuture(true));
when(allowLimiter.validateAsync(aci)).thenReturn(CompletableFuture.completedFuture(null));
when(allowLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
final RateLimiter denyLimiter = mock(RateLimiter.class);
when(denyLimiter.hasAvailablePermitsAsync(eq(aci), anyInt())).thenReturn(CompletableFuture.completedFuture(false));
when(denyLimiter.hasAvailablePermitsAsync(eq(aci), anyLong())).thenReturn(CompletableFuture.completedFuture(false));
when(denyLimiter.validateAsync(aci))
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
when(denyLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
@@ -61,7 +61,12 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
@Override
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
final Phonenumber.PhoneNumber phoneNumber, final String sourceHost, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
final Phonenumber.PhoneNumber phoneNumber,
final String sourceHost,
final boolean accountExistsWithPhoneNumber,
@javax.annotation.Nullable final String clientMcc,
@javax.annotation.Nullable final String clientMnc,
final Duration timeout) {
final String e164 = PhoneNumberUtil.getInstance()
.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.eq;
@@ -196,7 +197,6 @@ class DeviceControllerTest {
final Device refreshedDevice = mock(Device.class);
when(refreshedDevice.getId()).thenReturn(deviceId);
when(refreshedDevice.getName()).thenReturn(deviceName);
when(refreshedDevice.getCreated()).thenReturn(deviceCreated);
when(refreshedDevice.getLastSeen()).thenReturn(deviceLastSeen);
when(refreshedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
when(refreshedDevice.getCreatedAtCiphertext()).thenReturn(createdAtCiphertext);
@@ -215,7 +215,6 @@ class DeviceControllerTest {
assertEquals(1, deviceInfoList.devices().size());
assertEquals(deviceId, deviceInfoList.devices().getFirst().id());
assertArrayEquals(deviceName, deviceInfoList.devices().getFirst().name());
assertEquals(deviceCreated, deviceInfoList.devices().getFirst().created());
assertEquals(deviceLastSeen, deviceInfoList.devices().getFirst().lastSeen());
assertEquals(registrationId, deviceInfoList.devices().getFirst().registrationId());
assertArrayEquals(createdAtCiphertext, deviceInfoList.devices().getFirst().createdAtCiphertext());
@@ -962,7 +961,6 @@ class DeviceControllerTest {
final DeviceInfo deviceInfo = new DeviceInfo(Device.PRIMARY_ID,
"Device name ciphertext".getBytes(StandardCharsets.UTF_8),
System.currentTimeMillis(),
System.currentTimeMillis(),
1,
"timestamp ciphertext".getBytes(StandardCharsets.UTF_8));
@@ -985,7 +983,6 @@ class DeviceControllerTest {
final DeviceInfo retrievedDeviceInfo = response.readEntity(DeviceInfo.class);
assertEquals(deviceInfo.id(), retrievedDeviceInfo.id());
assertArrayEquals(deviceInfo.name(), retrievedDeviceInfo.name());
assertEquals(deviceInfo.created(), retrievedDeviceInfo.created());
assertEquals(deviceInfo.lastSeen(), retrievedDeviceInfo.lastSeen());
assertEquals(deviceInfo.registrationId(), retrievedDeviceInfo.registrationId());
assertArrayEquals(deviceInfo.createdAtCiphertext(), retrievedDeviceInfo.createdAtCiphertext());
@@ -1083,60 +1080,53 @@ class DeviceControllerTest {
}
}
@ParameterizedTest
@MethodSource
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
void recordTransferArchiveUploaded(final Optional<Instant> deviceCreated, final Optional<Integer> registrationId) {
@Test
void recordTransferArchiveUploaded() {
final byte deviceId = Device.PRIMARY_ID + 1;
final int registrationId = 123;
final RemoteAttachment transferArchive =
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.recordTransferArchiveUpload(account, deviceId, deviceCreated, registrationId, transferArchive))
when(accountsManager.recordTransferArchiveUpload(account, deviceId, registrationId, transferArchive))
.thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/transfer_archive")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, deviceCreated.map(Instant::toEpochMilli), registrationId, transferArchive),
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, registrationId, transferArchive),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(204, response.getStatus());
verify(accountsManager)
.recordTransferArchiveUpload(account, deviceId, deviceCreated, registrationId, transferArchive);
.recordTransferArchiveUpload(account, deviceId, registrationId, transferArchive);
}
}
private static List<Arguments> recordTransferArchiveUploaded() {
return List.of(
Arguments.of(Optional.empty(), Optional.of(123)),
Arguments.of(Optional.of(Instant.now().truncatedTo(ChronoUnit.MILLIS)), Optional.empty())
);
}
@Test
void recordTransferArchiveFailed() {
final byte deviceId = Device.PRIMARY_ID + 1;
final int registrationId = 123;
final Instant deviceCreated = Instant.now().truncatedTo(ChronoUnit.MILLIS);
final RemoteAttachmentError transferFailure = new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
when(rateLimiter.validateAsync(AuthHelper.VALID_UUID)).thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.recordTransferArchiveUpload(account, deviceId, Optional.of(deviceCreated), Optional.empty(), transferFailure))
when(accountsManager.recordTransferArchiveUpload(account, deviceId, registrationId, transferFailure))
.thenReturn(CompletableFuture.completedFuture(null));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/transfer_archive")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, Optional.of(deviceCreated.toEpochMilli()), Optional.empty(), transferFailure),
.put(Entity.entity(new TransferArchiveUploadedRequest(deviceId, registrationId, transferFailure),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(204, response.getStatus());
verify(accountsManager)
.recordTransferArchiveUpload(account, deviceId, Optional.of(deviceCreated), Optional.empty(), transferFailure);
.recordTransferArchiveUpload(account, deviceId, registrationId, transferFailure);
}
}
@@ -1154,7 +1144,7 @@ class DeviceControllerTest {
assertEquals(422, response.getStatus());
verify(accountsManager, never())
.recordTransferArchiveUpload(any(), anyByte(), any(), any(), any());
.recordTransferArchiveUpload(any(), anyByte(), anyInt(), any());
}
}
@@ -1164,22 +1154,16 @@ class DeviceControllerTest {
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8)));
return List.of(
Arguments.argumentSet("Invalid device ID", new TransferArchiveUploadedRequest((byte) -1, Optional.of(System.currentTimeMillis()), Optional.empty(), validTransferArchive)),
Arguments.argumentSet("Invalid \"created at\" timestamp",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of((long) -1), Optional.empty(), validTransferArchive)),
Arguments.argumentSet("Invalid device ID", new TransferArchiveUploadedRequest((byte) -1, 1, validTransferArchive)),
Arguments.argumentSet("Invalid registration ID - negative",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.of(-1), validTransferArchive)),
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, -1, validTransferArchive)),
Arguments.argumentSet("Invalid registration ID - too large",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.of(0x4000), validTransferArchive)),
Arguments.argumentSet("Exactly one of \"created at\" timestamp and registration ID must be present - neither provided",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.empty(), Optional.empty(), validTransferArchive)),
Arguments.argumentSet("Exactly one of \"created at\" timestamp and registration ID must be present - both provided",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.of(123), validTransferArchive)),
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, 0x4000, validTransferArchive)),
Arguments.argumentSet("Missing CDN number",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, 1,
new RemoteAttachment(null, Base64.getUrlEncoder().encodeToString("archive".getBytes(StandardCharsets.UTF_8))))),
Arguments.argumentSet("Bad attachment key",
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
new TransferArchiveUploadedRequest(Device.PRIMARY_ID, 1,
new RemoteAttachment(3, "This is not a valid base64 string")))
);
}
@@ -1193,14 +1177,14 @@ class DeviceControllerTest {
.target("/v1/devices/transfer_archive")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new TransferArchiveUploadedRequest(Device.PRIMARY_ID, Optional.of(System.currentTimeMillis()), Optional.empty(),
.put(Entity.entity(new TransferArchiveUploadedRequest(Device.PRIMARY_ID, 1,
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)))),
MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(429, response.getStatus());
verify(accountsManager, never())
.recordTransferArchiveUpload(any(), anyByte(), any(), any(), any());
.recordTransferArchiveUpload(any(), anyByte(), anyInt(), any());
}
}
@@ -192,7 +192,7 @@ class VerificationControllerTest {
@Test
void createSessionRateLimited() {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
final Invocation.Builder request = resources.getJerseyTest()
@@ -206,7 +206,7 @@ class VerificationControllerTest {
@Test
void createSessionRegistrationServiceError() {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("expected service error")));
final Invocation.Builder request = resources.getJerseyTest()
@@ -221,7 +221,7 @@ class VerificationControllerTest {
@ParameterizedTest
@MethodSource
void createBeninSessionSuccess(final String requestedNumber, final String expectedNumber) {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
@@ -238,7 +238,7 @@ class VerificationControllerTest {
final ArgumentCaptor<Phonenumber.PhoneNumber> phoneNumberArgumentCaptor = ArgumentCaptor.forClass(
Phonenumber.PhoneNumber.class);
verify(registrationServiceClient).createRegistrationSession(phoneNumberArgumentCaptor.capture(), anyString(), anyBoolean(), any());
verify(registrationServiceClient).createRegistrationSession(phoneNumberArgumentCaptor.capture(), anyString(), anyBoolean(), any(), any(), any());
final Phonenumber.PhoneNumber phoneNumber = phoneNumberArgumentCaptor.getValue();
assertEquals(expectedNumber, PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164));
@@ -262,7 +262,7 @@ class VerificationControllerTest {
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
@@ -283,7 +283,7 @@ class VerificationControllerTest {
@MethodSource
void createSessionSuccess(final String pushToken, final String pushTokenType,
final List<VerificationSession.Information> expectedRequestedInformation) {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
@@ -317,7 +317,7 @@ class VerificationControllerTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void createSessionReregistration(final boolean isReregistration) throws NumberParseException {
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
@@ -341,6 +341,8 @@ class VerificationControllerTest {
eq(PhoneNumberUtil.getInstance().parse(NUMBER, null)),
anyString(),
eq(isReregistration),
any(),
any(),
any()
);
}
@@ -483,16 +483,20 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final byte deviceId1 = 1;
final byte deviceId2 = 2;
final Map<Byte, Integer> deviceRegistrations = Map.of(
deviceId1, 123,
deviceId2, 456
);
for (final byte deviceId : List.of(deviceId1, deviceId2)) {
for (Map.Entry<Byte, Integer> entry : deviceRegistrations.entrySet()) {
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(3, identityKeyPair);
final Optional<ECPreKey> maybeEcPreKey = Optional
.of(new ECPreKey(1, ECKeyPair.generate().getPublicKey()))
.filter(_ -> deviceId == deviceId1);
.filter(_ -> entry.getKey() == deviceId1);
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, identityKeyPair);
devicePreKeysMap.put(deviceId, new KeysManager.DevicePreKeys(ecSignedPreKey, maybeEcPreKey, kemSignedPreKey));
devicePreKeysMap.put(entry.getKey(), new KeysManager.DevicePreKeys(ecSignedPreKey, maybeEcPreKey, kemSignedPreKey));
final GetPreKeysResponse.PreKeyBundle.Builder builder = GetPreKeysResponse.PreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
@@ -504,19 +508,21 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
.setKeyId(kemSignedPreKey.keyId())
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
.build());
.build())
.setRegistrationId(entry.getValue());
maybeEcPreKey.ifPresent(ecPreKey -> builder
.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(ecPreKey.keyId())
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
.build()));
expectedPreKeyBundles.put(deviceId, builder.build());
expectedPreKeyBundles.put(entry.getKey(), builder.build());
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
when(device.getId()).thenReturn(entry.getKey());
when(device.getRegistrationId(any())).thenReturn(entry.getValue());
devices.put(deviceId, device);
when(targetAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
devices.put(entry.getKey(), device);
when(targetAccount.getDevice(entry.getKey())).thenReturn(Optional.of(device));
}
when(targetAccount.getDevices()).thenReturn(new ArrayList<>(devices.values()));
@@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -328,7 +327,7 @@ class MessagesAnonymousGrpcServiceTest extends
final Duration retryDuration = Duration.ofHours(7);
doThrow(new RateLimitExceededException(retryDuration)).when(rateLimiter).validate(eq(serviceIdentifier.uuid()), anyInt());
doThrow(new RateLimitExceededException(retryDuration)).when(rateLimiter).validate(eq(serviceIdentifier.uuid()), anyLong());
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
Map.of(deviceId, IndividualRecipientMessageBundle.Message.newBuilder()
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -293,7 +293,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
final Duration retryDuration = Duration.ofHours(7);
doThrow(new RateLimitExceededException(retryDuration))
.when(rateLimiter).validate(eq(serviceIdentifier.uuid()), anyInt());
.when(rateLimiter).validate(eq(serviceIdentifier.uuid()), anyLong());
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
Map.of(deviceId, IndividualRecipientMessageBundle.Message.newBuilder()
@@ -555,7 +555,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
void rateLimited() throws RateLimitExceededException, MessageTooLargeException, MismatchedDevicesException {
final Duration retryDuration = Duration.ofHours(7);
doThrow(new RateLimitExceededException(retryDuration))
.when(rateLimiter).validate(eq(AUTHENTICATED_ACI), anyInt());
.when(rateLimiter).validate(eq(AUTHENTICATED_ACI), anyLong());
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
Map.of(AUTHENTICATED_DEVICE_ID, IndividualRecipientMessageBundle.Message.newBuilder()
@@ -32,9 +32,11 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.chat.require.Auth;
import org.signal.chat.rpc.Color;
import org.signal.chat.rpc.NestedMessage;
import org.signal.chat.rpc.ReactorAnonymousServiceGrpc;
import org.signal.chat.rpc.ReactorAuthServiceGrpc;
import org.signal.chat.rpc.ReactorValidationTestServiceGrpc;
import org.signal.chat.rpc.RecursiveMessage;
import org.signal.chat.rpc.ValidationTestServiceGrpc;
import org.signal.chat.rpc.ValidationsRequest;
import org.signal.chat.rpc.ValidationsResponse;
@@ -374,6 +376,37 @@ public class ValidatingInterceptorTest {
stub.validationsEndpoint(builderWithValidDefaults().build());
}
@Test
public void testFailedValidationOnNestedMessage() {
assertStatusException(Status.INVALID_ARGUMENT, () ->
stub.validationsEndpoint(builderWithValidDefaults().setNested(NestedMessage.newBuilder().setI32(101)).build()));
assertStatusException(Status.INVALID_ARGUMENT, () ->
stub.validationsEndpoint(builderWithValidDefaults()
.clearRepeatedNested()
.addRepeatedNested(NestedMessage.newBuilder().setI32(101)).build()));
assertStatusException(Status.INVALID_ARGUMENT, () ->
stub.validationsEndpoint(builderWithValidDefaults()
.clearMapNested()
.putMapNested("foo", NestedMessage.newBuilder().setI32(101).build()).build()));
}
@Test
public void deeplyNestedValidation() throws Exception {
// The default proto nesting limit (what we use in gRPC) is 100. Make sure we can handle twice that amount of nesting
int numNestedMessages = 100 * 2;
RecursiveMessage.Builder curr = RecursiveMessage.newBuilder().setI32(101);
for (int i = 0; i < numNestedMessages; i++) {
final RecursiveMessage.Builder pred = RecursiveMessage.newBuilder();
pred.setNext(curr);
curr = pred;
}
final RecursiveMessage recursiveMessage = curr.build();
assertStatusException(Status.INVALID_ARGUMENT, () ->
stub.validationsEndpoint(builderWithValidDefaults().setRecursiveMessage(recursiveMessage).build()));
}
@Nonnull
private static ValidationsRequest.Builder builderWithValidDefaults() {
return ValidationsRequest.newBuilder()
@@ -398,7 +431,10 @@ public class ValidatingInterceptorTest {
.setRangeSizeBytes(ByteString.copyFrom(new byte[3]))
.addAllFixedSizeList(List.of("a", "b", "c", "d", "e"))
.addAllRangeSizeList(List.of("a", "b", "c", "d", "e"))
.setI32Range(15);
.setI32Range(15)
.setNested(NestedMessage.getDefaultInstance())
.addRepeatedNested(NestedMessage.getDefaultInstance())
.putMapNested("test", NestedMessage.getDefaultInstance());
}
private static void assertStatusException(final Status expected, final Executable serviceCall) {
@@ -36,7 +36,7 @@ import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.util.TestClock;
class DynamicRateLimiterTest {
class LeakyBucketRateLimiterTest {
private ClusterLuaScript validateRateLimitScript;
private ScheduledExecutorService retryExecutor;
@@ -62,7 +62,7 @@ class DynamicRateLimiterTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void validate(final boolean failOpen) {
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, Duration.ofHours(1), failOpen),
validateRateLimitScript,
@@ -79,7 +79,7 @@ class DynamicRateLimiterTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void validateAsync(final boolean failOpen) {
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, Duration.ofHours(1), failOpen),
validateRateLimitScript,
@@ -102,7 +102,7 @@ class DynamicRateLimiterTest {
final ClusterLuaScript failingScript = mock(ClusterLuaScript.class);
when(failingScript.execute(any(), any())).thenThrow(new RuntimeException("OH NO"));
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, Duration.ofHours(1), failOpen),
failingScript,
@@ -125,7 +125,7 @@ class DynamicRateLimiterTest {
final ClusterLuaScript failingScript = mock(ClusterLuaScript.class);
when(failingScript.executeAsync(any(), any())).thenReturn(CompletableFuture.failedFuture(new RuntimeException("OH NO")));
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, Duration.ofHours(1), failOpen),
failingScript,
@@ -148,7 +148,7 @@ class DynamicRateLimiterTest {
@Test
void configChange_ReduceRefillRate() {
final AtomicReference<Duration> refillRate = new AtomicReference<>(Duration.ofMinutes(5));
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, refillRate.get(), false),
validateRateLimitScript,
@@ -172,7 +172,7 @@ class DynamicRateLimiterTest {
@Test
void configChange_IncreaseRefillRate() {
final AtomicReference<Duration> refillRate = new AtomicReference<>(Duration.ofMinutes(5));
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, refillRate.get(), false),
validateRateLimitScript,
@@ -199,7 +199,7 @@ class DynamicRateLimiterTest {
@Test
void configChange_ReduceBucketSize() {
final AtomicInteger bucketSize = new AtomicInteger(5);
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(bucketSize.get(), Duration.ofMinutes(1), false),
validateRateLimitScript,
@@ -224,7 +224,7 @@ class DynamicRateLimiterTest {
@Test
void configChange_IncreaseBucketSize() {
final AtomicInteger bucketSize = new AtomicInteger(5);
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(bucketSize.get(), Duration.ofMinutes(1), false),
validateRateLimitScript,
@@ -252,7 +252,7 @@ class DynamicRateLimiterTest {
when(failingScript.execute(any(), any())).thenThrow(new RuntimeException("OH NO"));
final AtomicBoolean failOpen = new AtomicBoolean(false);
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, Duration.ofMinutes(1), failOpen.get()),
failingScript,
@@ -275,7 +275,7 @@ class DynamicRateLimiterTest {
when(failingScript.execute(any(), any())).thenThrow(new RuntimeException("OH NO"));
final AtomicBoolean failOpen = new AtomicBoolean(true);
final DynamicRateLimiter rateLimiter = new DynamicRateLimiter(
final LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(
"test",
() -> new RateLimiterConfig(1, Duration.ofMinutes(1), failOpen.get()),
failingScript,
@@ -8,7 +8,7 @@ package org.whispersystems.textsecuregcm.limits;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -52,12 +52,12 @@ class RateLimitChallengeOptionManagerTest {
when(rateLimiters.getPushChallengeAttemptLimiter()).thenReturn(pushChallengeAttemptLimiter);
when(rateLimiters.getPushChallengeSuccessLimiter()).thenReturn(pushChallengeSuccessLimiter);
when(captchaChallengeAttemptLimiter.hasAvailablePermits(any(UUID.class), anyInt())).thenReturn(
when(captchaChallengeAttemptLimiter.hasAvailablePermits(any(UUID.class), anyLong())).thenReturn(
captchaAttemptPermitted);
when(captchaChallengeSuccessLimiter.hasAvailablePermits(any(UUID.class), anyInt())).thenReturn(
when(captchaChallengeSuccessLimiter.hasAvailablePermits(any(UUID.class), anyLong())).thenReturn(
captchaSuccessPermitted);
when(pushChallengeAttemptLimiter.hasAvailablePermits(any(UUID.class), anyInt())).thenReturn(pushAttemptPermitted);
when(pushChallengeSuccessLimiter.hasAvailablePermits(any(UUID.class), anyInt())).thenReturn(pushSuccessPermitted);
when(pushChallengeAttemptLimiter.hasAvailablePermits(any(UUID.class), anyLong())).thenReturn(pushAttemptPermitted);
when(pushChallengeSuccessLimiter.hasAvailablePermits(any(UUID.class), anyLong())).thenReturn(pushSuccessPermitted);
final int expectedLength = (expectCaptcha ? 1 : 0) + (expectPushChallenge ? 1 : 0);
@@ -46,7 +46,6 @@ import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
@@ -68,7 +67,6 @@ public class AccountCreationDeletionIntegrationTest {
DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS,
DynamoDbExtensionSchema.Tables.USERNAMES,
DynamoDbExtensionSchema.Tables.EC_KEYS,
DynamoDbExtensionSchema.Tables.PQ_KEYS,
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS,
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS,
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
@@ -101,7 +99,6 @@ public class AccountCreationDeletionIntegrationTest {
final DynamoDbAsyncClient dynamoDbAsyncClient = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient();
keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.EC_KEYS.tableName()),
new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName()),
new PagedSingleUseKEMPreKeyStore(dynamoDbAsyncClient,
S3_EXTENSION.getS3Client(),
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS.tableName(),
@@ -60,7 +60,6 @@ class AccountsManagerChangeNumberIntegrationTest {
Tables.PNI_ASSIGNMENTS,
Tables.USERNAMES,
Tables.EC_KEYS,
Tables.PQ_KEYS,
Tables.PAGED_PQ_KEYS,
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS,
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
@@ -90,7 +89,6 @@ class AccountsManagerChangeNumberIntegrationTest {
final DynamoDbAsyncClient dynamoDbAsyncClient = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient();
keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.EC_KEYS.tableName()),
new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName()),
new PagedSingleUseKEMPreKeyStore(dynamoDbAsyncClient,
S3_EXTENSION.getS3Client(),
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS.tableName(),
@@ -71,7 +71,6 @@ class AccountsManagerConcurrentModificationIntegrationTest {
Tables.PNI_ASSIGNMENTS,
Tables.DELETED_ACCOUNTS,
Tables.EC_KEYS,
Tables.PQ_KEYS,
Tables.PAGED_PQ_KEYS,
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS,
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
@@ -29,7 +29,6 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
@@ -91,13 +90,10 @@ public class AccountsManagerDeviceTransferIntegrationTest {
accountsManager.stop();
}
@ParameterizedTest
@MethodSource
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
void waitForTransferArchive(
final Optional<Long> recordUploadDeviceCreated,
final Optional<Integer> recordUploadRegistrationId) {
@Test
void waitForTransferArchive() {
final UUID accountIdentifier = UUID.randomUUID();
final int registrationId = 123;
final byte deviceId = Device.PRIMARY_ID;
final RemoteAttachment transferArchive =
@@ -105,8 +101,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
@@ -119,106 +114,62 @@ public class AccountsManagerDeviceTransferIntegrationTest {
assertEquals(Optional.empty(), displacedFuture.join());
accountsManager.recordTransferArchiveUpload(account, deviceId, recordUploadDeviceCreated.map(Instant::ofEpochMilli), recordUploadRegistrationId, transferArchive).join();
accountsManager.recordTransferArchiveUpload(account, deviceId, registrationId, transferArchive).join();
assertEquals(Optional.of(transferArchive), activeFuture.join());
}
private static List<Arguments> waitForTransferArchive() {
final long deviceCreated = System.currentTimeMillis();
final int registrationId = 123;
return List.of(
Arguments.of(Optional.empty(), Optional.of(registrationId)),
Arguments.of(Optional.of(deviceCreated), Optional.empty())
);
}
@ParameterizedTest
@MethodSource
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
void waitForTransferArchiveAlreadyAdded(
final Optional<Long> recordUploadDeviceCreated,
final Optional<Integer> recordUploadRegistrationId) {
@Test
void waitForTransferArchiveAlreadyAdded() {
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 123;
final RemoteAttachment transferArchive =
new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("transfer-archive".getBytes(StandardCharsets.UTF_8)));
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
accountsManager.recordTransferArchiveUpload(account, deviceId, recordUploadDeviceCreated.map(Instant::ofEpochMilli), recordUploadRegistrationId, transferArchive).join();
accountsManager.recordTransferArchiveUpload(account, deviceId, registrationId, transferArchive).join();
assertEquals(Optional.of(transferArchive),
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
}
private static List<Arguments> waitForTransferArchiveAlreadyAdded() {
final long deviceCreated = System.currentTimeMillis();
final int registrationId = 123;
return List.of(
Arguments.of(Optional.empty(), Optional.of(registrationId)),
Arguments.of(Optional.of(deviceCreated), Optional.empty())
);
}
@ParameterizedTest
@MethodSource
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
void waitForErrorTransferArchive(
final Optional<Long> recordUploadDeviceCreated,
final Optional<Integer> recordUploadRegistrationId) {
@Test
void waitForErrorTransferArchive() {
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 123;
final RemoteAttachmentError transferArchiveError =
new RemoteAttachmentError(RemoteAttachmentError.ErrorType.CONTINUE_WITHOUT_UPLOAD);
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(registrationId);
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
accountsManager.recordTransferArchiveUpload(account, deviceId, recordUploadDeviceCreated.map(Instant::ofEpochMilli),
recordUploadRegistrationId, transferArchiveError).join();
accountsManager.recordTransferArchiveUpload(account, deviceId,
registrationId, transferArchiveError).join();
assertEquals(Optional.of(transferArchiveError),
accountsManager.waitForTransferArchive(account, device, Duration.ofSeconds(5)).join());
}
private static List<Arguments> waitForErrorTransferArchive() {
final long deviceCreated = System.currentTimeMillis();
final int registrationId = 123;
return List.of(
Arguments.of(Optional.empty(), Optional.of(registrationId)),
Arguments.of(Optional.of(deviceCreated), Optional.empty())
);
}
@ParameterizedTest
@MethodSource
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
void waitForTransferArchiveTimeout(
final Optional<Long> recordUploadDeviceCreated,
final Optional<Integer> recordUploadRegistrationId) {
@Test
void waitForTransferArchiveTimeout() {
final UUID accountIdentifier = UUID.randomUUID();
final Device device = mock(Device.class);
when(device.getCreated()).thenReturn(recordUploadDeviceCreated.orElse(System.currentTimeMillis()));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(recordUploadRegistrationId.orElse(1));
when(device.getRegistrationId(IdentityType.ACI)).thenReturn(123);
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
@@ -227,16 +178,6 @@ public class AccountsManagerDeviceTransferIntegrationTest {
accountsManager.waitForTransferArchive(account, device, Duration.ofMillis(1)).join());
}
private static List<Arguments> waitForTransferArchiveTimeout() {
final long deviceCreated = System.currentTimeMillis();
final int registrationId = 123;
return List.of(
Arguments.of(Optional.empty(), Optional.of(registrationId)),
Arguments.of(Optional.of(deviceCreated), Optional.empty())
);
}
@Test
void waitForRestoreAccountRequest() {
final String token = RandomStringUtils.secure().nextAlphanumeric(16);
@@ -70,6 +70,7 @@ import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.stubbing.Answer;
@@ -508,13 +509,25 @@ class AccountsManagerTest {
verifyNoMoreInteractions(accounts);
}
@Test
void testGetAccountByUuidBrokenCache() {
enum FailureStep {
GET,
SET_ACI,
SET_PNI
}
@ParameterizedTest
@EnumSource(FailureStep.class)
void testGetAccountByUuidBrokenCache(final FailureStep step) {
UUID uuid = UUID.randomUUID();
UUID pni = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
when(clusterCommands.get(eq("Account3::" + uuid))).thenThrow(new RedisException("Connection lost!"));
(switch (step) {
case GET -> when(clusterCommands.get(eq("Account3::" + uuid)));
case SET_ACI -> when(clusterCommands.setex(eq("Account3::" + uuid), anyLong(), anyString()));
case SET_PNI -> when(clusterCommands.setex(eq("AccountMap::" + pni), anyLong(), eq(uuid.toString())));
}).thenThrow(new RedisException("Connection lost!"));
when(accounts.getByAccountIdentifier(eq(uuid))).thenReturn(Optional.of(account));
Optional<Account> retrieved = accountsManager.getByAccountIdentifier(uuid);
@@ -524,27 +537,35 @@ class AccountsManagerTest {
verify(clusterCommands, times(1)).get(eq("Account3::" + uuid));
verify(clusterCommands, times(1)).setex(eq("AccountMap::" + pni), anyLong(), eq(uuid.toString()));
verify(clusterCommands, times(1)).setex(eq("Account3::" + uuid), anyLong(), anyString());
// we only try setting the ACI if we successfully set the PNI
verify(clusterCommands, times(step == FailureStep.SET_PNI ? 0 : 1))
.setex(eq("Account3::" + uuid), anyLong(), anyString());
verifyNoMoreInteractions(clusterCommands);
verify(accounts, times(1)).getByAccountIdentifier(eq(uuid));
verifyNoMoreInteractions(accounts);
}
@Test
void testGetAccountByUuidBrokenCacheAsync() {
@ParameterizedTest
@EnumSource(FailureStep.class)
void testGetAccountByUuidBrokenCacheAsync(final FailureStep step) {
UUID uuid = UUID.randomUUID();
UUID pni = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
when(asyncClusterCommands.get(eq("Account3::" + uuid)))
.thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost!")));
.thenReturn(MockRedisFuture.completedFuture(null));
when(asyncClusterCommands.setex(any(), anyLong(), any())).thenReturn(MockRedisFuture.completedFuture("OK"));
when(accounts.getByAccountIdentifierAsync(eq(uuid)))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
(switch (step) {
case GET -> when(asyncClusterCommands.get(eq("Account3::" + uuid)));
case SET_ACI -> when(asyncClusterCommands.setex(eq("Account3::" + uuid), anyLong(), anyString()));
case SET_PNI -> when(asyncClusterCommands.setex(eq("AccountMap::" + pni), anyLong(), eq(uuid.toString())));
}).thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost!")));
Optional<Account> retrieved = accountsManager.getByAccountIdentifierAsync(uuid).join();
assertTrue(retrieved.isPresent());
@@ -1497,61 +1518,6 @@ class AccountsManagerTest {
}
}
@Test
void testFirstSuccessfulTransferArchiveCompletableFutureOneTimeout() {
// First future times out, second one completes successfully
final RemoteAttachment transferArchive = new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
final CompletableFuture<Optional<TransferArchiveResult>> timeoutFuture = new CompletableFuture<>();
timeoutFuture.completeOnTimeout(Optional.empty(), 50, TimeUnit.MILLISECONDS);
final CompletableFuture<Optional<TransferArchiveResult>> successfulFuture = new CompletableFuture<>();
final CompletableFuture<Optional<TransferArchiveResult>> result =
AccountsManager.firstSuccessfulTransferArchiveFuture(List.of(timeoutFuture, successfulFuture));
CompletableFuture.delayedExecutor(100, TimeUnit.MILLISECONDS)
.execute(() -> successfulFuture.complete(Optional.of(transferArchive)));
final Optional<TransferArchiveResult> maybeTransferArchive = result.join();
assertTrue(maybeTransferArchive.isPresent());
assertEquals(transferArchive, maybeTransferArchive.get());
}
@Test
void testFirstSuccessfulTransferArchiveCompletableFutureBothTimeout() {
// Both futures time out
final CompletableFuture<Optional<TransferArchiveResult>> firstTimeoutFuture = new CompletableFuture<>();
firstTimeoutFuture.completeOnTimeout(Optional.empty(), 10, TimeUnit.MILLISECONDS);
final CompletableFuture<Optional<TransferArchiveResult>> secondTimeoutFuture = new CompletableFuture<>();
secondTimeoutFuture.completeOnTimeout(Optional.empty(), 10, TimeUnit.MILLISECONDS);
final CompletableFuture<Optional<TransferArchiveResult>> result =
AccountsManager.firstSuccessfulTransferArchiveFuture(List.of(firstTimeoutFuture, secondTimeoutFuture));
assertTrue(result.join().isEmpty());
}
@Test
void testFirstSuccessfulTransferArchiveCompletableFuture() {
// First future completes successfully, second one times out
final RemoteAttachment transferArchive = new RemoteAttachment(3, Base64.getUrlEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
final CompletableFuture<Optional<TransferArchiveResult>> successfulFuture = new CompletableFuture<>();
final CompletableFuture<Optional<TransferArchiveResult>> timeoutFuture = new CompletableFuture<>();
timeoutFuture.completeOnTimeout(Optional.empty(), 50, TimeUnit.MILLISECONDS);
final CompletableFuture<Optional<TransferArchiveResult>> result =
AccountsManager.firstSuccessfulTransferArchiveFuture(List.of(successfulFuture, timeoutFuture));
successfulFuture.complete(Optional.of(transferArchive));
final Optional<TransferArchiveResult> maybeTransferArchive = result.join();
assertTrue(maybeTransferArchive.isPresent());
assertEquals(transferArchive, maybeTransferArchive.get());
}
private static List<Arguments> validateCompleteDeviceList() {
final byte deviceId = Device.PRIMARY_ID;
final byte extraDeviceId = deviceId + 1;
@@ -73,7 +73,6 @@ class AccountsManagerUsernameIntegrationTest {
Tables.PNI,
Tables.PNI_ASSIGNMENTS,
Tables.EC_KEYS,
Tables.PQ_KEYS,
Tables.PAGED_PQ_KEYS,
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS,
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
@@ -103,7 +102,6 @@ class AccountsManagerUsernameIntegrationTest {
final DynamoDbAsyncClient dynamoDbAsyncClient = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient();
final KeysManager keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.EC_KEYS.tableName()),
new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName()),
new PagedSingleUseKEMPreKeyStore(dynamoDbAsyncClient,
S3_EXTENSION.getS3Client(),
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS.tableName(),
@@ -62,7 +62,6 @@ public class AddRemoveDeviceIntegrationTest {
DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS,
DynamoDbExtensionSchema.Tables.USERNAMES,
DynamoDbExtensionSchema.Tables.EC_KEYS,
DynamoDbExtensionSchema.Tables.PQ_KEYS,
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS,
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS,
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
@@ -98,7 +97,6 @@ public class AddRemoveDeviceIntegrationTest {
final DynamoDbAsyncClient dynamoDbAsyncClient = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient();
keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.EC_KEYS.tableName()),
new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName()),
new PagedSingleUseKEMPreKeyStore(dynamoDbAsyncClient,
S3_EXTENSION.getS3Client(),
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS.tableName(),
@@ -472,7 +470,6 @@ public class AddRemoveDeviceIntegrationTest {
final DeviceInfo deviceInfo = maybeDeviceInfo.get();
assertEquals(updatedAccountAndDevice.second().getId(), deviceInfo.id());
assertEquals(updatedAccountAndDevice.second().getCreated(), deviceInfo.created());
assertEquals(updatedAccountAndDevice.second().getRegistrationId(IdentityType.ACI), deviceInfo.registrationId());
assertNotNull(deviceInfo.createdAtCiphertext());
}
@@ -521,7 +518,6 @@ public class AddRemoveDeviceIntegrationTest {
final DeviceInfo deviceInfo = maybeDeviceInfo.get();
assertEquals(updatedAccountAndDevice.second().getId(), deviceInfo.id());
assertEquals(updatedAccountAndDevice.second().getCreated(), deviceInfo.created());
assertEquals(updatedAccountAndDevice.second().getRegistrationId(IdentityType.ACI), deviceInfo.registrationId());
assertNotNull(deviceInfo.createdAtCiphertext());
}
@@ -546,13 +542,12 @@ public class AddRemoveDeviceIntegrationTest {
@ParameterizedTest
@CsvSource({
"10_000,1000,,false", // no pending messages
"10_000,1000,1000,true", // pending message at device creation
"10_000,1000,5999,true", // pending message right before device creation + fudge factor
"10_000,1000,6000,false", // pending message at device creation + fudge factor
"3000,5000,4000,false", // pending message after current time but before device creation
"10_000,,false", // no pending messages
"10_000,9999,true", // pending message right before now
"10_000,10_000,false", // pending message at now
"10_000,10_001,false", // pending message after now
})
void waitForMessageFetch(long currentTime, long deviceCreation, Long oldestMessage, boolean shouldWait)
void waitForMessageFetch(long currentTime, Long oldestMessage, boolean shouldWait)
throws InterruptedException {
final String number = PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("US"),
@@ -564,7 +559,6 @@ public class AddRemoveDeviceIntegrationTest {
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(UUID.randomUUID());
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
clock.pin(Instant.ofEpochMilli(deviceCreation));
final Pair<Account, Device> updatedAccountAndDevice =
accountsManager.addDevice(account, new DeviceSpec(
"device-name".getBytes(StandardCharsets.UTF_8),
@@ -583,8 +577,6 @@ public class AddRemoveDeviceIntegrationTest {
linkDeviceToken)
.join();
assertEquals(updatedAccountAndDevice.second().getCreated(), deviceCreation);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(account.getUuid(), account.getPrimaryDevice()))
.thenReturn(CompletableFuture.completedFuture(Optional.ofNullable(oldestMessage).map(Instant::ofEpochMilli)));
@@ -116,29 +116,15 @@ public final class DynamoDbExtensionSchema {
List.of(), List.of()),
EC_KEYS("keys_test",
SingleUsePreKeyStore.KEY_ACCOUNT_UUID,
SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID,
SingleUseECPreKeyStore.KEY_ACCOUNT_UUID,
SingleUseECPreKeyStore.KEY_DEVICE_ID_KEY_ID,
List.of(
AttributeDefinition.builder()
.attributeName(SingleUsePreKeyStore.KEY_ACCOUNT_UUID)
.attributeName(SingleUseECPreKeyStore.KEY_ACCOUNT_UUID)
.attributeType(ScalarAttributeType.B)
.build(),
AttributeDefinition.builder()
.attributeName(SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(), List.of()),
PQ_KEYS("pq_keys_test",
SingleUsePreKeyStore.KEY_ACCOUNT_UUID,
SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID,
List.of(
AttributeDefinition.builder()
.attributeName(SingleUsePreKeyStore.KEY_ACCOUNT_UUID)
.attributeType(ScalarAttributeType.B)
.build(),
AttributeDefinition.builder()
.attributeName(SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID)
.attributeName(SingleUseECPreKeyStore.KEY_DEVICE_ID_KEY_ID)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(), List.of()),
@@ -30,12 +30,11 @@ class KeysManagerTest {
private KeysManager keysManager;
private SingleUseKEMPreKeyStore singleUseKEMPreKeyStore;
private PagedSingleUseKEMPreKeyStore pagedSingleUseKEMPreKeyStore;
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
Tables.EC_KEYS, Tables.PQ_KEYS, Tables.PAGED_PQ_KEYS,
Tables.EC_KEYS, Tables.PAGED_PQ_KEYS,
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS, Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS);
@RegisterExtension
@@ -50,7 +49,6 @@ class KeysManagerTest {
@BeforeEach
void setup() {
final DynamoDbAsyncClient dynamoDbAsyncClient = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient();
singleUseKEMPreKeyStore = new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, Tables.PQ_KEYS.tableName());
pagedSingleUseKEMPreKeyStore = new PagedSingleUseKEMPreKeyStore(dynamoDbAsyncClient,
S3_EXTENSION.getS3Client(),
DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS.tableName(),
@@ -58,7 +56,6 @@ class KeysManagerTest {
keysManager = new KeysManager(
new SingleUseECPreKeyStore(dynamoDbAsyncClient, Tables.EC_KEYS.tableName()),
singleUseKEMPreKeyStore,
pagedSingleUseKEMPreKeyStore,
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName()),
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()));
@@ -77,24 +74,6 @@ class KeysManagerTest {
"Repeatedly storing same key should have no effect");
}
@Test
void storeKemOneTimePreKeysClearsOld() {
final List<KEMSignedPreKey> oldPreKeys = List.of(generateTestKEMSignedPreKey(1));
// Leave a key in the 'old' key store
singleUseKEMPreKeyStore.store(ACCOUNT_UUID, DEVICE_ID, oldPreKeys).join();
final List<KEMSignedPreKey> newPreKeys = List.of(generateTestKEMSignedPreKey(2));
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, newPreKeys).join();
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
assertEquals(1, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
assertEquals(0, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
final KEMSignedPreKey key = keysManager.takePQ(ACCOUNT_UUID, DEVICE_ID).join().orElseThrow();
assertEquals(2, key.keyId());
}
@Test
void storeKemOneTimePreKeys() {
assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join(),
@@ -103,12 +82,10 @@ class KeysManagerTest {
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestKEMSignedPreKey(1))).join();
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
assertEquals(1, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
assertEquals(0, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestKEMSignedPreKey(1))).join();
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
assertEquals(1, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
assertEquals(0, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
}
@@ -31,6 +31,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
@@ -163,14 +164,19 @@ public class ProfilesManagerTest {
verifyNoMoreInteractions(profiles);
}
@Test
public void testGetProfileBrokenCache() {
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testGetProfileBrokenCache(final boolean failUpdateCache) {
final UUID uuid = UUID.randomUUID();
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
when(commands.hget(eq(ProfilesManager.getCacheKey(uuid)), eq("someversion"))).thenThrow(new RedisException("Connection lost"));
if (failUpdateCache) {
when(commands.hset(eq(ProfilesManager.getCacheKey(uuid)), eq("someversion"), anyString()))
.thenThrow(new RedisException("Connection lost"));
}
when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile));
Optional<VersionedProfile> retrieved = profilesManager.get(uuid, "someversion");
@@ -186,15 +192,19 @@ public class ProfilesManagerTest {
verifyNoMoreInteractions(profiles);
}
@Test
public void testGetProfileAsyncBrokenCache() {
@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testGetProfileAsyncBrokenCache(final boolean failUpdateCache) {
final UUID uuid = UUID.randomUUID();
final byte[] name = TestRandomUtil.nextBytes(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, null, "somecommitment".getBytes());
when(asyncCommands.hget(eq(ProfilesManager.getCacheKey(uuid)), eq("someversion"))).thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost")));
when(asyncCommands.hset(eq(ProfilesManager.getCacheKey(uuid)), eq("someversion"), anyString())).thenReturn(MockRedisFuture.completedFuture(null));
when(asyncCommands.hset(eq(ProfilesManager.getCacheKey(uuid)), eq("someversion"), anyString()))
.thenReturn(failUpdateCache
? MockRedisFuture.failedFuture(new RedisException("Connection lost"))
: MockRedisFuture.completedFuture(null));
when(profiles.getAsync(eq(uuid), eq("someversion"))).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
Optional<VersionedProfile> retrieved = profilesManager.getAsync(uuid, "someversion").join();
@@ -5,7 +5,20 @@
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
@@ -14,10 +27,10 @@ import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable;
import java.util.Map;
class SingleUseECPreKeyStoreTest extends SingleUsePreKeyStoreTest<ECPreKey> {
class SingleUseECPreKeyStoreTest {
private static final int KEY_COUNT = 100;
private SingleUseECPreKeyStore preKeyStore;
@RegisterExtension
@@ -29,18 +42,11 @@ class SingleUseECPreKeyStoreTest extends SingleUsePreKeyStoreTest<ECPreKey> {
DynamoDbExtensionSchema.Tables.EC_KEYS.tableName());
}
@Override
protected SingleUsePreKeyStore<ECPreKey> getPreKeyStore() {
return preKeyStore;
}
@Override
protected ECPreKey generatePreKey(final long keyId) {
private ECPreKey generatePreKey(final long keyId) {
return new ECPreKey(keyId, ECKeyPair.generate().getPublicKey());
}
@Override
protected void clearKeyCountAttributes() {
private void clearKeyCountAttributes() {
final ScanIterable scanIterable = DYNAMO_DB_EXTENSION.getDynamoDbClient().scanPaginator(ScanRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.EC_KEYS.tableName())
.build());
@@ -51,11 +57,113 @@ class SingleUseECPreKeyStoreTest extends SingleUsePreKeyStoreTest<ECPreKey> {
DYNAMO_DB_EXTENSION.getDynamoDbClient().updateItem(UpdateItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.EC_KEYS.tableName())
.key(Map.of(
SingleUsePreKeyStore.KEY_ACCOUNT_UUID, item.get(SingleUsePreKeyStore.KEY_ACCOUNT_UUID),
SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID, item.get(SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID)))
.updateExpression("REMOVE " + SingleUsePreKeyStore.ATTR_REMAINING_KEYS)
SingleUseECPreKeyStore.KEY_ACCOUNT_UUID, item.get(SingleUseECPreKeyStore.KEY_ACCOUNT_UUID),
SingleUseECPreKeyStore.KEY_DEVICE_ID_KEY_ID, item.get(SingleUseECPreKeyStore.KEY_DEVICE_ID_KEY_ID)))
.updateExpression("REMOVE " + SingleUseECPreKeyStore.ATTR_REMAINING_KEYS)
.build());
}
}
}
@Test
void storeTake() {
final SingleUseECPreKeyStore preKeyStore = this.preKeyStore;
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(Optional.empty(), preKeyStore.take(accountIdentifier, deviceId).join());
final List<ECPreKey> sortedPreKeys;
{
final List<ECPreKey> preKeys = generateRandomPreKeys();
assertDoesNotThrow(() -> preKeyStore.store(accountIdentifier, deviceId, preKeys).join());
sortedPreKeys = new ArrayList<>(preKeys);
sortedPreKeys.sort(Comparator.comparing(preKey -> preKey.keyId()));
}
assertEquals(Optional.of(sortedPreKeys.get(0)), preKeyStore.take(accountIdentifier, deviceId).join());
assertEquals(Optional.of(sortedPreKeys.get(1)), preKeyStore.take(accountIdentifier, deviceId).join());
}
@Test
void getCount() {
final SingleUseECPreKeyStore preKeyStore = this.preKeyStore;
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
final List<ECPreKey> preKeys = generateRandomPreKeys();
preKeyStore.store(accountIdentifier, deviceId, preKeys).join();
assertEquals(KEY_COUNT, preKeyStore.getCount(accountIdentifier, deviceId).join());
for (int i = 0; i < KEY_COUNT; i++) {
preKeyStore.take(accountIdentifier, deviceId).join();
assertEquals(KEY_COUNT - (i + 1), preKeyStore.getCount(accountIdentifier, deviceId).join());
}
preKeyStore.store(accountIdentifier, deviceId, List.of(generatePreKey(KEY_COUNT + 1))).join();
clearKeyCountAttributes();
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
}
@Test
void deleteSingleDevice() {
final SingleUseECPreKeyStore preKeyStore = this.preKeyStore;
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier, deviceId).join());
final List<ECPreKey> preKeys = generateRandomPreKeys();
preKeyStore.store(accountIdentifier, deviceId, preKeys).join();
preKeyStore.store(accountIdentifier, (byte) (deviceId + 1), preKeys).join();
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier, deviceId).join());
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertEquals(KEY_COUNT, preKeyStore.getCount(accountIdentifier, (byte) (deviceId + 1)).join());
}
@Test
void deleteAllDevices() {
final SingleUseECPreKeyStore preKeyStore = this.preKeyStore;
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier).join());
final List<ECPreKey> preKeys = generateRandomPreKeys();
preKeyStore.store(accountIdentifier, deviceId, preKeys).join();
preKeyStore.store(accountIdentifier, (byte) (deviceId + 1), preKeys).join();
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier).join());
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertEquals(0, preKeyStore.getCount(accountIdentifier, (byte) (deviceId + 1)).join());
}
private List<ECPreKey> generateRandomPreKeys() {
final Set<Integer> keyIds = new HashSet<>(KEY_COUNT);
while (keyIds.size() < KEY_COUNT) {
keyIds.add(Math.abs(ThreadLocalRandom.current().nextInt()));
}
return keyIds.stream()
.map(this::generatePreKey)
.toList();
}
}
@@ -1,64 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable;
import java.util.Map;
class SingleUseKEMPreKeyStoreTest extends SingleUsePreKeyStoreTest<KEMSignedPreKey> {
private SingleUseKEMPreKeyStore preKeyStore;
private static final ECKeyPair IDENTITY_KEY_PAIR = ECKeyPair.generate();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.PQ_KEYS);
@BeforeEach
void setUp() {
preKeyStore = new SingleUseKEMPreKeyStore(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName());
}
@Override
protected SingleUsePreKeyStore<KEMSignedPreKey> getPreKeyStore() {
return preKeyStore;
}
@Override
protected KEMSignedPreKey generatePreKey(final long keyId) {
return KeysHelper.signedKEMPreKey(keyId, IDENTITY_KEY_PAIR);
}
@Override
protected void clearKeyCountAttributes() {
final ScanIterable scanIterable = DYNAMO_DB_EXTENSION.getDynamoDbClient().scanPaginator(ScanRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName())
.build());
for (final ScanResponse response : scanIterable) {
for (final Map<String, AttributeValue> item : response.items()) {
DYNAMO_DB_EXTENSION.getDynamoDbClient().updateItem(UpdateItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName())
.key(Map.of(
SingleUsePreKeyStore.KEY_ACCOUNT_UUID, item.get(SingleUsePreKeyStore.KEY_ACCOUNT_UUID),
SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID, item.get(SingleUsePreKeyStore.KEY_DEVICE_ID_KEY_ID)))
.updateExpression("REMOVE " + SingleUsePreKeyStore.ATTR_REMAINING_KEYS)
.build());
}
}
}
}
@@ -1,133 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.entities.PreKey;
abstract class SingleUsePreKeyStoreTest<K extends PreKey<?>> {
private static final int KEY_COUNT = 100;
protected abstract SingleUsePreKeyStore<K> getPreKeyStore();
protected abstract K generatePreKey(final long keyId);
protected abstract void clearKeyCountAttributes();
@Test
void storeTake() {
final SingleUsePreKeyStore<K> preKeyStore = getPreKeyStore();
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(Optional.empty(), preKeyStore.take(accountIdentifier, deviceId).join());
final List<K> sortedPreKeys;
{
final List<K> preKeys = generateRandomPreKeys();
assertDoesNotThrow(() -> preKeyStore.store(accountIdentifier, deviceId, preKeys).join());
sortedPreKeys = new ArrayList<>(preKeys);
sortedPreKeys.sort(Comparator.comparing(preKey -> preKey.keyId()));
}
assertEquals(Optional.of(sortedPreKeys.get(0)), preKeyStore.take(accountIdentifier, deviceId).join());
assertEquals(Optional.of(sortedPreKeys.get(1)), preKeyStore.take(accountIdentifier, deviceId).join());
}
@Test
void getCount() {
final SingleUsePreKeyStore<K> preKeyStore = getPreKeyStore();
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
final List<K> preKeys = generateRandomPreKeys();
preKeyStore.store(accountIdentifier, deviceId, preKeys).join();
assertEquals(KEY_COUNT, preKeyStore.getCount(accountIdentifier, deviceId).join());
for (int i = 0; i < KEY_COUNT; i++) {
preKeyStore.take(accountIdentifier, deviceId).join();
assertEquals(KEY_COUNT - (i + 1), preKeyStore.getCount(accountIdentifier, deviceId).join());
}
preKeyStore.store(accountIdentifier, deviceId, List.of(generatePreKey(KEY_COUNT + 1))).join();
clearKeyCountAttributes();
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
}
@Test
void deleteSingleDevice() {
final SingleUsePreKeyStore<K> preKeyStore = getPreKeyStore();
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier, deviceId).join());
final List<K> preKeys = generateRandomPreKeys();
preKeyStore.store(accountIdentifier, deviceId, preKeys).join();
preKeyStore.store(accountIdentifier, (byte) (deviceId + 1), preKeys).join();
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier, deviceId).join());
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertEquals(KEY_COUNT, preKeyStore.getCount(accountIdentifier, (byte) (deviceId + 1)).join());
}
@Test
void deleteAllDevices() {
final SingleUsePreKeyStore<K> preKeyStore = getPreKeyStore();
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier).join());
final List<K> preKeys = generateRandomPreKeys();
preKeyStore.store(accountIdentifier, deviceId, preKeys).join();
preKeyStore.store(accountIdentifier, (byte) (deviceId + 1), preKeys).join();
assertDoesNotThrow(() -> preKeyStore.delete(accountIdentifier).join());
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
assertEquals(0, preKeyStore.getCount(accountIdentifier, (byte) (deviceId + 1)).join());
}
private List<K> generateRandomPreKeys() {
final Set<Integer> keyIds = new HashSet<>(KEY_COUNT);
while (keyIds.size() < KEY_COUNT) {
keyIds.add(Math.abs(ThreadLocalRandom.current().nextInt()));
}
return keyIds.stream()
.map(this::generatePreKey)
.toList();
}
}
@@ -66,6 +66,21 @@ message ValidationsRequest {
message RequirePresentMessage {}
RequirePresentMessage presentMessage = 25 [(require.present) = true];
optional RequirePresentMessage optionalPresentMessage = 26 [(require.present) = true];
NestedMessage nested = 27;
repeated NestedMessage repeatedNested = 28;
map<string, NestedMessage> mapNested = 29;
RecursiveMessage recursiveMessage = 30;
}
message NestedMessage {
int32 i32 = 1 [(require.range).max = 100];
}
message RecursiveMessage {
RecursiveMessage next = 1;
int32 i32 = 2 [(require.range).max = 100];
}
message MessageWithInvalidRangeConstraint {
@@ -108,8 +108,6 @@ dynamoDbTables:
tableName: keys_test
ecSignedPreKeys:
tableName: repeated_use_signed_ec_pre_keys_test
pqKeys:
tableName: pq_keys_test
pagedPqKeys:
tableName: paged_pq_keys_test
pqLastResortKeys: