mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 04:56:47 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d18f576239 | ||
|
|
7d483c711a | ||
|
|
61256d49cd | ||
|
|
184cdc0331 | ||
|
|
ed972a0037 | ||
|
|
a62a6c1cb6 | ||
|
|
ba0c6be3e3 | ||
|
|
f66566aa17 | ||
|
|
b6ecfc7131 | ||
|
|
460dc6224c | ||
|
|
2b688b1a60 | ||
|
|
3c64d9292f | ||
|
|
0f52d2e464 | ||
|
|
1e5fadc440 | ||
|
|
f495ff483a |
No files matched your search
@@ -65,6 +65,8 @@ fcm.credentials: |
|
||||
cdn.accessKey: test # AWS Access Key ID
|
||||
cdn.accessSecret: test # AWS Access Secret
|
||||
|
||||
cdn3StorageManager.clientSecret: test
|
||||
|
||||
unidentifiedDelivery.certificate: ABCD1234
|
||||
unidentifiedDelivery.privateKey: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789AAAAAAA
|
||||
|
||||
|
||||
@@ -273,6 +273,11 @@ clientCdn:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
cdn3StorageManager:
|
||||
baseUri: https://storage-manager.example.com
|
||||
clientId: example
|
||||
clientSecret: secret://cdn3StorageManager.clientSecret
|
||||
|
||||
dogstatsd:
|
||||
environment: dev
|
||||
|
||||
|
||||
+11
-1
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ClientCdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
|
||||
@@ -108,6 +109,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private ClientCdnConfiguration clientCdn;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private Cdn3StorageManagerConfiguration cdn3StorageManager;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -421,10 +427,14 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return cdn;
|
||||
}
|
||||
|
||||
public ClientCdnConfiguration getClientCdn() {
|
||||
public ClientCdnConfiguration getClientCdnConfiguration() {
|
||||
return clientCdn;
|
||||
}
|
||||
|
||||
public Cdn3StorageManagerConfiguration getCdn3StorageManagerConfiguration() {
|
||||
return cdn3StorageManager;
|
||||
}
|
||||
|
||||
public DogstatsdConfiguration getDatadogConfiguration() {
|
||||
return dogstatsd;
|
||||
}
|
||||
|
||||
@@ -215,7 +215,6 @@ import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.MigrateSignedECPreKeysCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessPushNotificationFeedbackCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
|
||||
@@ -273,7 +272,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new UnlinkDeviceCommand());
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new MigrateSignedECPreKeysCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new ProcessPushNotificationFeedbackCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
@@ -355,8 +353,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getEcKeys().getTableName(),
|
||||
config.getDynamoDbTables().getKemKeys().getTableName(),
|
||||
config.getDynamoDbTables().getEcSignedPreKeys().getTableName(),
|
||||
config.getDynamoDbTables().getKemLastResortKeys().getTableName(),
|
||||
dynamicConfigurationManager);
|
||||
config.getDynamoDbTables().getKemLastResortKeys().getTableName()
|
||||
);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getMessages().getTableName(),
|
||||
config.getDynamoDbTables().getMessages().getExpiration(),
|
||||
@@ -665,7 +663,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
BackupsDb backupsDb = new BackupsDb(
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getBackups().getTableName(),
|
||||
config.getDynamoDbTables().getBackupMedia().getTableName(),
|
||||
clock);
|
||||
BackupManager backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
@@ -673,10 +670,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
cdn3BackupCredentialGenerator,
|
||||
new Cdn3RemoteStorageManager(
|
||||
remoteStorageExecutor,
|
||||
config.getClientCdn().getCircuitBreaker(),
|
||||
config.getClientCdn().getRetry(),
|
||||
config.getClientCdn().getCaCertificates()),
|
||||
config.getClientCdn().getAttachmentUrls(),
|
||||
config.getClientCdnConfiguration().getCircuitBreaker(),
|
||||
config.getClientCdnConfiguration().getRetry(),
|
||||
config.getClientCdnConfiguration().getCaCertificates(),
|
||||
config.getCdn3StorageManagerConfiguration()),
|
||||
config.getClientCdnConfiguration().getAttachmentUrls(),
|
||||
clock);
|
||||
|
||||
final BasicCredentialAuthenticationInterceptor basicCredentialAuthenticationInterceptor =
|
||||
|
||||
@@ -5,15 +5,19 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.grpc.Status;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.net.URI;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
@@ -28,14 +32,20 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
|
||||
public class BackupManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BackupManager.class);
|
||||
|
||||
static final String MEDIA_DIRECTORY_NAME = "media";
|
||||
static final String MESSAGE_BACKUP_NAME = "messageBackup";
|
||||
private static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = 1024L * 1024L * 1024L * 50L;
|
||||
private static final long MAX_MEDIA_OBJECT_SIZE = 1024L * 1024L * 101L;
|
||||
static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = 1024L * 1024L * 1024L * 50L;
|
||||
static final long MAX_MEDIA_OBJECT_SIZE = 1024L * 1024L * 101L;
|
||||
// If the last media usage recalculation is over MAX_QUOTA_STALENESS, force a recalculation before quota enforcement.
|
||||
static final Duration MAX_QUOTA_STALENESS = Duration.ofDays(1);
|
||||
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
|
||||
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
|
||||
"authorizationFailure");
|
||||
private static final String USAGE_RECALCULATION_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
|
||||
"usageRecalculation");
|
||||
private static final String SUCCESS_TAG_NAME = "success";
|
||||
private static final String FAILURE_REASON_TAG_NAME = "reason";
|
||||
|
||||
@@ -175,22 +185,41 @@ public class BackupManager {
|
||||
.withDescription("credential does not support storing media")
|
||||
.asRuntimeException();
|
||||
}
|
||||
return backupsDb.describeBackup(backupUser)
|
||||
.thenApply(info -> info.mediaUsedSpace()
|
||||
.filter(usedSpace -> MAX_TOTAL_BACKUP_MEDIA_BYTES - usedSpace >= mediaLength)
|
||||
.isPresent());
|
||||
return backupsDb.getMediaUsage(backupUser)
|
||||
.thenComposeAsync(info -> {
|
||||
final boolean canStore = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed() >= mediaLength;
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(MAX_QUOTA_STALENESS))) {
|
||||
return CompletableFuture.completedFuture(canStore);
|
||||
}
|
||||
|
||||
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
|
||||
// hard recalculation before actually forbidding the user from storing additional media.
|
||||
final String mediaPrefix = "%s/%s/".formatted(encodeBackupIdForCdn(backupUser), MEDIA_DIRECTORY_NAME);
|
||||
return this.remoteStorageManager.calculateBytesUsed(mediaPrefix)
|
||||
.thenCompose(usage -> backupsDb
|
||||
.setMediaUsage(backupUser, usage)
|
||||
.thenApply(ignored -> usage.bytesUsed()))
|
||||
.whenComplete((newUsage, throwable) -> {
|
||||
boolean usageChanged = throwable == null && !newUsage.equals(info.usageInfo());
|
||||
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, "usageChanged", String.valueOf(usageChanged))
|
||||
.increment();
|
||||
})
|
||||
.thenApply(usedSpace -> MAX_TOTAL_BACKUP_MEDIA_BYTES - usedSpace >= mediaLength);
|
||||
});
|
||||
}
|
||||
|
||||
public record StorageDescriptor(int cdn, byte[] key) {}
|
||||
|
||||
public record StorageDescriptorWithLength(int cdn, byte[] key, long length) {}
|
||||
|
||||
/**
|
||||
* Copy an encrypted object to the backup cdn, adding a layer of encryption
|
||||
* <p>
|
||||
* Implementation notes: <p> This method guarantees that any object that gets successfully copied to the backup cdn
|
||||
* will also have an entry for the user in the database. <p>
|
||||
* will also be deducted from the user's quota. </p>
|
||||
* <p>
|
||||
* However, the converse isn't true; there may be entries in the database that have not made it to the cdn. On list,
|
||||
* these entries are checked against the cdn and removed.
|
||||
* However, the converse isn't true. It's possible we may charge the user for media they failed to copy. As a result,
|
||||
* the quota may be over reported and it should be recalculated before taking quota enforcement actions.
|
||||
*
|
||||
* @return A stage that completes successfully with location of the twice-encrypted object on the backup cdn. The
|
||||
* returned CompletionStage can be completed exceptionally with the following exceptions.
|
||||
@@ -221,21 +250,27 @@ public class BackupManager {
|
||||
|
||||
final MessageBackupUploadDescriptor dst = cdn3BackupCredentialGenerator.generateUpload(
|
||||
encodeBackupIdForCdn(backupUser),
|
||||
encodeForCdn(destinationMediaId));
|
||||
"%s/%s".formatted(MEDIA_DIRECTORY_NAME, encodeForCdn(destinationMediaId)));
|
||||
|
||||
final int destinationLength = encryptionParameters.outputSize(sourceLength);
|
||||
|
||||
final URI sourceUri = attachmentReadUri(sourceCdn, sourceKey);
|
||||
return this.backupsDb
|
||||
// Write the ddb updates before actually updating backing storage
|
||||
.trackMedia(backupUser, destinationMediaId, sourceLength)
|
||||
|
||||
// copy the objects. On a failure, make a best-effort attempt to reverse the ddb transaction. If cleanup fails
|
||||
// the client may be left with some cleanup to do if they don't eventually upload the media id.
|
||||
.thenCompose(ignored -> remoteStorageManager
|
||||
// actually perform the copy
|
||||
.copy(attachmentReadUri(sourceCdn, sourceKey), sourceLength, encryptionParameters, dst)
|
||||
// best effort: on failure, untrack the copied media
|
||||
.exceptionallyCompose(copyError -> backupsDb.untrackMedia(backupUser, destinationMediaId, sourceLength)
|
||||
.thenCompose(ignoredSuccess -> CompletableFuture.failedFuture(copyError))))
|
||||
.trackMedia(backupUser, destinationLength)
|
||||
|
||||
// Actually copy the objects. If the copy fails, our estimated quota usage may not be exact
|
||||
.thenComposeAsync(ignored -> remoteStorageManager.copy(sourceUri, sourceLength, encryptionParameters, dst))
|
||||
.exceptionallyCompose(throwable -> {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
|
||||
if (!(unwrapped instanceof SourceObjectNotFoundException) && !(unwrapped instanceof InvalidLengthException)) {
|
||||
throw ExceptionUtils.wrap(unwrapped);
|
||||
}
|
||||
// In cases where we know the copy fails without writing anything, we can try to restore the user's quota
|
||||
return this.backupsDb.trackMedia(backupUser, -destinationLength).whenComplete((ignored, ignoredEx) -> {
|
||||
throw ExceptionUtils.wrap(unwrapped);
|
||||
});
|
||||
})
|
||||
// indicates where the backup was stored
|
||||
.thenApply(ignore -> new StorageDescriptor(dst.cdn(), destinationMediaId));
|
||||
|
||||
@@ -268,12 +303,55 @@ public class BackupManager {
|
||||
throw Status.PERMISSION_DENIED
|
||||
.withDescription("credential does not support read auth operation")
|
||||
.asRuntimeException();
|
||||
|
||||
}
|
||||
final String encodedBackupId = encodeBackupIdForCdn(backupUser);
|
||||
return cdn3BackupCredentialGenerator.readHeaders(encodedBackupId);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* List of media stored for a particular backup id
|
||||
*
|
||||
* @param media A page of media entries
|
||||
* @param cursor If set, can be passed back to a subsequent list request to resume listing from the previous point
|
||||
*/
|
||||
public record ListMediaResult(List<StorageDescriptorWithLength> media, Optional<String> cursor) {}
|
||||
|
||||
/**
|
||||
* List the media stored by the backupUser
|
||||
*
|
||||
* @param backupUser An already ZK authenticated backup user
|
||||
* @param cursor A cursor returned by a previous call that can be used to resume listing
|
||||
* @param limit The maximum number of list results to return
|
||||
* @return A {@link ListMediaResult}
|
||||
*/
|
||||
public CompletionStage<ListMediaResult> list(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final Optional<String> cursor,
|
||||
final int limit) {
|
||||
if (backupUser.backupTier().compareTo(BackupTier.MESSAGES) < 0) {
|
||||
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME).increment();
|
||||
throw Status.PERMISSION_DENIED
|
||||
.withDescription("credential does not support list operation")
|
||||
.asRuntimeException();
|
||||
}
|
||||
final String mediaPrefix = "%s/%s/".formatted(encodeBackupIdForCdn(backupUser), MEDIA_DIRECTORY_NAME);
|
||||
return remoteStorageManager.list(mediaPrefix, cursor, limit)
|
||||
.thenApply(result ->
|
||||
new ListMediaResult(
|
||||
result
|
||||
.objects()
|
||||
.stream()
|
||||
.map(entry -> new StorageDescriptorWithLength(
|
||||
remoteStorageManager.cdnNumber(),
|
||||
decodeFromCdn(entry.key()),
|
||||
entry.length()
|
||||
))
|
||||
.toList(),
|
||||
result.cursor()
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate the ZK anonymous backup credential's presentation
|
||||
* <p>
|
||||
@@ -369,7 +447,8 @@ public class BackupManager {
|
||||
});
|
||||
}
|
||||
|
||||
private static String encodeBackupIdForCdn(final AuthenticatedBackupUser backupUser) {
|
||||
@VisibleForTesting
|
||||
static String encodeBackupIdForCdn(final AuthenticatedBackupUser backupUser) {
|
||||
return encodeForCdn(BackupsDb.hashedBackupId(backupUser.backupId()));
|
||||
}
|
||||
|
||||
@@ -377,4 +456,8 @@ public class BackupManager {
|
||||
return Base64.getUrlEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private static byte[] decodeFromCdn(final String base64) {
|
||||
return Base64.getUrlDecoder().decode(base64);
|
||||
}
|
||||
|
||||
}
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import java.net.http.HttpRequest;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
|
||||
@@ -4,6 +4,7 @@ import io.grpc.Status;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
@@ -11,7 +12,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -22,31 +22,24 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Delete;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Put;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
/**
|
||||
* Tracks backup metadata in a persistent store.
|
||||
*
|
||||
* <p>
|
||||
* It's assumed that the caller has already validated that the backupUser being operated on has valid credentials and
|
||||
* possesses the appropriate {@link BackupTier} to perform the current operation.
|
||||
*/
|
||||
public class BackupsDb {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BackupsDb.class);
|
||||
static final int BACKUP_CDN = 3;
|
||||
|
||||
private final DynamoDbAsyncClient dynamoClient;
|
||||
private final String backupTableName;
|
||||
private final String backupMediaTableName;
|
||||
private final Clock clock;
|
||||
|
||||
// The backups table
|
||||
@@ -68,31 +61,25 @@ public class BackupsDb {
|
||||
public static final String ATTR_MEDIA_COUNT = "MC";
|
||||
// N: The cdn number where the message backup is stored
|
||||
public static final String ATTR_CDN = "CDN";
|
||||
|
||||
// The stored media table (hashedBackupId, mediaId, cdn, objectLength)
|
||||
|
||||
// B: 15-byte mediaId
|
||||
public static final String KEY_MEDIA_ID = "M";
|
||||
// N: The length of the encrypted media object
|
||||
public static final String ATTR_LENGTH = "L";
|
||||
// N: Time in seconds since epoch of last backup media usage recalculation. This timestamp is updated whenever we
|
||||
// recalculate the up-to-date bytes used by querying the cdn(s) directly.
|
||||
public static final String ATTR_MEDIA_USAGE_LAST_RECALCULATION = "MBTS";
|
||||
|
||||
public BackupsDb(
|
||||
final DynamoDbAsyncClient dynamoClient,
|
||||
final String backupTableName,
|
||||
final String backupMediaTableName,
|
||||
final Clock clock) {
|
||||
this.dynamoClient = dynamoClient;
|
||||
this.backupTableName = backupTableName;
|
||||
this.backupMediaTableName = backupMediaTableName;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the public key associated with a backupId.
|
||||
*
|
||||
* @param authenticatedBackupId The backup-id bytes that should be associated with the provided public key
|
||||
* @param authenticatedBackupId The backup-id bytes that should be associated with the provided public key
|
||||
* @param authenticatedBackupTier The backup tier
|
||||
* @param publicKey The public key to associate with the backup id
|
||||
* @param publicKey The public key to associate with the backup id
|
||||
* @return A stage that completes when the public key has been set. If the backup-id already has a set public key that
|
||||
* does not match, the stage will be completed exceptionally with a {@link PublicKeyConflictException}
|
||||
*/
|
||||
@@ -136,103 +123,27 @@ public class BackupsDb {
|
||||
|
||||
|
||||
/**
|
||||
* Add media to the backup media table and update the quota in the backup table
|
||||
*
|
||||
* @param backupUser The
|
||||
* @param mediaId The mediaId to add
|
||||
* @param mediaLength The length of the media before encryption (the length of the source media)
|
||||
* @return A stage that completes successfully once the tables are updated. If the media with the provided id has
|
||||
* previously been tracked with a different length, the stage will complete exceptionally with an
|
||||
* {@link InvalidLengthException}
|
||||
*/
|
||||
CompletableFuture<Void> trackMedia(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final byte[] mediaId,
|
||||
final int mediaLength) {
|
||||
final byte[] hashedBackupId = hashedBackupId(backupUser);
|
||||
return dynamoClient
|
||||
.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(
|
||||
|
||||
// Add the media to the media table
|
||||
TransactWriteItem.builder().put(Put.builder()
|
||||
.tableName(backupMediaTableName)
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.item(Map.of(
|
||||
KEY_BACKUP_ID_HASH, AttributeValues.b(hashedBackupId),
|
||||
KEY_MEDIA_ID, AttributeValues.b(mediaId),
|
||||
ATTR_CDN, AttributeValues.n(BACKUP_CDN),
|
||||
ATTR_LENGTH, AttributeValues.n(mediaLength)))
|
||||
.conditionExpression("attribute_not_exists(#mediaId)")
|
||||
.expressionAttributeNames(Map.of("#mediaId", KEY_MEDIA_ID))
|
||||
.build()).build(),
|
||||
|
||||
// Update the media quota and TTL
|
||||
TransactWriteItem.builder().update(
|
||||
UpdateBuilder.forUser(backupTableName, backupUser)
|
||||
.setRefreshTimes(clock)
|
||||
.incrementMediaBytes(mediaLength)
|
||||
.incrementMediaCount(1)
|
||||
.transactItemBuilder()
|
||||
.build()).build()).build())
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException txCancelled) {
|
||||
final long oldItemLength = conditionCheckFailed(txCancelled, 0)
|
||||
.flatMap(item -> Optional.ofNullable(item.get(ATTR_LENGTH)))
|
||||
.map(attr -> Long.parseLong(attr.n()))
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(throwable));
|
||||
if (oldItemLength != mediaLength) {
|
||||
throw new CompletionException(
|
||||
new InvalidLengthException("Previously tried to copy media with a different length. "
|
||||
+ "Provided " + mediaLength + " was " + oldItemLength));
|
||||
}
|
||||
// The client already "paid" for this media, can let them through
|
||||
return null;
|
||||
} else {
|
||||
// rethrow original exception
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
}
|
||||
})
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove media from backup media table and update the quota in the backup table
|
||||
* Update the quota in the backup table
|
||||
*
|
||||
* @param backupUser The backup user
|
||||
* @param mediaId The mediaId to add
|
||||
* @param mediaLength The length of the media before encryption (the length of the source media)
|
||||
* @return A stage that completes successfully once the tables are updated
|
||||
* @param mediaLength The length of the media after encryption. A negative length implies the media is being removed
|
||||
* @return A stage that completes successfully once the table are updated.
|
||||
*/
|
||||
CompletableFuture<Void> untrackMedia(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final byte[] mediaId,
|
||||
final int mediaLength) {
|
||||
final byte[] hashedBackupId = hashedBackupId(backupUser);
|
||||
return dynamoClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(
|
||||
TransactWriteItem.builder().delete(Delete.builder()
|
||||
.tableName(backupMediaTableName)
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.key(Map.of(
|
||||
KEY_BACKUP_ID_HASH, AttributeValues.b(hashedBackupId),
|
||||
KEY_MEDIA_ID, AttributeValues.b(mediaId)
|
||||
))
|
||||
.conditionExpression("#length = :length")
|
||||
.expressionAttributeNames(Map.of("#length", ATTR_LENGTH))
|
||||
.expressionAttributeValues(Map.of(":length", AttributeValues.n(mediaLength)))
|
||||
.build()).build(),
|
||||
|
||||
// Don't update TTLs, since we're just cleaning up media
|
||||
TransactWriteItem.builder().update(UpdateBuilder.forUser(backupTableName, backupUser)
|
||||
.incrementMediaBytes(-mediaLength)
|
||||
.incrementMediaCount(-1)
|
||||
.transactItemBuilder().build()).build()).build())
|
||||
.exceptionally(error -> {
|
||||
logger.warn("failed cleanup after failed copy operation", error);
|
||||
return null;
|
||||
})
|
||||
CompletableFuture<Void> trackMedia(final AuthenticatedBackupUser backupUser, final int mediaLength) {
|
||||
final Instant now = clock.instant();
|
||||
return dynamoClient
|
||||
.updateItem(
|
||||
// Update the media quota and TTL
|
||||
UpdateBuilder.forUser(backupTableName, backupUser)
|
||||
.setRefreshTimes(now)
|
||||
.incrementMediaBytes(mediaLength)
|
||||
.incrementMediaCount(Integer.signum(mediaLength))
|
||||
.updateItemBuilder()
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update the last update timestamps for the backupId in the presentation
|
||||
*
|
||||
@@ -249,6 +160,7 @@ public class BackupsDb {
|
||||
|
||||
/**
|
||||
* Track that a backup will be stored for the user
|
||||
*
|
||||
* @param backupUser an already authorized backup user
|
||||
*/
|
||||
CompletableFuture<Void> addMessageBackup(final AuthenticatedBackupUser backupUser) {
|
||||
@@ -276,8 +188,8 @@ public class BackupsDb {
|
||||
return dynamoClient.getItem(GetItemRequest.builder()
|
||||
.tableName(backupTableName)
|
||||
.key(Map.of(KEY_BACKUP_ID_HASH, AttributeValues.b(hashedBackupId(backupUser))))
|
||||
.projectionExpression("#cdn,#bytesUsed")
|
||||
.expressionAttributeNames(Map.of("#cdn", ATTR_CDN, "#bytesUsed", ATTR_MEDIA_BYTES_USED))
|
||||
.projectionExpression("#cdn,#mediaBytesUsed")
|
||||
.expressionAttributeNames(Map.of("#cdn", ATTR_CDN, "#mediaBytesUsed", ATTR_MEDIA_BYTES_USED))
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.thenApply(response -> {
|
||||
@@ -297,6 +209,46 @@ public class BackupsDb {
|
||||
});
|
||||
}
|
||||
|
||||
public record TimestampedUsageInfo(UsageInfo usageInfo, Instant lastRecalculationTime) {}
|
||||
|
||||
CompletableFuture<TimestampedUsageInfo> getMediaUsage(final AuthenticatedBackupUser backupUser) {
|
||||
return dynamoClient.getItem(GetItemRequest.builder()
|
||||
.tableName(backupTableName)
|
||||
.key(Map.of(KEY_BACKUP_ID_HASH, AttributeValues.b(hashedBackupId(backupUser))))
|
||||
.projectionExpression("#mediaBytesUsed,#mediaCount,#usageRecalc")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#mediaBytesUsed", ATTR_MEDIA_BYTES_USED,
|
||||
"#mediaCount", ATTR_MEDIA_COUNT,
|
||||
"#usageRecalc", ATTR_MEDIA_USAGE_LAST_RECALCULATION))
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.thenApply(response -> {
|
||||
final long mediaUsed = AttributeValues.getLong(response.item(), ATTR_MEDIA_BYTES_USED, 0L);
|
||||
final long mediaCount = AttributeValues.getLong(response.item(), ATTR_MEDIA_COUNT, 0L);
|
||||
final long recalcSeconds = AttributeValues.getLong(response.item(), ATTR_MEDIA_USAGE_LAST_RECALCULATION, 0L);
|
||||
return new TimestampedUsageInfo(new UsageInfo(mediaUsed, mediaCount), Instant.ofEpochSecond(recalcSeconds));
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
CompletableFuture<Void> setMediaUsage(final AuthenticatedBackupUser backupUser, UsageInfo usageInfo) {
|
||||
return dynamoClient.updateItem(
|
||||
UpdateBuilder.forUser(backupTableName, backupUser)
|
||||
.addSetExpression("#mediaBytesUsed = :mediaBytesUsed",
|
||||
Map.entry("#mediaBytesUsed", ATTR_MEDIA_BYTES_USED),
|
||||
Map.entry(":mediaBytesUsed", AttributeValues.n(usageInfo.bytesUsed())))
|
||||
.addSetExpression("#mediaCount = :mediaCount",
|
||||
Map.entry("#mediaCount", ATTR_MEDIA_COUNT),
|
||||
Map.entry(":mediaCount", AttributeValues.n(usageInfo.numObjects())))
|
||||
.addSetExpression("#mediaRecalc = :mediaRecalc",
|
||||
Map.entry("#mediaRecalc", ATTR_MEDIA_USAGE_LAST_RECALCULATION),
|
||||
Map.entry(":mediaRecalc", AttributeValues.n(clock.instant().getEpochSecond())))
|
||||
.updateItemBuilder()
|
||||
.build())
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Build ddb update statements for the backups table
|
||||
@@ -396,19 +348,22 @@ public class BackupsDb {
|
||||
* Set the lastRefresh time as part of the update
|
||||
* <p>
|
||||
* This always updates lastRefreshTime, and updates lastMediaRefreshTime if the backup user has the appropriate
|
||||
* tier
|
||||
* tier.
|
||||
*/
|
||||
UpdateBuilder setRefreshTimes(final Clock clock) {
|
||||
final long refreshTimeSecs = clock.instant().getEpochSecond();
|
||||
return this.setRefreshTimes(clock.instant());
|
||||
}
|
||||
|
||||
UpdateBuilder setRefreshTimes(final Instant refreshTime) {
|
||||
addSetExpression("#lastRefreshTime = :lastRefreshTime",
|
||||
Map.entry("#lastRefreshTime", ATTR_LAST_REFRESH),
|
||||
Map.entry(":lastRefreshTime", AttributeValues.n(refreshTimeSecs)));
|
||||
Map.entry(":lastRefreshTime", AttributeValues.n(refreshTime.getEpochSecond())));
|
||||
|
||||
if (backupTier.compareTo(BackupTier.MEDIA) >= 0) {
|
||||
// update the media time if we have the appropriate tier
|
||||
addSetExpression("#lastMediaRefreshTime = :lastMediaRefreshTime",
|
||||
Map.entry("#lastMediaRefreshTime", ATTR_LAST_MEDIA_REFRESH),
|
||||
Map.entry(":lastMediaRefreshTime", AttributeValues.n(refreshTimeSecs)));
|
||||
Map.entry(":lastMediaRefreshTime", AttributeValues.n(refreshTime.getEpochSecond())));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
@@ -462,28 +417,4 @@ public class BackupsDb {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a DynamoDb error indicates a condition check failed error, and return the value of the item failed to
|
||||
* update.
|
||||
*
|
||||
* @param e The error returned by {@link DynamoDbAsyncClient#transactWriteItems} attempt
|
||||
* @param itemIndex The index of the item in the transaction that had a condition expression
|
||||
* @return The remote value of the item that failed to update, or empty if the error was not a condition check failure
|
||||
*/
|
||||
private static Optional<Map<String, AttributeValue>> conditionCheckFailed(TransactionCanceledException e,
|
||||
int itemIndex) {
|
||||
if (!e.hasCancellationReasons()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (e.cancellationReasons().size() < itemIndex + 1) {
|
||||
return Optional.empty();
|
||||
}
|
||||
final CancellationReason reason = e.cancellationReasons().get(itemIndex);
|
||||
if (!"ConditionalCheckFailed".equals(reason.code()) || !reason.hasItem()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(reason.item());
|
||||
}
|
||||
|
||||
}
|
||||
+171
-9
@@ -1,41 +1,94 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.core.Response;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
public class Cdn3RemoteStorageManager implements RemoteStorageManager {
|
||||
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
private static final Logger logger = LoggerFactory.getLogger(Cdn3RemoteStorageManager.class);
|
||||
|
||||
private final FaultTolerantHttpClient cdnHttpClient;
|
||||
private final FaultTolerantHttpClient storageManagerHttpClient;
|
||||
private final String storageManagerBaseUrl;
|
||||
private final String clientId;
|
||||
private final String clientSecret;
|
||||
static final String CLIENT_ID_HEADER = "CF-Access-Client-Id";
|
||||
static final String CLIENT_SECRET_HEADER = "CF-Access-Client-Secret";
|
||||
|
||||
private static final String STORAGE_MANAGER_STATUS_COUNTER_NAME = MetricsUtil.name(Cdn3RemoteStorageManager.class,
|
||||
"storageManagerStatus");
|
||||
|
||||
private static final String STORAGE_MANAGER_TIMER_NAME = MetricsUtil.name(Cdn3RemoteStorageManager.class,
|
||||
"storageManager");
|
||||
private static final String OPERATION_TAG_NAME = "op";
|
||||
private static final String STATUS_TAG_NAME = "status";
|
||||
|
||||
public Cdn3RemoteStorageManager(
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration,
|
||||
final RetryConfiguration retryConfiguration,
|
||||
final List<String> caCertificates) throws CertificateException {
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withName("cdn3-remote-storage")
|
||||
final List<String> cdnCaCertificates,
|
||||
final Cdn3StorageManagerConfiguration configuration) throws CertificateException {
|
||||
|
||||
// strip trailing "/" for easier URI construction
|
||||
this.storageManagerBaseUrl = StringUtils.removeEnd(configuration.baseUri(), "/");
|
||||
this.clientId = configuration.clientId();
|
||||
this.clientSecret = configuration.clientSecret().value();
|
||||
|
||||
// Client used to read/write to cdn
|
||||
this.cdnHttpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withName("cdn-client")
|
||||
.withCircuitBreaker(circuitBreakerConfiguration)
|
||||
.withExecutor(Executors.newCachedThreadPool())
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withRetry(retryConfiguration)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.withTrustedServerCertificates(cdnCaCertificates.toArray(new String[0]))
|
||||
.build();
|
||||
|
||||
// Client used for calls to storage-manager
|
||||
// storage-manager has an external CA so uses a different client
|
||||
this.storageManagerHttpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withName("cdn3-storage-manager")
|
||||
.withCircuitBreaker(circuitBreakerConfiguration)
|
||||
.withExecutor(Executors.newCachedThreadPool())
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withRetry(retryConfiguration)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.withTrustedServerCertificates(caCertificates.toArray(new String[0]))
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -55,10 +108,10 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
|
||||
throw new IllegalArgumentException("Cdn3RemoteStorageManager can only copy to cdn3");
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final BackupMediaEncrypter encrypter = new BackupMediaEncrypter(encryptionParameters);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder().GET().uri(sourceUri).build();
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofPublisher()).thenCompose(response -> {
|
||||
return cdnHttpClient.sendAsync(request, HttpResponse.BodyHandlers.ofPublisher()).thenCompose(response -> {
|
||||
if (response.statusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
|
||||
throw new CompletionException(new SourceObjectNotFoundException());
|
||||
} else if (response.statusCode() != Response.Status.OK.getStatusCode()) {
|
||||
@@ -90,13 +143,122 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
|
||||
.POST(encryptedBody)
|
||||
.build();
|
||||
|
||||
return httpClient.sendAsync(put, HttpResponse.BodyHandlers.discarding());
|
||||
return cdnHttpClient.sendAsync(put, HttpResponse.BodyHandlers.discarding());
|
||||
})
|
||||
.thenAccept(response -> {
|
||||
if (response.statusCode() != Response.Status.CREATED.getStatusCode() &&
|
||||
response.statusCode() != Response.Status.OK.getStatusCode()) {
|
||||
throw new CompletionException(new IOException("Failed to copy object: " + response.statusCode()));
|
||||
}
|
||||
});
|
||||
})
|
||||
.whenComplete((ignored, ignoredException) ->
|
||||
sample.stop(Metrics.timer(STORAGE_MANAGER_TIMER_NAME, OPERATION_TAG_NAME, "copy")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<ListResult> list(
|
||||
final String prefix,
|
||||
final Optional<String> cursor,
|
||||
final long limit) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final Map<String, String> queryParams = new HashMap<>();
|
||||
queryParams.put("prefix", prefix);
|
||||
queryParams.put("limit", Long.toString(limit));
|
||||
cursor.ifPresent(s -> queryParams.put("cursor", cursor.get()));
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder().GET()
|
||||
.uri(URI.create("%s/%s/%s".formatted(
|
||||
storageManagerBaseUrl,
|
||||
Cdn3BackupCredentialGenerator.CDN_PATH,
|
||||
HttpUtils.queryParamString(queryParams.entrySet()))))
|
||||
.header(CLIENT_ID_HEADER, clientId)
|
||||
.header(CLIENT_SECRET_HEADER, clientSecret)
|
||||
.build();
|
||||
|
||||
return this.storageManagerHttpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
|
||||
.thenApply(response -> {
|
||||
Metrics.counter(STORAGE_MANAGER_STATUS_COUNTER_NAME,
|
||||
OPERATION_TAG_NAME, "list",
|
||||
STATUS_TAG_NAME, Integer.toString(response.statusCode()))
|
||||
.increment();
|
||||
try {
|
||||
return parseListResponse(response, prefix);
|
||||
} catch (IOException e) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
})
|
||||
.whenComplete((ignored, ignoredException) ->
|
||||
sample.stop(Metrics.timer(STORAGE_MANAGER_TIMER_NAME, OPERATION_TAG_NAME, "list")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialized list response from storage manager
|
||||
*/
|
||||
record Cdn3ListResponse(@NotNull List<Entry> objects, @Nullable String cursor) {
|
||||
|
||||
record Entry(@NotNull String key, @NotNull long size) {}
|
||||
}
|
||||
|
||||
private static ListResult parseListResponse(final HttpResponse<InputStream> httpListResponse, final String prefix)
|
||||
throws IOException {
|
||||
if (!HttpUtils.isSuccessfulResponse(httpListResponse.statusCode())) {
|
||||
throw new IOException("Failed to list objects: " + httpListResponse.statusCode());
|
||||
}
|
||||
final Cdn3ListResponse result = SystemMapper.jsonMapper()
|
||||
.readValue(httpListResponse.body(), Cdn3ListResponse.class);
|
||||
|
||||
final List<ListResult.Entry> objects = new ArrayList<>(result.objects.size());
|
||||
for (Cdn3ListResponse.Entry entry : result.objects) {
|
||||
if (!entry.key().startsWith(prefix)) {
|
||||
logger.error("unexpected listing result from cdn3 - entry {} does not contain requested prefix {}",
|
||||
entry.key(), prefix);
|
||||
throw new IOException("prefix listing returned unexpected result");
|
||||
}
|
||||
objects.add(new ListResult.Entry(entry.key().substring(prefix.length()), entry.size()));
|
||||
}
|
||||
return new ListResult(objects, Optional.ofNullable(result.cursor));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Serialized usage response from storage manager
|
||||
*/
|
||||
record UsageResponse(@NotNull long numObjects, @NotNull long bytesUsed) {}
|
||||
|
||||
@Override
|
||||
public CompletionStage<UsageInfo> calculateBytesUsed(final String prefix) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final HttpRequest request = HttpRequest.newBuilder().GET()
|
||||
.uri(URI.create("%s/usage%s".formatted(
|
||||
storageManagerBaseUrl,
|
||||
HttpUtils.queryParamString(Map.of("prefix", prefix).entrySet()))))
|
||||
.header(CLIENT_ID_HEADER, clientId)
|
||||
.header(CLIENT_SECRET_HEADER, clientSecret)
|
||||
.build();
|
||||
return this.storageManagerHttpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
|
||||
.thenApply(response -> {
|
||||
Metrics.counter(STORAGE_MANAGER_STATUS_COUNTER_NAME,
|
||||
OPERATION_TAG_NAME, "usage",
|
||||
STATUS_TAG_NAME, Integer.toString(response.statusCode()))
|
||||
.increment();
|
||||
try {
|
||||
return parseUsageResponse(response);
|
||||
} catch (IOException e) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
})
|
||||
.whenComplete((ignored, ignoredException) ->
|
||||
sample.stop(Metrics.timer(STORAGE_MANAGER_TIMER_NAME, OPERATION_TAG_NAME, "usage")));
|
||||
}
|
||||
|
||||
private static UsageInfo parseUsageResponse(final HttpResponse<InputStream> httpUsageResponse) throws IOException {
|
||||
if (!HttpUtils.isSuccessfulResponse(httpUsageResponse.statusCode())) {
|
||||
throw new IOException("Failed to retrieve usage: " + httpUsageResponse.statusCode());
|
||||
}
|
||||
final UsageResponse response = SystemMapper.jsonMapper().readValue(httpUsageResponse.body(), UsageResponse.class);
|
||||
return new UsageInfo(response.bytesUsed(), response.numObjects);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+7
@@ -14,4 +14,11 @@ public record MediaEncryptionParameters(
|
||||
new SecretKeySpec(macKey, "HmacSHA256"),
|
||||
new IvParameterSpec(iv));
|
||||
}
|
||||
|
||||
public int outputSize(final int inputSize) {
|
||||
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
|
||||
final int numBlocks = (inputSize + 16) / 16;
|
||||
// IV + AES-256 encrypted data + HmacSHA256
|
||||
return this.iv().getIV().length + (numBlocks * 16) + 32;
|
||||
}
|
||||
}
|
||||
+39
@@ -1,6 +1,8 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/**
|
||||
@@ -35,4 +37,41 @@ public interface RemoteStorageManager {
|
||||
int expectedSourceLength,
|
||||
MediaEncryptionParameters encryptionParameters,
|
||||
MessageBackupUploadDescriptor uploadDescriptor);
|
||||
|
||||
/**
|
||||
* Result of a {@link #list} operation
|
||||
*
|
||||
* @param objects An {@link Entry} for each object returned by the list request
|
||||
* @param cursor An opaque string that can be used to resume listing from where a previous request left off, empty if
|
||||
* the request reached the end of the list of matching objects.
|
||||
*/
|
||||
record ListResult(List<Entry> objects, Optional<String> cursor) {
|
||||
|
||||
/**
|
||||
* An entry representing a remote stored object under a prefix
|
||||
*
|
||||
* @param key The name of the object with the prefix removed
|
||||
* @param length The length of the object in bytes
|
||||
*/
|
||||
record Entry(String key, long length) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* List objects on the remote cdn.
|
||||
*
|
||||
* @param prefix The prefix of the objects to list
|
||||
* @param cursor The cursor returned by a previous call to list, or empty if starting from the first object with the
|
||||
* provided prefix
|
||||
* @param limit The maximum number of items to return in the list
|
||||
* @return A {@link ListResult} of objects that match the prefix.
|
||||
*/
|
||||
CompletionStage<ListResult> list(final String prefix, final Optional<String> cursor, final long limit);
|
||||
|
||||
/**
|
||||
* Calculate the total number of bytes stored by objects with the provided prefix
|
||||
*
|
||||
* @param prefix The prefix of the objects to sum
|
||||
* @return The number of bytes used
|
||||
*/
|
||||
CompletionStage<UsageInfo> calculateBytesUsed(final String prefix);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public record UsageInfo(long bytesUsed, long numObjects) {}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public record Cdn3StorageManagerConfiguration(
|
||||
@NotNull String baseUri,
|
||||
@NotNull String clientId,
|
||||
@NotNull SecretString clientSecret) {}
|
||||
-8
@@ -49,7 +49,6 @@ public class DynamoDbTables {
|
||||
private final AccountsTableConfiguration accounts;
|
||||
|
||||
private final Table backups;
|
||||
private final Table backupMedia;
|
||||
private final Table clientReleases;
|
||||
private final Table deletedAccounts;
|
||||
private final Table deletedAccountsLock;
|
||||
@@ -96,7 +95,6 @@ public class DynamoDbTables {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.backups = backups;
|
||||
this.backupMedia = backupMedia;
|
||||
this.clientReleases = clientReleases;
|
||||
this.deletedAccounts = deletedAccounts;
|
||||
this.deletedAccountsLock = deletedAccountsLock;
|
||||
@@ -130,12 +128,6 @@ public class DynamoDbTables {
|
||||
return backups;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getBackupMedia() {
|
||||
return backupMedia;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getClientReleases() {
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
public record MonitoredS3ObjectConfiguration(
|
||||
@NotBlank String s3Region,
|
||||
@NotBlank String s3Bucket,
|
||||
@NotBlank String objectKey,
|
||||
Long maxSize,
|
||||
Duration refreshInterval) {
|
||||
|
||||
private static long DEFAULT_MAXSIZE = 16*1024*1024;
|
||||
private static Duration DEFAULT_REFRESH_INTERVAL = Duration.ofMinutes(5);
|
||||
|
||||
public MonitoredS3ObjectConfiguration {
|
||||
if (maxSize == null) {
|
||||
maxSize = DEFAULT_MAXSIZE;
|
||||
}
|
||||
if (refreshInterval == null) {
|
||||
refreshInterval = DEFAULT_REFRESH_INTERVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
-8
@@ -51,10 +51,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicRateLimitPolicy rateLimitPolicy = new DynamicRateLimitPolicy(false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicECPreKeyMigrationConfiguration ecPreKeyMigration = new DynamicECPreKeyMigrationConfiguration(true, false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicInboundMessageByteLimitConfiguration inboundMessageByteLimit = new DynamicInboundMessageByteLimitConfiguration(true);
|
||||
@@ -102,10 +98,6 @@ public class DynamicConfiguration {
|
||||
return rateLimitPolicy;
|
||||
}
|
||||
|
||||
public DynamicECPreKeyMigrationConfiguration getEcPreKeyMigrationConfiguration() {
|
||||
return ecPreKeyMigration;
|
||||
}
|
||||
|
||||
public DynamicInboundMessageByteLimitConfiguration getInboundMessageByteLimitConfiguration() {
|
||||
return inboundMessageByteLimit;
|
||||
}
|
||||
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicECPreKeyMigrationConfiguration(boolean deleteEcSignedPreKeys, boolean storeEcSignedPreKeys) {
|
||||
}
|
||||
+75
-3
@@ -27,6 +27,8 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
@@ -231,7 +233,10 @@ public class ArchiveController {
|
||||
@Schema(description = "If present, the CDN type where the message backup is stored")
|
||||
int cdn,
|
||||
|
||||
@Schema(description = "If present, the directory of your backup data on the cdn.")
|
||||
@Schema(description = """
|
||||
If present, the directory of your backup data on the cdn. The message backup can be found at /backupDir/backupName
|
||||
and stored media can be found at /backupDir/media/mediaId.
|
||||
""")
|
||||
String backupDir,
|
||||
|
||||
@Schema(description = "If present, the name of the most recent message backup on the cdn. The backup is at /backupDir/backupName")
|
||||
@@ -409,9 +414,10 @@ public class ArchiveController {
|
||||
description = """
|
||||
Copy and re-encrypt media from the attachments cdn into the backup cdn.
|
||||
|
||||
The original, already encrypted, attachment will be encrypted with the provided key material before being copied
|
||||
The original, already encrypted, attachment will be encrypted with the provided key material before being copied.
|
||||
|
||||
If the destination media already exists, the copy will be skipped and a 200 will be returned.
|
||||
A particular destination media id should not be reused with a different source media id or different encryption
|
||||
parameters.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = CopyMediaResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "The provided object length was incorrect")
|
||||
@@ -610,4 +616,70 @@ public class ArchiveController {
|
||||
.thenCompose(backupManager::ttlRefresh)
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
record StoredMediaObject(
|
||||
|
||||
@Schema(description = "The backup cdn where this media object is stored")
|
||||
@NotNull
|
||||
Integer cdn,
|
||||
|
||||
@Schema(description = "The mediaId of the object in URL-safe base64", implementation = String.class)
|
||||
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
|
||||
@NotNull
|
||||
@ExactlySize(15)
|
||||
byte[] mediaId,
|
||||
|
||||
@Schema(description = "The length of the object in bytes")
|
||||
@NotNull
|
||||
Long objectLength) {}
|
||||
|
||||
public record ListResponse(
|
||||
@Schema(description = "A page of media objects stored for this backup ID")
|
||||
List<StoredMediaObject> storedMediaObjects,
|
||||
|
||||
@Schema(description = "If set, the cursor value to pass to the next list request to continue listing. If absent, all objects have been listed")
|
||||
String cursor) {}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/media")
|
||||
@Operation(summary = "List media objects",
|
||||
description = """
|
||||
Retrieve a list of media objects stored for this backup-id. A client may have previously stored media objects
|
||||
that are no longer referenced in their current backup. To reclaim storage space used by these orphaned
|
||||
objects, perform a list operation and remove any unreferenced media objects via DELETE /v1/backups/<mediaId>.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = ListResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid cursor or limit")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<ListResponse> listMedia(
|
||||
@Auth final Optional<AuthenticatedAccount> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH) final BackupAuthCredentialPresentationHeader presentation,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Parameter(description = "A cursor returned by a previous call")
|
||||
@QueryParam("cursor") final Optional<String> cursor,
|
||||
|
||||
@Parameter(description = "The number of entries to return per call")
|
||||
@QueryParam("limit") final Optional<@Min(1) @Max(10_000) Integer> limit) {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature)
|
||||
.thenCompose(backupUser -> backupManager.list(backupUser, cursor, limit.orElse(1000)))
|
||||
.thenApply(result -> new ListResponse(
|
||||
result.media()
|
||||
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
|
||||
.toList(),
|
||||
result.cursor().orElse(null)));
|
||||
}
|
||||
}
|
||||
+10
-41
@@ -38,8 +38,6 @@ import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
|
||||
@@ -51,7 +49,6 @@ import org.whispersystems.textsecuregcm.entities.PreKeyResponseItem;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
|
||||
import org.whispersystems.textsecuregcm.entities.SetKeysRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.experiment.Experiment;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -74,14 +71,11 @@ public class KeysController {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final KeysManager keys;
|
||||
private final AccountsManager accounts;
|
||||
private final Experiment compareSignedEcPreKeysExperiment = new Experiment("compareSignedEcPreKeys");
|
||||
|
||||
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
|
||||
|
||||
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture[0];
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(KeysController.class);
|
||||
|
||||
public KeysController(RateLimiters rateLimiters, KeysManager keys, AccountsManager accounts) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.keys = keys;
|
||||
@@ -143,9 +137,7 @@ public class KeysController {
|
||||
case PNI -> d.setPhoneNumberIdentitySignedPreKey(setKeysRequest.signedPreKey());
|
||||
}
|
||||
},
|
||||
d -> keys.buildWriteItemForEcSignedPreKey(identifier, d.getId(), setKeysRequest.signedPreKey())
|
||||
.map(List::of)
|
||||
.orElseGet(Collections::emptyList))
|
||||
d -> List.of(keys.buildWriteItemForEcSignedPreKey(identifier, d.getId(), setKeysRequest.signedPreKey())))
|
||||
.toCompletableFuture();
|
||||
} else {
|
||||
updateAccountFuture = CompletableFuture.completedFuture(account);
|
||||
@@ -249,35 +241,13 @@ public class KeysController {
|
||||
.increment();
|
||||
|
||||
final List<PreKeyResponseItem> responseItems = Flux.fromIterable(parseDeviceId(deviceId, target))
|
||||
.flatMap(device -> {
|
||||
final ECSignedPreKey ecSignedPreKey = device.getSignedPreKey(targetIdentifier.identityType());
|
||||
final CompletableFuture<Optional<ECSignedPreKey>> signedPreKeyFuture =
|
||||
keys.getEcSignedPreKey(targetIdentifier.uuid(), device.getId());
|
||||
|
||||
compareSignedEcPreKeysExperiment.compareFutureResult(Optional.ofNullable(ecSignedPreKey), signedPreKeyFuture);
|
||||
|
||||
signedPreKeyFuture.whenComplete((maybeSignedPreKey, throwable) -> {
|
||||
if (throwable == null) {
|
||||
if (!Optional.ofNullable(ecSignedPreKey).equals(maybeSignedPreKey)) {
|
||||
logger.warn("Signed pre-keys do not match for {}, device {}. From device: {}; from table: {}",
|
||||
targetIdentifier,
|
||||
deviceId,
|
||||
Optional.ofNullable(ecSignedPreKey).map(ECSignedPreKey::keyId),
|
||||
maybeSignedPreKey.map(ECSignedPreKey::keyId));
|
||||
}
|
||||
} else {
|
||||
logger.error("Failed to get signed pre-key for {}, device {}", targetIdentifier, deviceId, throwable);
|
||||
}
|
||||
});
|
||||
|
||||
return Mono.zip(
|
||||
Mono.just(device),
|
||||
Mono.just(Optional.ofNullable(ecSignedPreKey)),
|
||||
Mono.fromFuture(() -> keys.takeEC(targetIdentifier.uuid(), device.getId())),
|
||||
Mono.fromFuture(() -> returnPqKey ? keys.takePQ(targetIdentifier.uuid(), device.getId())
|
||||
: CompletableFuture.<Optional<KEMSignedPreKey>>completedFuture(Optional.empty()))
|
||||
);
|
||||
}).filter(keys -> keys.getT2().isPresent() || keys.getT3().isPresent() || keys.getT4().isPresent())
|
||||
.flatMap(device -> Mono.zip(
|
||||
Mono.just(device),
|
||||
Mono.fromFuture(() -> keys.getEcSignedPreKey(targetIdentifier.uuid(), device.getId())),
|
||||
Mono.fromFuture(() -> keys.takeEC(targetIdentifier.uuid(), device.getId())),
|
||||
Mono.fromFuture(() -> returnPqKey ? keys.takePQ(targetIdentifier.uuid(), device.getId())
|
||||
: CompletableFuture.<Optional<KEMSignedPreKey>>completedFuture(Optional.empty()))
|
||||
)).filter(keys -> keys.getT2().isPresent() || keys.getT3().isPresent() || keys.getT4().isPresent())
|
||||
.map(deviceAndKeys -> {
|
||||
final Device device = deviceAndKeys.getT1();
|
||||
final int registrationId = switch (targetIdentifier.identityType()) {
|
||||
@@ -298,6 +268,7 @@ public class KeysController {
|
||||
if (responseItems.isEmpty()) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
|
||||
return new PreKeyResponse(identityKey, responseItems);
|
||||
}
|
||||
|
||||
@@ -326,9 +297,7 @@ public class KeysController {
|
||||
case PNI -> d.setPhoneNumberIdentitySignedPreKey(signedPreKey);
|
||||
}
|
||||
},
|
||||
d -> keys.buildWriteItemForEcSignedPreKey(identifier, d.getId(), signedPreKey)
|
||||
.map(List::of)
|
||||
.orElseGet(Collections::emptyList))
|
||||
d -> List.of(keys.buildWriteItemForEcSignedPreKey(identifier, d.getId(), signedPreKey)))
|
||||
.toCompletableFuture()
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
@@ -41,41 +41,37 @@ class KeysGrpcHelper {
|
||||
return devices
|
||||
.filter(Device::isEnabled)
|
||||
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
|
||||
.flatMap(device -> {
|
||||
final ECSignedPreKey ecSignedPreKey = device.getSignedPreKey(identityType);
|
||||
.flatMap(device -> Flux.merge(
|
||||
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
|
||||
Mono.fromFuture(() -> keysManager.getEcSignedPreKey(targetAccount.getIdentifier(identityType), device.getId())),
|
||||
Mono.fromFuture(() -> keysManager.takePQ(targetAccount.getIdentifier(identityType), device.getId())))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.reduce(GetPreKeysResponse.PreKeyBundle.newBuilder(), (builder, preKey) -> {
|
||||
if (preKey instanceof ECPreKey ecPreKey) {
|
||||
builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
|
||||
.build());
|
||||
} else if (preKey instanceof ECSignedPreKey ecSignedPreKey) {
|
||||
builder.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(ecSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build());
|
||||
} else if (preKey instanceof KEMSignedPreKey kemSignedPreKey) {
|
||||
builder.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(kemSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build());
|
||||
} else {
|
||||
throw new AssertionError("Unexpected pre-key type: " + preKey.getClass());
|
||||
}
|
||||
|
||||
final GetPreKeysResponse.PreKeyBundle.Builder preKeyBundleBuilder = GetPreKeysResponse.PreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(ecSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build());
|
||||
|
||||
return Flux.merge(
|
||||
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
|
||||
Mono.fromFuture(() -> keysManager.takePQ(targetAccount.getIdentifier(identityType), device.getId())))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.reduce(preKeyBundleBuilder, (builder, preKey) -> {
|
||||
if (preKey instanceof ECPreKey ecPreKey) {
|
||||
builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(ecPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(ecPreKey.serializedPublicKey()))
|
||||
.build());
|
||||
} else if (preKey instanceof KEMSignedPreKey kemSignedPreKey) {
|
||||
preKeyBundleBuilder.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(kemSignedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build());
|
||||
} else {
|
||||
throw new AssertionError("Unexpected pre-key type: " + preKey.getClass());
|
||||
}
|
||||
|
||||
return builder;
|
||||
})
|
||||
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
|
||||
.map(builder -> Tuples.of((int) device.getId(), builder.build()));
|
||||
return builder;
|
||||
})
|
||||
// Cast device IDs to `int` to match data types in the response object’s protobuf definition
|
||||
.map(builder -> Tuples.of((int) device.getId(), builder.build())))
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.map(preKeyBundles -> GetPreKeysResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(identityType).serialize()))
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface ManagedSupplier<T> extends Supplier<T>, Managed {
|
||||
|
||||
@Override
|
||||
default void start() throws Exception {
|
||||
// noop
|
||||
}
|
||||
|
||||
@Override
|
||||
default void stop() throws Exception {
|
||||
// noop
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.InputStream;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.MonitoredS3ObjectConfiguration;
|
||||
|
||||
public class S3MonitoringSupplier<T> implements ManagedSupplier<T> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
|
||||
|
||||
@Nonnull
|
||||
private final Timer refreshTimer;
|
||||
|
||||
@Nonnull
|
||||
private final Counter refreshErrors;
|
||||
|
||||
@Nonnull
|
||||
private final AtomicReference<T> holder;
|
||||
|
||||
@Nonnull
|
||||
private final S3ObjectMonitor monitor;
|
||||
|
||||
@Nonnull
|
||||
private final Function<InputStream, T> parser;
|
||||
|
||||
|
||||
public S3MonitoringSupplier(
|
||||
@Nonnull final ScheduledExecutorService executor,
|
||||
@Nonnull final MonitoredS3ObjectConfiguration cfg,
|
||||
@Nonnull final Function<InputStream, T> parser,
|
||||
@Nonnull final T initial,
|
||||
@Nonnull final String name) {
|
||||
this.refreshTimer = Metrics.timer(name(name, "refresh"));
|
||||
this.refreshErrors = Metrics.counter(name(name, "refreshErrors"));
|
||||
this.holder = new AtomicReference<>(initial);
|
||||
this.parser = requireNonNull(parser);
|
||||
this.monitor = new S3ObjectMonitor(
|
||||
cfg.s3Region(),
|
||||
cfg.s3Bucket(),
|
||||
cfg.objectKey(),
|
||||
cfg.maxSize(),
|
||||
executor,
|
||||
cfg.refreshInterval(),
|
||||
this::handleObjectChange
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nonnull
|
||||
public T get() {
|
||||
return requireNonNull(holder.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws Exception {
|
||||
monitor.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() throws Exception {
|
||||
monitor.stop();
|
||||
}
|
||||
|
||||
private void handleObjectChange(@Nonnull final InputStream inputStream) {
|
||||
refreshTimer.record(() -> {
|
||||
// parser function is supposed to close the input stream
|
||||
try {
|
||||
holder.set(parser.apply(inputStream));
|
||||
} catch (final Exception e) {
|
||||
log.error("failed to update internal state from the monitored object", e);
|
||||
refreshErrors.increment();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerService;
|
||||
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.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;
|
||||
|
||||
/**
|
||||
* An S3 object monitor watches a specific object in an S3 bucket and notifies a listener if that object changes.
|
||||
*/
|
||||
public class S3ObjectMonitor {
|
||||
|
||||
private final String s3Bucket;
|
||||
private final String objectKey;
|
||||
private final long maxObjectSize;
|
||||
|
||||
private final ScheduledExecutorService refreshExecutorService;
|
||||
private final Duration refreshInterval;
|
||||
private ScheduledFuture<?> refreshFuture;
|
||||
|
||||
private final Consumer<InputStream> changeListener;
|
||||
|
||||
private final AtomicReference<String> lastETag = new AtomicReference<>();
|
||||
|
||||
private final S3Client s3Client;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(S3ObjectMonitor.class);
|
||||
|
||||
public S3ObjectMonitor(
|
||||
final String s3Region,
|
||||
final String s3Bucket,
|
||||
final String objectKey,
|
||||
final long maxObjectSize,
|
||||
final ScheduledExecutorService refreshExecutorService,
|
||||
final Duration refreshInterval,
|
||||
final Consumer<InputStream> changeListener) {
|
||||
|
||||
this(S3Client.builder()
|
||||
.region(Region.of(s3Region))
|
||||
.credentialsProvider(WhisperServerService.AWSSDK_CREDENTIALS_PROVIDER)
|
||||
.build(),
|
||||
s3Bucket,
|
||||
objectKey,
|
||||
maxObjectSize,
|
||||
refreshExecutorService,
|
||||
refreshInterval,
|
||||
changeListener);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
S3ObjectMonitor(
|
||||
final S3Client s3Client,
|
||||
final String s3Bucket,
|
||||
final String objectKey,
|
||||
final long maxObjectSize,
|
||||
final ScheduledExecutorService refreshExecutorService,
|
||||
final Duration refreshInterval,
|
||||
final Consumer<InputStream> changeListener) {
|
||||
|
||||
this.s3Client = s3Client;
|
||||
this.s3Bucket = s3Bucket;
|
||||
this.objectKey = objectKey;
|
||||
this.maxObjectSize = maxObjectSize;
|
||||
|
||||
this.refreshExecutorService = refreshExecutorService;
|
||||
this.refreshInterval = refreshInterval;
|
||||
|
||||
this.changeListener = changeListener;
|
||||
}
|
||||
|
||||
public synchronized void start() {
|
||||
if (refreshFuture != null) {
|
||||
throw new RuntimeException("S3 object manager already started");
|
||||
}
|
||||
|
||||
// Run the first request immediately/blocking, then start subsequent calls.
|
||||
log.info("Initial request for s3://{}/{}", s3Bucket, objectKey);
|
||||
refresh();
|
||||
|
||||
refreshFuture = refreshExecutorService
|
||||
.scheduleAtFixedRate(this::refresh, refreshInterval.toMillis(), refreshInterval.toMillis(),
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
if (refreshFuture != null) {
|
||||
refreshFuture.cancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Immediately returns the monitored S3 object regardless of whether it has changed since it was last retrieved.
|
||||
*
|
||||
* @return the current version of the monitored S3 object. Caller should close() this upon completion.
|
||||
* @throws IOException if the retrieved S3 object is larger than the configured maximum size
|
||||
*/
|
||||
@VisibleForTesting
|
||||
ResponseInputStream<GetObjectResponse> getObject() throws IOException {
|
||||
final ResponseInputStream<GetObjectResponse> response = s3Client.getObject(GetObjectRequest.builder()
|
||||
.key(objectKey)
|
||||
.bucket(s3Bucket)
|
||||
.build());
|
||||
|
||||
lastETag.set(response.response().eTag());
|
||||
|
||||
if (response.response().contentLength() <= maxObjectSize) {
|
||||
return response;
|
||||
} else {
|
||||
log.warn("Object at s3://{}/{} has a size of {} bytes, which exceeds the maximum allowed size of {} bytes",
|
||||
s3Bucket, objectKey, response.response().contentLength(), maxObjectSize);
|
||||
response.abort();
|
||||
throw new IOException("S3 object too large");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls S3 for object metadata and notifies the listener provided at construction time if and only if the object has
|
||||
* changed since the last call to {@link #getObject()} or {@code refresh()}.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
void refresh() {
|
||||
try {
|
||||
final HeadObjectResponse objectMetadata = s3Client.headObject(HeadObjectRequest.builder()
|
||||
.bucket(s3Bucket)
|
||||
.key(objectKey)
|
||||
.build());
|
||||
|
||||
final String initialETag = lastETag.get();
|
||||
final String refreshedETag = objectMetadata.eTag();
|
||||
|
||||
if (!StringUtils.equals(initialETag, refreshedETag) && lastETag.compareAndSet(initialETag, refreshedETag)) {
|
||||
try (final ResponseInputStream<GetObjectResponse> response = getObject()) {
|
||||
log.info("Object at s3://{}/{} has changed; new eTag is {} and object size is {} bytes",
|
||||
s3Bucket, objectKey, response.response().eTag(), response.response().contentLength());
|
||||
changeListener.accept(response);
|
||||
}
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to refresh monitored object", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -439,6 +439,9 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
|
||||
/**
|
||||
* Reserve a username hash under the account UUID
|
||||
* @return a future that completes once the username hash has been reserved; may fail with an
|
||||
* {@link ContestedOptimisticLockException} if the account has been updated or
|
||||
* {@link UsernameHashNotAvailableException} if the username was taken by someone else
|
||||
*/
|
||||
public CompletableFuture<Void> reserveUsernameHash(
|
||||
final Account account,
|
||||
@@ -474,9 +477,12 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
ATTR_TTL, AttributeValues.fromLong(expirationTime),
|
||||
ATTR_CONFIRMED, AttributeValues.fromBool(false),
|
||||
ATTR_RECLAIMABLE, AttributeValues.fromBool(false)))
|
||||
.conditionExpression("attribute_not_exists(#username_hash) OR (#ttl < :now)")
|
||||
.expressionAttributeNames(Map.of("#username_hash", ATTR_USERNAME_HASH, "#ttl", ATTR_TTL))
|
||||
.expressionAttributeValues(Map.of(":now", AttributeValues.fromLong(clock.instant().getEpochSecond())))
|
||||
.conditionExpression("attribute_not_exists(#username_hash) OR #ttl < :now OR (#aci = :aci AND #confirmed = :confirmed)")
|
||||
.expressionAttributeNames(Map.of("#username_hash", ATTR_USERNAME_HASH, "#ttl", ATTR_TTL, "#aci", KEY_ACCOUNT_UUID, "#confirmed", ATTR_CONFIRMED))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
|
||||
":aci", AttributeValues.fromUUID(uuid),
|
||||
":confirmed", AttributeValues.fromBool(false)))
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.build())
|
||||
.build());
|
||||
@@ -501,7 +507,12 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
.build())
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException e) {
|
||||
if (e.cancellationReasons().stream().map(CancellationReason::code).anyMatch(CONDITIONAL_CHECK_FAILED::equals)) {
|
||||
// If the constraint table update failed the condition check, the username's taken and we should stop
|
||||
// trying. However if it was only in the accounts table that the condition check update failed, it's an
|
||||
// optimistic locking failure (the account was concurrently updated) and we should try again.
|
||||
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
|
||||
throw ExceptionUtils.wrap(new UsernameHashNotAvailableException());
|
||||
} else if (conditionalCheckFailed(e.cancellationReasons().get(1))) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
}
|
||||
@@ -526,7 +537,8 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
* @param account to update
|
||||
* @param usernameHash believed to be available
|
||||
* @return a future that completes once the username hash has been confirmed; may fail with an
|
||||
* {@link ContestedOptimisticLockException} if the account has been updated or the username has taken by someone else
|
||||
* {@link ContestedOptimisticLockException} if the account has been updated or
|
||||
* {@link UsernameHashNotAvailableException} if the username was taken by someone else
|
||||
*/
|
||||
public CompletableFuture<Void> confirmUsernameHash(final Account account, final byte[] usernameHash, @Nullable final byte[] encryptedUsername) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
@@ -556,10 +568,15 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
return (Void) null;
|
||||
})
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(
|
||||
throwable) instanceof TransactionCanceledException transactionCanceledException) {
|
||||
if (transactionCanceledException.cancellationReasons().stream().map(CancellationReason::code)
|
||||
.anyMatch(CONDITIONAL_CHECK_FAILED::equals)) {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException e) {
|
||||
// If the constraint table update failed the condition check, the username's taken and we should stop
|
||||
// trying. However if it was only in the accounts table that the condition check update failed, it's an
|
||||
// optimistic locking failure (the account was concurrently updated) and we should try again.
|
||||
// NOTE: the fixed indices here must be kept in sync with the creation of the TransactWriteItems in
|
||||
// buildConfirmUsernameHashRequest!
|
||||
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
|
||||
throw ExceptionUtils.wrap(new UsernameHashNotAvailableException());
|
||||
} else if (conditionalCheckFailed(e.cancellationReasons().get(1))) {
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
}
|
||||
@@ -600,6 +617,8 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
final byte[] usernameHash = updatedAccount.getUsernameHash()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account must have a username hash"));
|
||||
|
||||
// NOTE: the order in which writeItems are added to the list is significant, and must be kept in sync with the catch block in confirmUsernameHash!
|
||||
|
||||
// add the username hash to the constraint table, wiping out the ttl if we had already reserved the hash
|
||||
writeItems.add(TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
@@ -905,28 +924,6 @@ public class Accounts extends AbstractDynamoDbStore {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> usernameHashAvailable(final byte[] username) {
|
||||
return usernameHashAvailable(Optional.empty(), username);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> usernameHashAvailable(final Optional<UUID> accountUuid, final byte[] usernameHash) {
|
||||
return itemByKeyAsync(usernamesConstraintTableName, ATTR_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash))
|
||||
.thenApply(maybeUsernameHashItem -> maybeUsernameHashItem
|
||||
.map(item -> {
|
||||
if (AttributeValues.getLong(item, ATTR_TTL, Long.MAX_VALUE) < clock.instant().getEpochSecond()) {
|
||||
// username hash was reserved, but has expired
|
||||
return true;
|
||||
}
|
||||
|
||||
// username hash is reserved by us
|
||||
return !AttributeValues.getBool(item, ATTR_CONFIRMED, true) && accountUuid
|
||||
.map(AttributeValues.getUUID(item, KEY_ACCOUNT_UUID, new UUID(0, 0))::equals)
|
||||
.orElse(false);
|
||||
})
|
||||
// If no item was found, then the username hash is free
|
||||
.orElse(true));
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public Optional<Account> getByE164(final String number) {
|
||||
return getByIndirectLookup(
|
||||
|
||||
+12
-26
@@ -468,8 +468,7 @@ public class AccountsManager {
|
||||
|
||||
if (pniSignedPreKeys != null) {
|
||||
pniSignedPreKeys.forEach((deviceId, signedPreKey) ->
|
||||
keysManager.buildWriteItemForEcSignedPreKey(phoneNumberIdentifier, deviceId, signedPreKey)
|
||||
.ifPresent(keyWriteItems::add));
|
||||
keyWriteItems.add(keysManager.buildWriteItemForEcSignedPreKey(phoneNumberIdentifier, deviceId, signedPreKey)));
|
||||
}
|
||||
|
||||
if (pniPqLastResortPreKeys != null) {
|
||||
@@ -579,23 +578,17 @@ public class AccountsManager {
|
||||
}
|
||||
|
||||
private CompletableFuture<byte[]> checkAndReserveNextUsernameHash(final Account account, final Queue<byte[]> requestedUsernameHashes) {
|
||||
final byte[] usernameHash;
|
||||
final byte[] usernameHash = requestedUsernameHashes.remove();
|
||||
|
||||
try {
|
||||
usernameHash = requestedUsernameHashes.remove();
|
||||
} catch (final NoSuchElementException e) {
|
||||
return CompletableFuture.failedFuture(new UsernameHashNotAvailableException());
|
||||
}
|
||||
|
||||
return accounts.usernameHashAvailable(usernameHash)
|
||||
.thenCompose(usernameHashAvailable -> {
|
||||
if (usernameHashAvailable) {
|
||||
return accounts.reserveUsernameHash(account, usernameHash, USERNAME_HASH_RESERVATION_TTL_MINUTES)
|
||||
.thenApply(ignored -> usernameHash);
|
||||
} else {
|
||||
return checkAndReserveNextUsernameHash(account, requestedUsernameHashes);
|
||||
}
|
||||
});
|
||||
return accounts.reserveUsernameHash(account, usernameHash, USERNAME_HASH_RESERVATION_TTL_MINUTES)
|
||||
.thenApply(ignored -> usernameHash)
|
||||
.exceptionallyComposeAsync(
|
||||
throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof UsernameHashNotAvailableException && !requestedUsernameHashes.isEmpty()) {
|
||||
return checkAndReserveNextUsernameHash(account, requestedUsernameHashes);
|
||||
}
|
||||
return CompletableFuture.failedFuture(throwable);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -629,14 +622,7 @@ public class AccountsManager {
|
||||
.thenCompose(ignored -> updateWithRetriesAsync(
|
||||
account,
|
||||
a -> true,
|
||||
a -> accounts.usernameHashAvailable(Optional.of(account.getUuid()), reservedUsernameHash)
|
||||
.thenCompose(usernameHashAvailable -> {
|
||||
if (!usernameHashAvailable) {
|
||||
return CompletableFuture.failedFuture(new UsernameHashNotAvailableException());
|
||||
}
|
||||
|
||||
return accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername);
|
||||
}),
|
||||
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
|
||||
() -> accounts.getByAccountIdentifierAsync(account.getUuid()).thenApply(Optional::orElseThrow),
|
||||
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR,
|
||||
MAX_UPDATE_ATTEMPTS
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -246,6 +247,10 @@ public class Device {
|
||||
this.phoneNumberIdentityRegistrationId = phoneNumberIdentityRegistrationId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Please retrieve signed pre-keys via {@link KeysManager#getEcSignedPreKey(UUID, byte)} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public ECSignedPreKey getSignedPreKey(final IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> signedPreKey;
|
||||
|
||||
@@ -6,12 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
@@ -20,8 +18,6 @@ import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
|
||||
public class KeysManager {
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private final SingleUseECPreKeyStore ecPreKeys;
|
||||
private final SingleUseKEMPreKeyStore pqPreKeys;
|
||||
private final RepeatedUseECSignedPreKeyStore ecSignedPreKeys;
|
||||
@@ -32,22 +28,18 @@ public class KeysManager {
|
||||
final String ecTableName,
|
||||
final String pqTableName,
|
||||
final String ecSignedPreKeysTableName,
|
||||
final String pqLastResortTableName,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
final String pqLastResortTableName) {
|
||||
this.ecPreKeys = new SingleUseECPreKeyStore(dynamoDbAsyncClient, ecTableName);
|
||||
this.pqPreKeys = new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, pqTableName);
|
||||
this.ecSignedPreKeys = new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, ecSignedPreKeysTableName);
|
||||
this.pqLastResortKeys = new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, pqLastResortTableName);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public Optional<TransactWriteItem> buildWriteItemForEcSignedPreKey(final UUID identifier,
|
||||
public TransactWriteItem buildWriteItemForEcSignedPreKey(final UUID identifier,
|
||||
final byte deviceId,
|
||||
final ECSignedPreKey ecSignedPreKey) {
|
||||
|
||||
return dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().storeEcSignedPreKeys()
|
||||
? Optional.of(ecSignedPreKeys.buildTransactWriteItemForInsertion(identifier, deviceId, ecSignedPreKey))
|
||||
: Optional.empty();
|
||||
return ecSignedPreKeys.buildTransactWriteItemForInsertion(identifier, deviceId, ecSignedPreKey);
|
||||
}
|
||||
|
||||
public TransactWriteItem buildWriteItemForLastResortKey(final UUID identifier,
|
||||
@@ -65,51 +57,28 @@ public class KeysManager {
|
||||
final KEMSignedPreKey aciPqLastResortPreKey,
|
||||
final KEMSignedPreKey pniLastResortPreKey) {
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>(List.of(
|
||||
return List.of(
|
||||
ecSignedPreKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, aciSignedPreKey),
|
||||
ecSignedPreKeys.buildTransactWriteItemForInsertion(phoneNumberIdentifier, deviceId, pniSignedPreKey),
|
||||
pqLastResortKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, aciPqLastResortPreKey),
|
||||
pqLastResortKeys.buildTransactWriteItemForInsertion(phoneNumberIdentifier, deviceId, pniLastResortPreKey)
|
||||
));
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().storeEcSignedPreKeys()) {
|
||||
writeItems.addAll(List.of(
|
||||
ecSignedPreKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, aciSignedPreKey),
|
||||
ecSignedPreKeys.buildTransactWriteItemForInsertion(phoneNumberIdentifier, deviceId, pniSignedPreKey)
|
||||
));
|
||||
}
|
||||
|
||||
return writeItems;
|
||||
);
|
||||
}
|
||||
|
||||
public List<TransactWriteItem> buildWriteItemsForRemovedDevice(final UUID accountIdentifier,
|
||||
final UUID phoneNumberIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>(List.of(
|
||||
return List.of(
|
||||
ecSignedPreKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId),
|
||||
ecSignedPreKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId),
|
||||
pqLastResortKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId),
|
||||
pqLastResortKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId)
|
||||
));
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().deleteEcSignedPreKeys()) {
|
||||
writeItems.addAll(List.of(
|
||||
ecSignedPreKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId),
|
||||
ecSignedPreKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId)
|
||||
));
|
||||
}
|
||||
|
||||
return writeItems;
|
||||
);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> storeEcSignedPreKeys(final UUID identifier, final byte deviceId, final ECSignedPreKey ecSignedPreKey) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getEcPreKeyMigrationConfiguration().storeEcSignedPreKeys()) {
|
||||
return ecSignedPreKeys.store(identifier, deviceId, ecSignedPreKey);
|
||||
} else {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> storeEcSignedPreKeyIfAbsent(final UUID identifier, final byte deviceId,
|
||||
final ECSignedPreKey signedPreKey) {
|
||||
return ecSignedPreKeys.storeIfAbsent(identifier, deviceId, signedPreKey);
|
||||
return ecSignedPreKeys.store(identifier, deviceId, ecSignedPreKey);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> storePqLastResort(final UUID identifier, final byte deviceId, final KEMSignedPreKey lastResortKey) {
|
||||
|
||||
-27
@@ -7,27 +7,17 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
|
||||
public class RepeatedUseECSignedPreKeyStore extends RepeatedUseSignedPreKeyStore<ECSignedPreKey> {
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
|
||||
public RepeatedUseECSignedPreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
|
||||
super(dynamoDbAsyncClient, tableName);
|
||||
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -53,21 +43,4 @@ public class RepeatedUseECSignedPreKeyStore extends RepeatedUseSignedPreKeyStore
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> storeIfAbsent(final UUID identifier, final byte deviceId, final ECSignedPreKey signedPreKey) {
|
||||
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(getItemFromPreKey(identifier, deviceId, signedPreKey))
|
||||
.conditionExpression("attribute_not_exists(#public_key)")
|
||||
.expressionAttributeNames(Map.of("#public_key", ATTR_PUBLIC_KEY))
|
||||
.build())
|
||||
.thenApply(ignored -> true)
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,12 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class HttpUtils {
|
||||
|
||||
private HttpUtils() {
|
||||
@@ -14,4 +20,18 @@ public final class HttpUtils {
|
||||
public static boolean isSuccessfulResponse(final int statusCode) {
|
||||
return statusCode >= 200 && statusCode < 300;
|
||||
}
|
||||
|
||||
public static String queryParamString(final Collection<Map.Entry<String, String>> params) {
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
if (params.isEmpty()) {
|
||||
return sb.toString();
|
||||
}
|
||||
sb.append("?");
|
||||
sb.append(params.stream()
|
||||
.map(e -> "%s=%s".formatted(
|
||||
URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8),
|
||||
URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8)))
|
||||
.collect(Collectors.joining("&")));
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -168,8 +168,8 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
configuration.getDynamoDbTables().getEcKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getEcSignedPreKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName(),
|
||||
dynamicConfigurationManager);
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName()
|
||||
);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
|
||||
+2
-2
@@ -142,8 +142,8 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getEcKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getEcSignedPreKeys().getTableName(),
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName(),
|
||||
dynamicConfigurationManager);
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName()
|
||||
);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuple3;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class MigrateSignedECPreKeysCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private static final String STORE_KEY_ATTEMPT_COUNTER_NAME =
|
||||
MetricsUtil.name(MigrateSignedECPreKeysCommand.class, "storeKeyAttempt");
|
||||
|
||||
// It's tricky to find, but the default connection count for the AWS SDK's async DynamoDB client is 50. As long as
|
||||
// we stay below that, we should be fine.
|
||||
private static final int DEFAULT_MAX_CONCURRENCY = 32;
|
||||
|
||||
private static final String BUFFER_ARGUMENT = "buffer";
|
||||
private static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MigrateSignedECPreKeysCommand.class);
|
||||
|
||||
public MigrateSignedECPreKeysCommand() {
|
||||
super("migrate-signed-ec-pre-keys", "Migrate signed EC pre-keys from Account records to a dedicated table");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(DEFAULT_MAX_CONCURRENCY)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--buffer")
|
||||
.type(Integer.class)
|
||||
.dest(BUFFER_ARGUMENT)
|
||||
.setDefault(16_384)
|
||||
.help("Devices to buffer");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final KeysManager keysManager = getCommandDependencies().keysManager();
|
||||
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final int bufferSize = getNamespace().getInt(BUFFER_ARGUMENT);
|
||||
|
||||
accounts
|
||||
.flatMap(account -> Flux.fromIterable(account.getDevices())
|
||||
.flatMap(device -> Flux.fromArray(IdentityType.values())
|
||||
.filter(identityType -> device.getSignedPreKey(identityType) != null)
|
||||
.map(identityType -> Tuples.of(account.getIdentifier(identityType), device.getId(), device.getSignedPreKey(identityType)))))
|
||||
.buffer(bufferSize)
|
||||
.map(source -> {
|
||||
final List<Tuple3<UUID, Byte, ECSignedPreKey>> shuffled = new ArrayList<>(source);
|
||||
Collections.shuffle(shuffled);
|
||||
return shuffled;
|
||||
})
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(keyTuple -> {
|
||||
final UUID identifier = keyTuple.getT1();
|
||||
final byte deviceId = keyTuple.getT2();
|
||||
final ECSignedPreKey signedPreKey = keyTuple.getT3();
|
||||
|
||||
return Mono.fromFuture(() -> keysManager.storeEcSignedPreKeyIfAbsent(identifier, deviceId, signedPreKey))
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).onRetryExhaustedThrow((spec, rs) -> rs.failure()))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to migrate key for UUID {}, device {}", identifier, deviceId);
|
||||
return Mono.just(false);
|
||||
})
|
||||
.doOnSuccess(keyStored -> Metrics.counter(STORE_KEY_ATTEMPT_COUNTER_NAME, "stored", String.valueOf(keyStored)).increment());
|
||||
}, maxConcurrency)
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
}
|
||||
+75
-18
@@ -10,10 +10,14 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.shaded.reactor.util.function.Tuple2;
|
||||
import io.micrometer.shaded.reactor.util.function.Tuples;
|
||||
import java.util.Collection;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -21,17 +25,27 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuple2;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private static final int DEFAULT_MAX_CONCURRENCY = 16;
|
||||
private static final int DEFAULT_BUFFER_SIZE = 16_384;
|
||||
private static final int DEFAULT_RETRIES = 3;
|
||||
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
private static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
private static final String BUFFER_ARGUMENT = "buffer";
|
||||
private static final String RETRIES_ARGUMENT = "retries";
|
||||
|
||||
private static final String REMOVED_DEVICES_COUNTER_NAME = name(RemoveExpiredLinkedDevicesCommand.class,
|
||||
"removedDevices");
|
||||
|
||||
private static final String RETRIED_UPDATES_COUNTER_NAME = name(RemoveExpiredLinkedDevicesCommand.class,
|
||||
"retries");
|
||||
|
||||
private static final String FAILED_UPDATES_COUNTER_NAME = name(RemoveExpiredLinkedDevicesCommand.class,
|
||||
"failedUpdates");
|
||||
private static final Logger logger = LoggerFactory.getLogger(RemoveExpiredLinkedDevicesCommand.class);
|
||||
@@ -56,6 +70,18 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(DEFAULT_MAX_CONCURRENCY)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--buffer")
|
||||
.type(Integer.class)
|
||||
.dest(BUFFER_ARGUMENT)
|
||||
.setDefault(DEFAULT_BUFFER_SIZE)
|
||||
.help("Accounts to buffer");
|
||||
|
||||
subparser.addArgument("--retries")
|
||||
.type(Integer.class)
|
||||
.dest(RETRIES_ARGUMENT)
|
||||
.setDefault(DEFAULT_RETRIES)
|
||||
.help("Maximum number of retries permitted per device");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -63,23 +89,33 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
|
||||
|
||||
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final int bufferSize = getNamespace().getInt(BUFFER_ARGUMENT);
|
||||
final int maxRetries = getNamespace().getInt(RETRIES_ARGUMENT);
|
||||
|
||||
final Counter successCounter = Metrics.counter(REMOVED_DEVICES_COUNTER_NAME, "dryRun", String.valueOf(dryRun));
|
||||
final Counter errorCounter = Metrics.counter(FAILED_UPDATES_COUNTER_NAME);
|
||||
|
||||
accounts.flatMap(account -> Flux.fromIterable(getExpiredLinkedDeviceIds(account)))
|
||||
.flatMap(accountAndExpiredDeviceId -> {
|
||||
final Account account = accountAndExpiredDeviceId.getT1();
|
||||
final byte deviceId = accountAndExpiredDeviceId.getT2();
|
||||
accounts.map(a -> Tuples.of(a, getExpiredLinkedDeviceIds(a.getDevices())))
|
||||
.filter(accountAndExpiredDevices -> !accountAndExpiredDevices.getT2().isEmpty())
|
||||
.buffer(bufferSize)
|
||||
.map(source -> {
|
||||
final List<Tuple2<Account, Set<Byte>>> shuffled = new ArrayList<>(source);
|
||||
Collections.shuffle(shuffled);
|
||||
return shuffled;
|
||||
})
|
||||
.limitRate(2)
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(accountAndExpiredDevices -> {
|
||||
final Account account = accountAndExpiredDevices.getT1();
|
||||
final Set<Byte> expiredDevices = accountAndExpiredDevices.getT2();
|
||||
|
||||
Mono<Account> removeDevice = dryRun
|
||||
? Mono.just(account)
|
||||
: Mono.fromFuture(() -> getCommandDependencies().accountsManager().removeDevice(account, deviceId));
|
||||
final Mono<Long> accountUpdate = dryRun
|
||||
? Mono.just((long) expiredDevices.size())
|
||||
: deleteDevices(account, expiredDevices, maxRetries);
|
||||
|
||||
return removeDevice.doOnNext(ignored -> successCounter.increment())
|
||||
return accountUpdate
|
||||
.doOnNext(successCounter::increment)
|
||||
.onErrorResume(t -> {
|
||||
logger.warn("Failed to remove expired linked device {}.{}", account.getUuid(), deviceId, t);
|
||||
errorCounter.increment();
|
||||
logger.warn("Failed to remove expired linked devices for {}", account.getUuid(), t);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
@@ -87,14 +123,35 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
|
||||
.block();
|
||||
}
|
||||
|
||||
private Mono<Long> deleteDevices(final Account account, final Set<Byte> expiredDevices, final int maxRetries) {
|
||||
|
||||
final Counter retryCounter = Metrics.counter(RETRIED_UPDATES_COUNTER_NAME);
|
||||
final Counter errorCounter = Metrics.counter(FAILED_UPDATES_COUNTER_NAME);
|
||||
|
||||
return Flux.fromIterable(expiredDevices)
|
||||
.flatMap(deviceId ->
|
||||
Mono.fromFuture(() -> getCommandDependencies().accountsManager().removeDevice(account, deviceId))
|
||||
.retryWhen(Retry.backoff(maxRetries, Duration.ofSeconds(1))
|
||||
.doAfterRetry(ignored -> retryCounter.increment())
|
||||
.onRetryExhaustedThrow((spec, rs) -> rs.failure()))
|
||||
.onErrorResume(t -> {
|
||||
logger.info("Failed to remove expired linked device {}.{}", account.getUuid(), deviceId, t);
|
||||
errorCounter.increment();
|
||||
return Mono.empty();
|
||||
}),
|
||||
// limit concurrency to avoid contested updates
|
||||
1)
|
||||
.count();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
protected static Collection<Tuple2<Account, Byte>> getExpiredLinkedDeviceIds(Account account) {
|
||||
return account.getDevices().stream()
|
||||
protected static Set<Byte> getExpiredLinkedDeviceIds(List<Device> devices) {
|
||||
return devices.stream()
|
||||
// linked devices
|
||||
.filter(Predicate.not(Device::isPrimary))
|
||||
// that are expired
|
||||
.filter(Device::isExpired)
|
||||
.map(device -> Tuples.of(account, device.getId()))
|
||||
.toList();
|
||||
.map(Device::getId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
+124
-26
@@ -9,11 +9,13 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.grpc.Status;
|
||||
@@ -27,16 +29,20 @@ import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -55,8 +61,7 @@ public class BackupManagerTest {
|
||||
|
||||
@RegisterExtension
|
||||
public static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS,
|
||||
DynamoDbExtensionSchema.Tables.BACKUP_MEDIA);
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS);
|
||||
|
||||
private final TestClock testClock = TestClock.now();
|
||||
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(testClock);
|
||||
@@ -66,15 +71,18 @@ public class BackupManagerTest {
|
||||
private final UUID aci = UUID.randomUUID();
|
||||
|
||||
private BackupManager backupManager;
|
||||
private BackupsDb backupsDb;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
reset(tusCredentialGenerator);
|
||||
testClock.unpin();
|
||||
this.backupsDb = new BackupsDb(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(),
|
||||
testClock);
|
||||
this.backupManager = new BackupManager(
|
||||
new BackupsDb(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(), DynamoDbExtensionSchema.Tables.BACKUP_MEDIA.tableName(),
|
||||
testClock),
|
||||
backupsDb,
|
||||
backupAuthTestUtil.params,
|
||||
tusCredentialGenerator,
|
||||
remoteStorageManager,
|
||||
@@ -256,25 +264,23 @@ public class BackupManagerTest {
|
||||
.thenReturn(new MessageBackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
|
||||
when(remoteStorageManager.copy(eq(URI.create("cdn3.example.org/attachments/abc")), eq(100), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
final MediaEncryptionParameters encryptionParams = new MediaEncryptionParameters(
|
||||
TestRandomUtil.nextBytes(32),
|
||||
TestRandomUtil.nextBytes(32),
|
||||
TestRandomUtil.nextBytes(16));
|
||||
|
||||
final BackupManager.StorageDescriptor copied = backupManager.copyToBackup(
|
||||
backupUser, 3, "abc", 100, mock(MediaEncryptionParameters.class),
|
||||
"def".getBytes(StandardCharsets.UTF_8)).join();
|
||||
backupUser, 3, "abc", 100, encryptionParams, "def".getBytes(StandardCharsets.UTF_8)).join();
|
||||
|
||||
assertThat(copied.cdn()).isEqualTo(3);
|
||||
assertThat(copied.key()).isEqualTo("def".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
final Map<String, AttributeValue> backup = getBackupItem(backupUser);
|
||||
final long bytesUsed = AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_BYTES_USED, 0L);
|
||||
assertThat(bytesUsed).isEqualTo(100);
|
||||
assertThat(bytesUsed).isEqualTo(encryptionParams.outputSize(100));
|
||||
|
||||
final long mediaCount = AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_COUNT, 0L);
|
||||
assertThat(mediaCount).isEqualTo(1);
|
||||
|
||||
final Map<String, AttributeValue> mediaItem = getBackupMediaItem(backupUser,
|
||||
"def".getBytes(StandardCharsets.UTF_8));
|
||||
final long mediaLength = AttributeValues.getLong(mediaItem, BackupsDb.ATTR_LENGTH, 0L);
|
||||
assertThat(mediaLength).isEqualTo(100L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -292,12 +298,115 @@ public class BackupManagerTest {
|
||||
mock(MediaEncryptionParameters.class),
|
||||
"def".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// usage should be rolled back after a known copy failure
|
||||
final Map<String, AttributeValue> backup = getBackupItem(backupUser);
|
||||
assertThat(AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_BYTES_USED, -1L)).isEqualTo(0L);
|
||||
assertThat(AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_COUNT, -1L)).isEqualTo(0L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void quotaEnforcementNoRecalculation() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
verifyNoInteractions(remoteStorageManager);
|
||||
|
||||
// set the backupsDb to be out of quota at t=0
|
||||
testClock.pin(Instant.ofEpochSecond(1));
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES, 1000)).join();
|
||||
// check still within staleness bound (t=0 + 1 day - 1 sec)
|
||||
testClock.pin(Instant.ofEpochSecond(0)
|
||||
.plus(BackupManager.MAX_QUOTA_STALENESS)
|
||||
.minus(Duration.ofSeconds(1)));
|
||||
assertThat(backupManager.canStoreMedia(backupUser, 10).join()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void quotaEnforcementRecalculation() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
final String backupMediaPrefix = "%s/%s/".formatted(
|
||||
BackupManager.encodeBackupIdForCdn(backupUser),
|
||||
BackupManager.MEDIA_DIRECTORY_NAME);
|
||||
|
||||
// on recalculation, say there's actually 10 bytes left
|
||||
when(remoteStorageManager.calculateBytesUsed(eq(backupMediaPrefix)))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(new UsageInfo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - 10, 1000)));
|
||||
|
||||
// set the backupsDb to be out of quota at t=0
|
||||
testClock.pin(Instant.ofEpochSecond(0));
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES, 1000)).join();
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(BackupManager.MAX_QUOTA_STALENESS));
|
||||
assertThat(backupManager.canStoreMedia(backupUser, 10).join()).isTrue();
|
||||
|
||||
// backupsDb should have the new value
|
||||
final BackupsDb.TimestampedUsageInfo info = backupsDb.getMediaUsage(backupUser).join();
|
||||
assertThat(info.lastRecalculationTime()).isEqualTo(
|
||||
Instant.ofEpochSecond(0).plus(BackupManager.MAX_QUOTA_STALENESS));
|
||||
assertThat(info.usageInfo().bytesUsed()).isEqualTo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - 10);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"true, 10, 10, true",
|
||||
"true, 10, 11, false",
|
||||
"true, 0, 1, false",
|
||||
"true, 0, 0, true",
|
||||
"false, 10, 10, true",
|
||||
"false, 10, 11, false",
|
||||
"false, 0, 1, false",
|
||||
"false, 0, 0, true",
|
||||
})
|
||||
public void quotaEnforcement(
|
||||
boolean recalculation,
|
||||
final long spaceLeft,
|
||||
final long mediaToAddSize,
|
||||
boolean shouldAccept) {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
final String backupMediaPrefix = "%s/%s/".formatted(
|
||||
BackupManager.encodeBackupIdForCdn(backupUser),
|
||||
BackupManager.MEDIA_DIRECTORY_NAME);
|
||||
|
||||
// set the backupsDb to be out of quota at t=0
|
||||
testClock.pin(Instant.ofEpochSecond(0));
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - spaceLeft, 1000))
|
||||
.join();
|
||||
|
||||
if (recalculation) {
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(BackupManager.MAX_QUOTA_STALENESS).plus(Duration.ofSeconds(1)));
|
||||
when(remoteStorageManager.calculateBytesUsed(eq(backupMediaPrefix)))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new UsageInfo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES - spaceLeft, 1000)));
|
||||
}
|
||||
assertThat(backupManager.canStoreMedia(backupUser, mediaToAddSize).join()).isEqualTo(shouldAccept);
|
||||
if (recalculation && !shouldAccept) {
|
||||
// should have recalculated if we exceeded quota
|
||||
verify(remoteStorageManager, times(1)).calculateBytesUsed(anyString());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "cursor"})
|
||||
public void list(final String cursorVal) {
|
||||
final Optional<String> cursor = Optional.of(cursorVal).filter(StringUtils::isNotBlank);
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
final String backupMediaPrefix = "%s/%s/".formatted(
|
||||
BackupManager.encodeBackupIdForCdn(backupUser),
|
||||
BackupManager.MEDIA_DIRECTORY_NAME);
|
||||
|
||||
when(remoteStorageManager.cdnNumber()).thenReturn(13);
|
||||
when(remoteStorageManager.list(eq(backupMediaPrefix), eq(cursor), eq(17L)))
|
||||
.thenReturn(CompletableFuture.completedFuture(new RemoteStorageManager.ListResult(
|
||||
List.of(new RemoteStorageManager.ListResult.Entry("aaa", 123)),
|
||||
Optional.of("newCursor")
|
||||
)));
|
||||
|
||||
final BackupManager.ListMediaResult result = backupManager.list(backupUser, cursor, 17)
|
||||
.toCompletableFuture().join();
|
||||
assertThat(result.media()).hasSize(1);
|
||||
assertThat(result.media().get(0).cdn()).isEqualTo(13);
|
||||
assertThat(result.media().get(0).key()).isEqualTo(Base64.getDecoder().decode("aaa".getBytes(StandardCharsets.UTF_8)));
|
||||
assertThat(result.media().get(0).length()).isEqualTo(123);
|
||||
assertThat(result.cursor()).get().isEqualTo("newCursor");
|
||||
|
||||
final Map<String, AttributeValue> media = getBackupMediaItem(backupUser, "def".getBytes(StandardCharsets.UTF_8));
|
||||
assertThat(media).isEmpty();
|
||||
}
|
||||
|
||||
private Map<String, AttributeValue> getBackupItem(final AuthenticatedBackupUser backupUser) {
|
||||
@@ -308,17 +417,6 @@ public class BackupManagerTest {
|
||||
.item();
|
||||
}
|
||||
|
||||
private Map<String, AttributeValue> getBackupMediaItem(final AuthenticatedBackupUser backupUser,
|
||||
final byte[] mediaId) {
|
||||
return DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.BACKUP_MEDIA.tableName())
|
||||
.key(Map.of(
|
||||
BackupsDb.KEY_BACKUP_ID_HASH, AttributeValues.b(hashedBackupId(backupUser.backupId())),
|
||||
BackupsDb.KEY_MEDIA_ID, AttributeValues.b(mediaId)))
|
||||
.build())
|
||||
.item();
|
||||
}
|
||||
|
||||
private void checkExpectedExpirations(
|
||||
final Instant expectedExpiration,
|
||||
final @Nullable Instant expectedMediaExpiration,
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
public class BackupMediaEncrypterTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 2, 15, 16, 17, 63, 64, 65, 1023, 1024, 1025})
|
||||
public void sizeCalc() {
|
||||
final MediaEncryptionParameters params = new MediaEncryptionParameters(
|
||||
TestRandomUtil.nextBytes(32),
|
||||
TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(16));
|
||||
final BackupMediaEncrypter encrypter = new BackupMediaEncrypter(params);
|
||||
assertThat(params.outputSize(1)).isEqualTo(encrypter.outputSize(1));
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,13 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
@@ -27,8 +30,7 @@ public class BackupsDbTest {
|
||||
|
||||
@RegisterExtension
|
||||
public static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS,
|
||||
DynamoDbExtensionSchema.Tables.BACKUP_MEDIA);
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS);
|
||||
|
||||
private final TestClock testClock = TestClock.now();
|
||||
private BackupsDb backupsDb;
|
||||
@@ -37,26 +39,10 @@ public class BackupsDbTest {
|
||||
public void setup() {
|
||||
testClock.unpin();
|
||||
backupsDb = new BackupsDb(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(), DynamoDbExtensionSchema.Tables.BACKUP_MEDIA.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(),
|
||||
testClock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trackMediaIdempotent() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 100).join();
|
||||
assertDoesNotThrow(() ->
|
||||
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 100).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trackMediaLengthChange() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 100).join();
|
||||
CompletableFutureTestUtil.assertFailsWithCause(InvalidLengthException.class,
|
||||
this.backupsDb.trackMedia(backupUser, "abc".getBytes(StandardCharsets.UTF_8), 99));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trackMediaStats() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
@@ -64,27 +50,33 @@ public class BackupsDbTest {
|
||||
backupsDb.addMessageBackup(backupUser).join();
|
||||
int total = 0;
|
||||
for (int i = 0; i < 5; i++) {
|
||||
this.backupsDb.trackMedia(backupUser, Integer.toString(i).getBytes(StandardCharsets.UTF_8), i).join();
|
||||
this.backupsDb.trackMedia(backupUser, i).join();
|
||||
total += i;
|
||||
final BackupsDb.BackupDescription description = this.backupsDb.describeBackup(backupUser).join();
|
||||
assertThat(description.mediaUsedSpace().get()).isEqualTo(total);
|
||||
}
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
this.backupsDb.untrackMedia(backupUser, Integer.toString(i).getBytes(StandardCharsets.UTF_8), i).join();
|
||||
this.backupsDb.trackMedia(backupUser, -i).join();
|
||||
total -= i;
|
||||
final BackupsDb.BackupDescription description = this.backupsDb.describeBackup(backupUser).join();
|
||||
assertThat(description.mediaUsedSpace().get()).isEqualTo(total);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static byte[] hashedBackupId(final byte[] backupId) {
|
||||
try {
|
||||
return Arrays.copyOf(MessageDigest.getInstance("SHA-256").digest(backupId), 16);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
public void setUsage(boolean mediaAlreadyExists) {
|
||||
testClock.pin(Instant.ofEpochSecond(5));
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupTier.MEDIA);
|
||||
if (mediaAlreadyExists) {
|
||||
this.backupsDb.trackMedia(backupUser, 10).join();
|
||||
}
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo( 113, 17)).join();
|
||||
final BackupsDb.TimestampedUsageInfo info = backupsDb.getMediaUsage(backupUser).join();
|
||||
assertThat(info.lastRecalculationTime()).isEqualTo(Instant.ofEpochSecond(5));
|
||||
assertThat(info.usageInfo().bytesUsed()).isEqualTo(113L);
|
||||
assertThat(info.usageInfo().numObjects()).isEqualTo(17L);
|
||||
}
|
||||
|
||||
private AuthenticatedBackupUser backupUser(final byte[] backupId, final BackupTier backupTier) {
|
||||
|
||||
+70
-2
@@ -1,16 +1,20 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
|
||||
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
@@ -19,6 +23,8 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Executors;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
@@ -33,9 +39,12 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
@@ -62,7 +71,11 @@ public class Cdn3RemoteStorageManagerTest {
|
||||
Executors.newSingleThreadScheduledExecutor(),
|
||||
new CircuitBreakerConfiguration(),
|
||||
new RetryConfiguration(),
|
||||
Collections.emptyList());
|
||||
Collections.emptyList(),
|
||||
new Cdn3StorageManagerConfiguration(
|
||||
wireMock.url("storage-manager/"),
|
||||
"clientId",
|
||||
new SecretString("clientSecret")));
|
||||
|
||||
wireMock.stubFor(get(urlEqualTo("/cdn2/source/small"))
|
||||
.willReturn(aResponse()
|
||||
@@ -125,7 +138,9 @@ public class Cdn3RemoteStorageManagerTest {
|
||||
.toCompletableFuture().join();
|
||||
|
||||
final byte[] destBody = wireMock.findAll(postRequestedFor(urlEqualTo("/cdn3/dest"))).get(0).getBody();
|
||||
assertThat(destBody.length).isEqualTo(new BackupMediaEncrypter(params).outputSize(LARGE.length()));
|
||||
assertThat(destBody.length)
|
||||
.isEqualTo(new BackupMediaEncrypter(params).outputSize(LARGE.length()))
|
||||
.isEqualTo(params.outputSize(LARGE.length()));
|
||||
assertThat(new String(decrypt(destBody), StandardCharsets.UTF_8)).isEqualTo(LARGE);
|
||||
}
|
||||
|
||||
@@ -176,4 +191,57 @@ public class Cdn3RemoteStorageManagerTest {
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(AES_KEY, "AES"), new IvParameterSpec(IV));
|
||||
return cipher.doFinal(encrypted, IV.length, encrypted.length - IV.length - mac.getMacLength());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void list() throws JsonProcessingException {
|
||||
wireMock.stubFor(get(urlPathEqualTo("/storage-manager/backups/"))
|
||||
.withQueryParam("prefix", equalTo("abc/"))
|
||||
.withQueryParam("limit", equalTo("3"))
|
||||
.withHeader(Cdn3RemoteStorageManager.CLIENT_ID_HEADER, equalTo("clientId"))
|
||||
.withHeader(Cdn3RemoteStorageManager.CLIENT_SECRET_HEADER, equalTo("clientSecret"))
|
||||
.willReturn(aResponse()
|
||||
.withBody(SystemMapper.jsonMapper().writeValueAsString(new Cdn3RemoteStorageManager.Cdn3ListResponse(
|
||||
List.of(
|
||||
new Cdn3RemoteStorageManager.Cdn3ListResponse.Entry("abc/x/y", 3),
|
||||
new Cdn3RemoteStorageManager.Cdn3ListResponse.Entry("abc/y", 4),
|
||||
new Cdn3RemoteStorageManager.Cdn3ListResponse.Entry("abc/z", 5)
|
||||
), "cursor")))));
|
||||
final RemoteStorageManager.ListResult result = remoteStorageManager
|
||||
.list("abc/", Optional.empty(), 3)
|
||||
.toCompletableFuture().join();
|
||||
assertThat(result.cursor()).get().isEqualTo("cursor");
|
||||
assertThat(result.objects()).hasSize(3);
|
||||
|
||||
// should strip the common prefix
|
||||
assertThat(result.objects()).isEqualTo(List.of(
|
||||
new RemoteStorageManager.ListResult.Entry("x/y", 3),
|
||||
new RemoteStorageManager.ListResult.Entry("y", 4),
|
||||
new RemoteStorageManager.ListResult.Entry("z", 5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void prefixMissing() throws JsonProcessingException {
|
||||
wireMock.stubFor(get(urlPathEqualTo("/storage-manager/backups/"))
|
||||
.willReturn(aResponse()
|
||||
.withBody(SystemMapper.jsonMapper().writeValueAsString(new Cdn3RemoteStorageManager.Cdn3ListResponse(
|
||||
List.of(new Cdn3RemoteStorageManager.Cdn3ListResponse.Entry("x", 3)),
|
||||
"cursor")))));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(IOException.class,
|
||||
remoteStorageManager.list("abc/", Optional.empty(), 3).toCompletableFuture());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usage() throws JsonProcessingException {
|
||||
wireMock.stubFor(get(urlPathEqualTo("/storage-manager/usage"))
|
||||
.withQueryParam("prefix", equalTo("abc/"))
|
||||
.willReturn(aResponse()
|
||||
.withBody(SystemMapper.jsonMapper().writeValueAsString(new Cdn3RemoteStorageManager.UsageResponse(
|
||||
17,
|
||||
113)))));
|
||||
final UsageInfo result = remoteStorageManager.calculateBytesUsed("abc/")
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
assertThat(result.numObjects()).isEqualTo(17);
|
||||
assertThat(result.bytesUsed()).isEqualTo(113);
|
||||
}
|
||||
}
|
||||
+40
@@ -46,6 +46,7 @@ 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.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
|
||||
@@ -438,4 +439,43 @@ public class ArchiveControllerTest {
|
||||
).toList())));
|
||||
assertThat(response.getStatus()).isEqualTo(413);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
public void list(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorProvided,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorReturned)
|
||||
throws VerificationFailedException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupTier.MEDIA, backupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new AuthenticatedBackupUser(presentation.getBackupId(), BackupTier.MEDIA)));
|
||||
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(15);
|
||||
final Optional<String> expectedCursor = cursorProvided ? Optional.of("myCursor") : Optional.empty();
|
||||
final Optional<String> returnedCursor = cursorReturned ? Optional.of("newCursor") : Optional.empty();
|
||||
|
||||
when(backupManager.list(any(), eq(expectedCursor), eq(17)))
|
||||
.thenReturn(CompletableFuture.completedFuture(new BackupManager.ListMediaResult(
|
||||
List.of(new BackupManager.StorageDescriptorWithLength(1, mediaId, 100)),
|
||||
returnedCursor
|
||||
)));
|
||||
|
||||
WebTarget target = resources.getJerseyTest()
|
||||
.target("v1/archives/media/")
|
||||
.queryParam("limit", 17);
|
||||
if (cursorProvided) {
|
||||
target = target.queryParam("cursor", "myCursor");
|
||||
}
|
||||
final ArchiveController.ListResponse response = target
|
||||
.request()
|
||||
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
|
||||
.header("X-Signal-ZK-Auth-Signature", "aaa")
|
||||
.get(ArchiveController.ListResponse.class);
|
||||
|
||||
assertThat(response.storedMediaObjects()).hasSize(1);
|
||||
assertThat(response.storedMediaObjects().get(0).objectLength()).isEqualTo(100);
|
||||
assertThat(response.storedMediaObjects().get(0).mediaId()).isEqualTo(mediaId);
|
||||
assertThat(response.cursor()).isEqualTo(returnedCursor.orElse(null));
|
||||
}
|
||||
}
|
||||
+31
-24
@@ -199,14 +199,6 @@ class KeysControllerTest {
|
||||
when(sampleDevice2.isEnabled()).thenReturn(true);
|
||||
when(sampleDevice3.isEnabled()).thenReturn(false);
|
||||
when(sampleDevice4.isEnabled()).thenReturn(true);
|
||||
when(sampleDevice.getSignedPreKey(IdentityType.ACI)).thenReturn(SAMPLE_SIGNED_KEY);
|
||||
when(sampleDevice2.getSignedPreKey(IdentityType.ACI)).thenReturn(SAMPLE_SIGNED_KEY2);
|
||||
when(sampleDevice3.getSignedPreKey(IdentityType.ACI)).thenReturn(SAMPLE_SIGNED_KEY3);
|
||||
when(sampleDevice4.getSignedPreKey(IdentityType.ACI)).thenReturn(null);
|
||||
when(sampleDevice.getSignedPreKey(IdentityType.PNI)).thenReturn(SAMPLE_SIGNED_PNI_KEY);
|
||||
when(sampleDevice2.getSignedPreKey(IdentityType.PNI)).thenReturn(SAMPLE_SIGNED_PNI_KEY2);
|
||||
when(sampleDevice3.getSignedPreKey(IdentityType.PNI)).thenReturn(SAMPLE_SIGNED_PNI_KEY3);
|
||||
when(sampleDevice4.getSignedPreKey(IdentityType.PNI)).thenReturn(null);
|
||||
when(sampleDevice.getId()).thenReturn(sampleDeviceId);
|
||||
when(sampleDevice2.getId()).thenReturn(sampleDevice2Id);
|
||||
when(sampleDevice3.getId()).thenReturn(sampleDevice3Id);
|
||||
@@ -257,6 +249,24 @@ class KeysControllerTest {
|
||||
when(KEYS.getEcSignedPreKey(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
when(KEYS.storeEcSignedPreKeys(any(), anyByte(), any())).thenReturn(CompletableFutureTestUtil.almostCompletedFuture(null));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDeviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDevice2Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY2)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_UUID, sampleDevice3Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_KEY3)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDeviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDevice2Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY2)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(EXISTS_PNI, sampleDevice3Id))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(SAMPLE_SIGNED_PNI_KEY3)));
|
||||
|
||||
when(KEYS.takeEC(EXISTS_UUID, sampleDeviceId)).thenReturn(
|
||||
CompletableFuture.completedFuture(Optional.of(SAMPLE_KEY)));
|
||||
when(KEYS.takePQ(EXISTS_UUID, sampleDeviceId)).thenReturn(
|
||||
@@ -269,9 +279,13 @@ class KeysControllerTest {
|
||||
when(KEYS.getEcCount(AuthHelper.VALID_UUID, sampleDeviceId)).thenReturn(CompletableFuture.completedFuture(5));
|
||||
when(KEYS.getPqCount(AuthHelper.VALID_UUID, sampleDeviceId)).thenReturn(CompletableFuture.completedFuture(5));
|
||||
|
||||
when(AuthHelper.VALID_DEVICE.getSignedPreKey(IdentityType.ACI)).thenReturn(VALID_DEVICE_SIGNED_KEY);
|
||||
when(AuthHelper.VALID_DEVICE.getSignedPreKey(IdentityType.PNI)).thenReturn(VALID_DEVICE_PNI_SIGNED_KEY);
|
||||
when(AuthHelper.VALID_ACCOUNT.getIdentityKey(IdentityType.ACI)).thenReturn(null);
|
||||
|
||||
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE.getId()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(VALID_DEVICE_SIGNED_KEY)));
|
||||
|
||||
when(KEYS.getEcSignedPreKey(AuthHelper.VALID_PNI, AuthHelper.VALID_DEVICE.getId()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(VALID_DEVICE_PNI_SIGNED_KEY)));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -350,8 +364,7 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey());
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isNull();
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(existsAccount.getDevice(SAMPLE_DEVICE_ID).get().getSignedPreKey(IdentityType.ACI),
|
||||
result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
@@ -374,8 +387,7 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey());
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isNull();
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(existsAccount.getDevice(SAMPLE_DEVICE_ID).get().getSignedPreKey(IdentityType.ACI),
|
||||
result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
@@ -397,8 +409,7 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey());
|
||||
assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey());
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(existsAccount.getDevice(SAMPLE_DEVICE_ID).get().getSignedPreKey(IdentityType.ACI),
|
||||
result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
@@ -419,8 +430,7 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_KEY_PNI, result.getDevice(SAMPLE_DEVICE_ID).getPreKey());
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isNull();
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
|
||||
assertEquals(existsAccount.getDevice(SAMPLE_DEVICE_ID).get().getSignedPreKey(IdentityType.PNI),
|
||||
result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
@@ -441,8 +451,7 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_KEY_PNI, result.getDevice(SAMPLE_DEVICE_ID).getPreKey());
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isEqualTo(SAMPLE_PQ_KEY_PNI);
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
|
||||
assertEquals(existsAccount.getDevice(SAMPLE_DEVICE_ID).get().getSignedPreKey(IdentityType.PNI),
|
||||
result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
@@ -465,8 +474,7 @@ class KeysControllerTest {
|
||||
assertEquals(SAMPLE_KEY_PNI, result.getDevice(SAMPLE_DEVICE_ID).getPreKey());
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey()).isNull();
|
||||
assertThat(result.getDevice(SAMPLE_DEVICE_ID).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
|
||||
assertEquals(existsAccount.getDevice(SAMPLE_DEVICE_ID).get().getSignedPreKey(IdentityType.PNI),
|
||||
result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_PNI_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, SAMPLE_DEVICE_ID);
|
||||
@@ -501,8 +509,7 @@ class KeysControllerTest {
|
||||
assertThat(result.getDevicesCount()).isEqualTo(1);
|
||||
assertEquals(SAMPLE_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPreKey());
|
||||
assertEquals(SAMPLE_PQ_KEY, result.getDevice(SAMPLE_DEVICE_ID).getPqPreKey());
|
||||
assertEquals(existsAccount.getDevice(SAMPLE_DEVICE_ID).get().getSignedPreKey(IdentityType.ACI),
|
||||
result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
assertEquals(SAMPLE_SIGNED_KEY, result.getDevice(SAMPLE_DEVICE_ID).getSignedPreKey());
|
||||
|
||||
verify(KEYS).takeEC(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
verify(KEYS).takePQ(EXISTS_UUID, SAMPLE_DEVICE_ID);
|
||||
|
||||
+8
-3
@@ -96,9 +96,14 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
|
||||
|
||||
when(keysManager.takeEC(identifier, Device.PRIMARY_ID)).thenReturn(CompletableFuture.completedFuture(Optional.of(ecPreKey)));
|
||||
when(keysManager.takePQ(identifier, Device.PRIMARY_ID)).thenReturn(CompletableFuture.completedFuture(Optional.of(kemSignedPreKey)));
|
||||
when(targetDevice.getSignedPreKey(IdentityType.ACI)).thenReturn(ecSignedPreKey);
|
||||
when(keysManager.takeEC(identifier, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecPreKey)));
|
||||
|
||||
when(keysManager.takePQ(identifier, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(kemSignedPreKey)));
|
||||
|
||||
when(keysManager.getEcSignedPreKey(identifier, Device.PRIMARY_ID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(ecSignedPreKey)));
|
||||
|
||||
final GetPreKeysResponse response = unauthenticatedServiceStub().getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
|
||||
+3
-1
@@ -494,7 +494,6 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getSignedPreKey(identityType)).thenReturn(ecSignedPreKeys.get(deviceId));
|
||||
|
||||
devices.put(deviceId, device);
|
||||
when(targetAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
|
||||
@@ -505,6 +504,9 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
|
||||
ecOneTimePreKeys.forEach((deviceId, preKey) -> when(keysManager.takeEC(identifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
|
||||
|
||||
ecSignedPreKeys.forEach((deviceId, preKey) -> when(keysManager.getEcSignedPreKey(identifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
|
||||
|
||||
kemPreKeys.forEach((deviceId, preKey) -> when(keysManager.takePQ(identifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(preKey))));
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.core.ResponseInputStream;
|
||||
import software.amazon.awssdk.http.AbortableInputStream;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
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;
|
||||
|
||||
class S3ObjectMonitorTest {
|
||||
|
||||
@Test
|
||||
void refresh() {
|
||||
final S3Client s3Client = mock(S3Client.class);
|
||||
|
||||
final String bucket = "s3bucket";
|
||||
final String objectKey = "greatest-smooth-jazz-hits-of-all-time.zip";
|
||||
|
||||
//noinspection unchecked
|
||||
final Consumer<InputStream> listener = mock(Consumer.class);
|
||||
|
||||
final S3ObjectMonitor objectMonitor = new S3ObjectMonitor(
|
||||
s3Client,
|
||||
bucket,
|
||||
objectKey,
|
||||
16 * 1024 * 1024,
|
||||
mock(ScheduledExecutorService.class),
|
||||
Duration.ofMinutes(1),
|
||||
listener);
|
||||
|
||||
final String uuid = UUID.randomUUID().toString();
|
||||
when(s3Client.headObject(HeadObjectRequest.builder().bucket(bucket).key(objectKey).build())).thenReturn(
|
||||
HeadObjectResponse.builder().eTag(uuid).build());
|
||||
final ResponseInputStream<GetObjectResponse> ris = responseInputStreamFromString("abc", uuid);
|
||||
when(s3Client.getObject(GetObjectRequest.builder().bucket(bucket).key(objectKey).build())).thenReturn(ris);
|
||||
|
||||
objectMonitor.refresh();
|
||||
objectMonitor.refresh();
|
||||
|
||||
verify(listener).accept(ris);
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshAfterGet() throws IOException {
|
||||
final S3Client s3Client = mock(S3Client.class);
|
||||
|
||||
final String bucket = "s3bucket";
|
||||
final String objectKey = "greatest-smooth-jazz-hits-of-all-time.zip";
|
||||
|
||||
//noinspection unchecked
|
||||
final Consumer<InputStream> listener = mock(Consumer.class);
|
||||
|
||||
final S3ObjectMonitor objectMonitor = new S3ObjectMonitor(
|
||||
s3Client,
|
||||
bucket,
|
||||
objectKey,
|
||||
16 * 1024 * 1024,
|
||||
mock(ScheduledExecutorService.class),
|
||||
Duration.ofMinutes(1),
|
||||
listener);
|
||||
|
||||
final String uuid = UUID.randomUUID().toString();
|
||||
when(s3Client.headObject(HeadObjectRequest.builder().key(objectKey).bucket(bucket).build()))
|
||||
.thenReturn(HeadObjectResponse.builder().eTag(uuid).build());
|
||||
final ResponseInputStream<GetObjectResponse> responseInputStream = responseInputStreamFromString("abc", uuid);
|
||||
when(s3Client.getObject(GetObjectRequest.builder().key(objectKey).bucket(bucket).build())).thenReturn(responseInputStream);
|
||||
|
||||
objectMonitor.getObject();
|
||||
objectMonitor.refresh();
|
||||
|
||||
verify(listener, never()).accept(responseInputStream);
|
||||
}
|
||||
|
||||
private ResponseInputStream<GetObjectResponse> responseInputStreamFromString(final String s, final String etag) {
|
||||
final byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
|
||||
final AbortableInputStream ais = AbortableInputStream.create(new ByteArrayInputStream(bytes));
|
||||
return new ResponseInputStream<>(GetObjectResponse.builder().contentLength((long) bytes.length).eTag(etag).build(), ais);
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshOversizedObject() {
|
||||
final S3Client s3Client = mock(S3Client.class);
|
||||
|
||||
final String bucket = "s3bucket";
|
||||
final String objectKey = "greatest-smooth-jazz-hits-of-all-time.zip";
|
||||
final long maxObjectSize = 16 * 1024 * 1024;
|
||||
|
||||
//noinspection unchecked
|
||||
final Consumer<InputStream> listener = mock(Consumer.class);
|
||||
|
||||
final S3ObjectMonitor objectMonitor = new S3ObjectMonitor(
|
||||
s3Client,
|
||||
bucket,
|
||||
objectKey,
|
||||
maxObjectSize,
|
||||
mock(ScheduledExecutorService.class),
|
||||
Duration.ofMinutes(1),
|
||||
listener);
|
||||
|
||||
final String uuid = UUID.randomUUID().toString();
|
||||
when(s3Client.headObject(HeadObjectRequest.builder().bucket(bucket).key(objectKey).build())).thenReturn(
|
||||
HeadObjectResponse.builder().eTag(uuid).contentLength(maxObjectSize+1).build());
|
||||
final ResponseInputStream<GetObjectResponse> ris = responseInputStreamFromString("a".repeat((int) maxObjectSize+1), uuid);
|
||||
when(s3Client.getObject(GetObjectRequest.builder().bucket(bucket).key(objectKey).build())).thenReturn(ris);
|
||||
|
||||
objectMonitor.refresh();
|
||||
|
||||
verify(listener, never()).accept(any());
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -36,7 +36,6 @@ import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicECPreKeyMigrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
@@ -86,16 +85,14 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getEcPreKeyMigrationConfiguration())
|
||||
.thenReturn(new DynamicECPreKeyMigrationConfiguration(true, true));
|
||||
|
||||
keysManager = new KeysManager(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.EC_KEYS.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName(),
|
||||
dynamicConfigurationManager);
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()
|
||||
);
|
||||
|
||||
final Accounts accounts = new Accounts(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
|
||||
+2
-2
@@ -84,8 +84,8 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
Tables.EC_KEYS.tableName(),
|
||||
Tables.PQ_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName(),
|
||||
dynamicConfigurationManager);
|
||||
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()
|
||||
);
|
||||
|
||||
final Accounts accounts = new Accounts(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
|
||||
+45
-14
@@ -77,6 +77,7 @@ import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager.UsernameReservation;
|
||||
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
@@ -86,6 +87,7 @@ import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class AccountsManagerTest {
|
||||
@@ -193,7 +195,6 @@ class AccountsManagerTest {
|
||||
|
||||
enrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
when(enrollmentManager.isEnrolled(any(UUID.class), eq(AccountsManager.USERNAME_EXPERIMENT_NAME))).thenReturn(true);
|
||||
when(accounts.usernameHashAvailable(any())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
final AccountLockManager accountLockManager = mock(AccountLockManager.class);
|
||||
|
||||
@@ -1587,18 +1588,36 @@ class AccountsManagerTest {
|
||||
@Test
|
||||
void testReserveUsernameHash() throws UsernameHashNotAvailableException {
|
||||
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
final List<byte[]> usernameHashes = List.of(new byte[32], new byte[32]);
|
||||
when(accounts.usernameHashAvailable(any())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
when(accounts.getByAccountIdentifierAsync(account.getUuid())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
final List<byte[]> usernameHashes = List.of(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
|
||||
when(accounts.reserveUsernameHash(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
accountsManager.reserveUsernameHash(account, usernameHashes);
|
||||
verify(accounts).reserveUsernameHash(eq(account), eq(new byte[32]), eq(Duration.ofMinutes(5)));
|
||||
|
||||
UsernameReservation result = accountsManager.reserveUsernameHash(account, usernameHashes).join();
|
||||
assertArrayEquals(usernameHashes.get(0), result.reservedUsernameHash());
|
||||
verify(accounts, times(1)).reserveUsernameHash(eq(account), any(), eq(Duration.ofMinutes(5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReserveUsernameOptimisticLockingFailure() throws UsernameHashNotAvailableException {
|
||||
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
when(accounts.getByAccountIdentifierAsync(account.getUuid())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
final List<byte[]> usernameHashes = List.of(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
|
||||
when(accounts.reserveUsernameHash(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new ContestedOptimisticLockException()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
UsernameReservation result = accountsManager.reserveUsernameHash(account, usernameHashes).join();
|
||||
assertArrayEquals(usernameHashes.get(0), result.reservedUsernameHash());
|
||||
verify(accounts, times(2)).reserveUsernameHash(eq(account), any(), eq(Duration.ofMinutes(5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReserveUsernameHashNotAvailable() {
|
||||
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
when(accounts.usernameHashAvailable(any())).thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
when(accounts.getByAccountIdentifierAsync(account.getUuid())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
when(accounts.reserveUsernameHash(any(), any(), any())).thenReturn(CompletableFuture.failedFuture(new UsernameHashNotAvailableException()));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accountsManager.reserveUsernameHash(account, List.of(USERNAME_HASH_1, USERNAME_HASH_2)));
|
||||
}
|
||||
@@ -1615,8 +1634,6 @@ class AccountsManagerTest {
|
||||
void testConfirmReservedUsernameHash() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
setReservationHash(account, USERNAME_HASH_1);
|
||||
when(accounts.usernameHashAvailable(Optional.of(account.getUuid()), USERNAME_HASH_1))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
when(accounts.confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -1625,12 +1642,26 @@ class AccountsManagerTest {
|
||||
verify(accounts).confirmUsernameHash(eq(account), eq(USERNAME_HASH_1), eq(ENCRYPTED_USERNAME_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConfirmReservedUsernameHashOptimisticLockingFailure() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
setReservationHash(account, USERNAME_HASH_1);
|
||||
when(accounts.getByAccountIdentifierAsync(account.getUuid())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
when(accounts.confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1))
|
||||
.thenReturn(CompletableFuture.failedFuture(new ContestedOptimisticLockException()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1).join();
|
||||
verify(accounts, times(2)).confirmUsernameHash(eq(account), eq(USERNAME_HASH_1), eq(ENCRYPTED_USERNAME_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConfirmReservedHashNameMismatch() {
|
||||
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
setReservationHash(account, USERNAME_HASH_1);
|
||||
when(accounts.usernameHashAvailable(eq(Optional.of(account.getUuid())), eq(USERNAME_HASH_1)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
when(accounts.confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameReservationNotFoundException.class,
|
||||
accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_2, ENCRYPTED_USERNAME_2));
|
||||
}
|
||||
@@ -1640,11 +1671,11 @@ class AccountsManagerTest {
|
||||
final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
// hash was reserved, but the reservation lapsed and another account took it
|
||||
setReservationHash(account, USERNAME_HASH_1);
|
||||
when(accounts.usernameHashAvailable(eq(Optional.of(account.getUuid())), eq(USERNAME_HASH_1)))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
when(accounts.confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1))
|
||||
.thenReturn(CompletableFuture.failedFuture(new UsernameHashNotAvailableException()));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accountsManager.confirmReservedUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
|
||||
verify(accounts, never()).confirmUsernameHash(any(), any(), any());
|
||||
assertTrue(account.getUsernameHash().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-13
@@ -100,8 +100,8 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
Tables.EC_KEYS.tableName(),
|
||||
Tables.PQ_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName(),
|
||||
dynamicConfigurationManager);
|
||||
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()
|
||||
);
|
||||
|
||||
accounts = Mockito.spy(new Accounts(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
@@ -182,7 +182,7 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReserveUsernameSnatched() throws InterruptedException, UsernameHashNotAvailableException {
|
||||
void testReserveUsernameGetFirstAvailableChoice() throws InterruptedException, UsernameHashNotAvailableException {
|
||||
final Account account = AccountsHelper.createAccount(accountsManager, "+18005551111");
|
||||
|
||||
ArrayList<byte[]> usernameHashes = new ArrayList<>(Arrays.asList(USERNAME_HASH_1, USERNAME_HASH_2));
|
||||
@@ -198,23 +198,14 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
|
||||
byte[] availableHash = TestRandomUtil.nextBytes(32);
|
||||
usernameHashes.add(availableHash);
|
||||
usernameHashes.add(TestRandomUtil.nextBytes(32));
|
||||
|
||||
// first time this is called lie and say the username is available
|
||||
// this simulates seeing an available username and then it being taken
|
||||
// by someone before the write
|
||||
doReturn(CompletableFuture.completedFuture(true))
|
||||
.doCallRealMethod()
|
||||
.when(accounts).usernameHashAvailable(any());
|
||||
final byte[] username = accountsManager
|
||||
.reserveUsernameHash(account, usernameHashes)
|
||||
.join()
|
||||
.reservedUsernameHash();
|
||||
|
||||
assertArrayEquals(username, availableHash);
|
||||
|
||||
// 1 attempt on first try (returns true),
|
||||
// 5 more attempts until "availableHash" returns true
|
||||
verify(accounts, times(4)).usernameHashAvailable(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -910,12 +910,7 @@ class AccountsTest {
|
||||
final UUID newHandle = account.getUsernameLinkHandle();
|
||||
|
||||
assertThat(accounts.getByUsernameHash(USERNAME_HASH_1).join()).isEmpty();
|
||||
assertThat(DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(Tables.USERNAMES.tableName())
|
||||
.key(Map.of(Accounts.ATTR_USERNAME_HASH, AttributeValues.fromByteArray(USERNAME_HASH_1)))
|
||||
.build())
|
||||
.item()).isEmpty();
|
||||
assertThat(getUsernameConstraintTableItem(USERNAME_HASH_1)).isEmpty();
|
||||
assertThat(accounts.getByUsernameLinkHandle(oldHandle).join()).isEmpty();
|
||||
|
||||
{
|
||||
@@ -950,15 +945,15 @@ class AccountsTest {
|
||||
verifyStoredState(firstAccount.getNumber(), firstAccount.getUuid(), firstAccount.getPhoneNumberIdentifier(), USERNAME_HASH_1, maybeAccount.get(), firstAccount);
|
||||
|
||||
// throw an error if second account tries to reserve or confirm the same username hash
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.reserveUsernameHash(secondAccount, USERNAME_HASH_1, Duration.ofDays(1)));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.confirmUsernameHash(secondAccount, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
|
||||
|
||||
// throw an error if first account tries to reserve or confirm the username hash that it has already confirmed
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.reserveUsernameHash(firstAccount, USERNAME_HASH_1, Duration.ofDays(1)));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.confirmUsernameHash(firstAccount, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
|
||||
|
||||
assertThat(secondAccount.getReservedUsernameHash()).isEmpty();
|
||||
@@ -1034,9 +1029,9 @@ class AccountsTest {
|
||||
assertThat(account1.getUsernameHash()).isEmpty();
|
||||
|
||||
// account 2 shouldn't be able to reserve or confirm the same username hash
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.reserveUsernameHash(account2, USERNAME_HASH_1, Duration.ofDays(1)));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.confirmUsernameHash(account2, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
|
||||
assertThat(accounts.getByUsernameHash(USERNAME_HASH_1).join()).isEmpty();
|
||||
|
||||
@@ -1045,33 +1040,67 @@ class AccountsTest {
|
||||
assertArrayEquals(account1.getUsernameHash().orElseThrow(), USERNAME_HASH_1);
|
||||
assertThat(accounts.getByUsernameHash(USERNAME_HASH_1).join().get().getUuid()).isEqualTo(account1.getUuid());
|
||||
|
||||
final Map<String, AttributeValue> usernameConstraintRecord = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(Tables.USERNAMES.tableName())
|
||||
.key(Map.of(Accounts.ATTR_USERNAME_HASH, AttributeValues.fromByteArray(USERNAME_HASH_1)))
|
||||
.build())
|
||||
.item();
|
||||
final Map<String, AttributeValue> usernameConstraintRecord = getUsernameConstraintTableItem(USERNAME_HASH_1);
|
||||
|
||||
assertThat(usernameConstraintRecord).containsKey(Accounts.ATTR_USERNAME_HASH);
|
||||
assertThat(usernameConstraintRecord).doesNotContainKey(Accounts.ATTR_TTL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUsernameHashAvailable() {
|
||||
final Account account1 = generateAccount("+18005551111", UUID.randomUUID(), UUID.randomUUID());
|
||||
createAccount(account1);
|
||||
void switchBetweenReservedUsernameHashes() {
|
||||
final Account account = generateAccount("+18005551111", UUID.randomUUID(), UUID.randomUUID());
|
||||
createAccount(account);
|
||||
|
||||
accounts.reserveUsernameHash(account1, USERNAME_HASH_1, Duration.ofDays(1)).join();
|
||||
assertThat(accounts.usernameHashAvailable(USERNAME_HASH_1).join()).isFalse();
|
||||
assertThat(accounts.usernameHashAvailable(Optional.empty(), USERNAME_HASH_1).join()).isFalse();
|
||||
assertThat(accounts.usernameHashAvailable(Optional.of(UUID.randomUUID()), USERNAME_HASH_1).join()).isFalse();
|
||||
assertThat(accounts.usernameHashAvailable(Optional.of(account1.getUuid()), USERNAME_HASH_1).join()).isTrue();
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(1)).join();
|
||||
assertArrayEquals(account.getReservedUsernameHash().orElseThrow(), USERNAME_HASH_1);
|
||||
assertThat(account.getUsernameHash()).isEmpty();
|
||||
|
||||
accounts.confirmUsernameHash(account1, USERNAME_HASH_1, ENCRYPTED_USERNAME_1).join();
|
||||
assertThat(accounts.usernameHashAvailable(USERNAME_HASH_1).join()).isFalse();
|
||||
assertThat(accounts.usernameHashAvailable(Optional.empty(), USERNAME_HASH_1).join()).isFalse();
|
||||
assertThat(accounts.usernameHashAvailable(Optional.of(UUID.randomUUID()), USERNAME_HASH_1).join()).isFalse();
|
||||
assertThat(accounts.usernameHashAvailable(Optional.of(account1.getUuid()), USERNAME_HASH_1).join()).isFalse();
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_2, Duration.ofDays(1)).join();
|
||||
assertArrayEquals(account.getReservedUsernameHash().orElseThrow(), USERNAME_HASH_2);
|
||||
assertThat(account.getUsernameHash()).isEmpty();
|
||||
|
||||
final Map<String, AttributeValue> usernameConstraintRecord1 = getUsernameConstraintTableItem(USERNAME_HASH_1);
|
||||
final Map<String, AttributeValue> usernameConstraintRecord2 = getUsernameConstraintTableItem(USERNAME_HASH_2);
|
||||
assertThat(usernameConstraintRecord1).containsKey(Accounts.ATTR_USERNAME_HASH);
|
||||
assertThat(usernameConstraintRecord2).containsKey(Accounts.ATTR_USERNAME_HASH);
|
||||
assertThat(usernameConstraintRecord1).containsKey(Accounts.ATTR_TTL);
|
||||
assertThat(usernameConstraintRecord2).containsKey(Accounts.ATTR_TTL);
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofMinutes(1)));
|
||||
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(1)).join();
|
||||
assertArrayEquals(account.getReservedUsernameHash().orElseThrow(), USERNAME_HASH_1);
|
||||
assertThat(account.getUsernameHash()).isEmpty();
|
||||
|
||||
final Map<String, AttributeValue> newUsernameConstraintRecord1 = getUsernameConstraintTableItem(USERNAME_HASH_1);
|
||||
assertThat(newUsernameConstraintRecord1).containsKey(Accounts.ATTR_USERNAME_HASH);
|
||||
assertThat(newUsernameConstraintRecord1).containsKey(Accounts.ATTR_TTL);
|
||||
assertThat(usernameConstraintRecord1.get(Accounts.ATTR_TTL))
|
||||
.isNotEqualTo(newUsernameConstraintRecord1.get(Accounts.ATTR_TTL));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reserveOwnConfirmedUsername() {
|
||||
final Account account = generateAccount("+18005551111", UUID.randomUUID(), UUID.randomUUID());
|
||||
createAccount(account);
|
||||
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(1)).join();
|
||||
assertArrayEquals(account.getReservedUsernameHash().orElseThrow(), USERNAME_HASH_1);
|
||||
assertThat(account.getUsernameHash()).isEmpty();
|
||||
assertThat(getUsernameConstraintTableItem(USERNAME_HASH_1)).containsKey(Accounts.ATTR_TTL);
|
||||
|
||||
|
||||
accounts.confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1).join();
|
||||
assertThat(account.getReservedUsernameHash()).isEmpty();
|
||||
assertArrayEquals(account.getUsernameHash().orElseThrow(), USERNAME_HASH_1);
|
||||
assertThat(getUsernameConstraintTableItem(USERNAME_HASH_1)).doesNotContainKey(Accounts.ATTR_TTL);
|
||||
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(1)));
|
||||
assertThat(account.getReservedUsernameHash()).isEmpty();
|
||||
assertArrayEquals(account.getUsernameHash().orElseThrow(), USERNAME_HASH_1);
|
||||
assertThat(getUsernameConstraintTableItem(USERNAME_HASH_1)).containsKey(Accounts.ATTR_USERNAME_HASH);
|
||||
assertThat(getUsernameConstraintTableItem(USERNAME_HASH_1)).doesNotContainKey(Accounts.ATTR_TTL);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1086,7 +1115,7 @@ class AccountsTest {
|
||||
assertThat(account1.getUsernameHash()).isEmpty();
|
||||
|
||||
// only account1 should be able to confirm the reserved hash
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.confirmUsernameHash(account2, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
|
||||
}
|
||||
|
||||
@@ -1101,7 +1130,7 @@ class AccountsTest {
|
||||
|
||||
for (int i = 0; i <= 2; i++) {
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(i)));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.reserveUsernameHash(account2, USERNAME_HASH_1, Duration.ofDays(1)));
|
||||
}
|
||||
|
||||
@@ -1112,24 +1141,13 @@ class AccountsTest {
|
||||
|
||||
accounts.confirmUsernameHash(account2, USERNAME_HASH_1, ENCRYPTED_USERNAME_1).join();
|
||||
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.reserveUsernameHash(account1, USERNAME_HASH_1, Duration.ofDays(2)));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
CompletableFutureTestUtil.assertFailsWithCause(UsernameHashNotAvailableException.class,
|
||||
accounts.confirmUsernameHash(account1, USERNAME_HASH_1, ENCRYPTED_USERNAME_1));
|
||||
assertThat(accounts.getByUsernameHash(USERNAME_HASH_1).join().get().getUuid()).isEqualTo(account2.getUuid());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetryReserveUsernameHash() {
|
||||
final Account account = generateAccount("+18005551111", UUID.randomUUID(), UUID.randomUUID());
|
||||
createAccount(account);
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(2)).join();
|
||||
|
||||
CompletableFutureTestUtil.assertFailsWithCause(ContestedOptimisticLockException.class,
|
||||
accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(2)),
|
||||
"Shouldn't be able to re-reserve same username hash (would extend ttl)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReserveConfirmUsernameHashVersionConflict() {
|
||||
final Account account = generateAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID());
|
||||
@@ -1300,6 +1318,15 @@ class AccountsTest {
|
||||
return get.item();
|
||||
}
|
||||
|
||||
private Map<String, AttributeValue> getUsernameConstraintTableItem(final byte[] usernameHash) {
|
||||
return DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(Tables.USERNAMES.tableName())
|
||||
.key(Map.of(Accounts.ATTR_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash)))
|
||||
.build())
|
||||
.item();
|
||||
}
|
||||
|
||||
private void verifyStoredState(String number, UUID uuid, UUID pni, byte[] usernameHash, Account expecting, boolean canonicallyDiscoverable) {
|
||||
final DynamoDbClient db = DYNAMO_DB_EXTENSION.getDynamoDbClient();
|
||||
|
||||
|
||||
+2
-5
@@ -28,7 +28,6 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicECPreKeyMigrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
@@ -74,16 +73,14 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getEcPreKeyMigrationConfiguration())
|
||||
.thenReturn(new DynamicECPreKeyMigrationConfiguration(true, true));
|
||||
|
||||
keysManager = new KeysManager(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.EC_KEYS.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.PQ_KEYS.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName(),
|
||||
dynamicConfigurationManager);
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()
|
||||
);
|
||||
|
||||
final Accounts accounts = new Accounts(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
|
||||
-12
@@ -57,18 +57,6 @@ public final class DynamoDbExtensionSchema {
|
||||
.attributeType(ScalarAttributeType.B).build()),
|
||||
Collections.emptyList(), Collections.emptyList()),
|
||||
|
||||
BACKUP_MEDIA("backups_media_test",
|
||||
BackupsDb.KEY_BACKUP_ID_HASH,
|
||||
BackupsDb.KEY_MEDIA_ID,
|
||||
List.of(
|
||||
AttributeDefinition.builder()
|
||||
.attributeName(BackupsDb.KEY_BACKUP_ID_HASH)
|
||||
.attributeType(ScalarAttributeType.B).build(),
|
||||
AttributeDefinition.builder()
|
||||
.attributeName(BackupsDb.KEY_MEDIA_ID)
|
||||
.attributeType(ScalarAttributeType.B).build()),
|
||||
Collections.emptyList(), Collections.emptyList()),
|
||||
|
||||
CLIENT_RELEASES("client_releases_test",
|
||||
ClientReleases.ATTR_PLATFORM,
|
||||
ClientReleases.ATTR_VERSION,
|
||||
|
||||
+2
-34
@@ -9,8 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -20,12 +18,8 @@ import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicECPreKeyMigrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
@@ -34,7 +28,6 @@ import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
|
||||
class KeysManagerTest {
|
||||
|
||||
private DynamicECPreKeyMigrationConfiguration ecPreKeyMigrationConfiguration;
|
||||
private KeysManager keysManager;
|
||||
|
||||
@RegisterExtension
|
||||
@@ -48,22 +41,13 @@ class KeysManagerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
ecPreKeyMigrationConfiguration = mock(DynamicECPreKeyMigrationConfiguration.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getEcPreKeyMigrationConfiguration()).thenReturn(ecPreKeyMigrationConfiguration);
|
||||
when(ecPreKeyMigrationConfiguration.storeEcSignedPreKeys()).thenReturn(true);
|
||||
when(ecPreKeyMigrationConfiguration.deleteEcSignedPreKeys()).thenReturn(true);
|
||||
|
||||
keysManager = new KeysManager(
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
Tables.EC_KEYS.tableName(),
|
||||
Tables.PQ_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName(),
|
||||
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName(),
|
||||
dynamicConfigurationManager);
|
||||
Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -239,22 +223,6 @@ class KeysManagerTest {
|
||||
Set.copyOf(keysManager.getPqEnabledDevices(ACCOUNT_UUID).join()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStoreEcSignedPreKeyDisabled() {
|
||||
when(ecPreKeyMigrationConfiguration.storeEcSignedPreKeys()).thenReturn(false);
|
||||
|
||||
keysManager.storeEcSignedPreKeys(ACCOUNT_UUID, DEVICE_ID, generateTestECSignedPreKey(1)).join();
|
||||
assertFalse(keysManager.getEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID).join().isPresent());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void buildWriteItemForEcSignedPreKey(final boolean enableSignedPreKeyWrite) {
|
||||
when(ecPreKeyMigrationConfiguration.storeEcSignedPreKeys()).thenReturn(enableSignedPreKeyWrite);
|
||||
assertEquals(enableSignedPreKeyWrite,
|
||||
keysManager.buildWriteItemForEcSignedPreKey(ACCOUNT_UUID, DEVICE_ID, generateTestECSignedPreKey(1)).isPresent());
|
||||
}
|
||||
|
||||
private static ECPreKey generateTestPreKey(final long keyId) {
|
||||
return new ECPreKey(keyId, Curve.generateKeyPair().getPublicKey());
|
||||
}
|
||||
|
||||
-24
@@ -5,14 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
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.Curve;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
@@ -52,21 +45,4 @@ class RepeatedUseECSignedPreKeyStoreTest extends RepeatedUseSignedPreKeyStoreTes
|
||||
protected DynamoDbClient getDynamoDbClient() {
|
||||
return DYNAMO_DB_EXTENSION.getDynamoDbClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
void storeIfAbsent() {
|
||||
final UUID identifier = UUID.randomUUID();
|
||||
final byte deviceIdWithExistingKey = 1;
|
||||
final byte deviceIdWithoutExistingKey = deviceIdWithExistingKey + 1;
|
||||
|
||||
final ECSignedPreKey originalSignedPreKey = generateSignedPreKey();
|
||||
|
||||
keyStore.store(identifier, deviceIdWithExistingKey, originalSignedPreKey).join();
|
||||
|
||||
assertFalse(keyStore.storeIfAbsent(identifier, deviceIdWithExistingKey, generateSignedPreKey()).join());
|
||||
assertTrue(keyStore.storeIfAbsent(identifier, deviceIdWithoutExistingKey, generateSignedPreKey()).join());
|
||||
|
||||
assertEquals(Optional.of(originalSignedPreKey), keyStore.find(identifier, deviceIdWithExistingKey).join());
|
||||
assertTrue(keyStore.find(identifier, deviceIdWithoutExistingKey).join().isPresent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpUtilsTest {
|
||||
|
||||
@Test
|
||||
public void queryParameterStringPreservesOrder() {
|
||||
final String result = HttpUtils.queryParamString(List.of(
|
||||
Map.entry("a", "aval"),
|
||||
Map.entry("b", "bval1"),
|
||||
Map.entry("b", "bval2")
|
||||
));
|
||||
// https://url.spec.whatwg.org/#example-constructing-urlsearchparams allows multiple parameters with the same key
|
||||
// https://url.spec.whatwg.org/#example-searchparams-sort implies that the relative order of values for parameters
|
||||
// with the same key must be preserved
|
||||
assertThat(result).isEqualTo("?a=aval&b=bval1&b=bval2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryParameterStringEncodesUnsafeChars() {
|
||||
final String result = HttpUtils.queryParamString(List.of(Map.entry("&k?e=y/!", "=v/a?l&u;e")));
|
||||
assertThat(result).isEqualTo("?%26k%3Fe%3Dy%2F%21=%3Dv%2Fa%3Fl%26u%3Be");
|
||||
}
|
||||
}
|
||||
+1
-12
@@ -9,15 +9,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.micrometer.shaded.reactor.util.function.Tuple2;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
class RemoveExpiredLinkedDevicesCommandTest {
|
||||
@@ -52,14 +49,6 @@ class RemoveExpiredLinkedDevicesCommandTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getDeviceIdsToRemove(final List<Device> devices, final Set<Byte> expectedIds) {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getDevices()).thenReturn(devices);
|
||||
|
||||
final Set<Byte> actualIds = RemoveExpiredLinkedDevicesCommand.getExpiredLinkedDeviceIds(account)
|
||||
.stream()
|
||||
.map(Tuple2::getT2)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
assertEquals(expectedIds, actualIds);
|
||||
assertEquals(expectedIds, RemoveExpiredLinkedDevicesCommand.getExpiredLinkedDeviceIds(devices));
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule spam-filter updated: 9419c2c07a...e6aa9f4311.
Reference in new issue
Block a user