mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 09:26:47 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cd446ee31 | ||
|
|
1847c6d4ca | ||
|
|
1770558d5e | ||
|
|
e0d39212ec | ||
|
|
31ebe9071a | ||
|
|
8f65486fab | ||
|
|
7e3540bda0 | ||
|
|
c544628dfe | ||
|
|
61b162d0a1 | ||
|
|
8c2d738924 | ||
|
|
efde8a31f9 | ||
|
|
b2dd315177 | ||
|
|
dc3920a99c | ||
|
|
b8e8fd3313 | ||
|
|
a5423b6e21 | ||
|
|
89b37015c6 | ||
|
|
2af3088571 |
No files matched your search
@@ -13,11 +13,16 @@ jobs:
|
||||
timeout-minutes: 20
|
||||
|
||||
services:
|
||||
foundationdb:
|
||||
foundationdb0:
|
||||
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
|
||||
# it's a little behind the CLIENT version.
|
||||
image: foundationdb/foundationdb:7.3.62
|
||||
options: --name foundationdb
|
||||
options: --name foundationdb0
|
||||
foundationdb1:
|
||||
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
|
||||
# it's a little behind the CLIENT version.
|
||||
image: foundationdb/foundationdb:7.3.62
|
||||
options: --name foundationdb1
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
@@ -49,12 +54,14 @@ jobs:
|
||||
|
||||
# ca-certificates: required for AWS CRT client
|
||||
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
|
||||
- name: Configure FoundationDB database
|
||||
run: docker exec foundationdb /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Configure FoundationDB0 database
|
||||
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Configure FoundationDB1 database
|
||||
run: docker exec foundationdb1 /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Download and install FoundationDB client
|
||||
run: |
|
||||
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
|
||||
cp service/target/jib-extra/usr/lib/libfdb_c.x86_64.so /usr/lib/libfdb_c.x86_64.so
|
||||
ldconfig
|
||||
- name: Build with Maven
|
||||
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerName=foundationdb
|
||||
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
|
||||
@@ -445,6 +445,12 @@
|
||||
<artifactId>netty-codec-haproxy</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-transport-native-epoll</artifactId>
|
||||
<classifier>linux-x86_64</classifier>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-core</artifactId>
|
||||
|
||||
@@ -273,6 +273,7 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
@@ -342,6 +343,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new BackupUsageRecalculationCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
@@ -806,7 +808,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
cdn3RemoteStorageManager,
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
dynamoDbClient,
|
||||
|
||||
@@ -11,6 +11,8 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -31,6 +33,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -134,6 +137,32 @@ public class BackupAuthManager {
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public record BackupIdRotationLimit(boolean hasPermitsRemaining, Duration nextPermitAvailable) {}
|
||||
|
||||
public CompletionStage<BackupIdRotationLimit> checkBackupIdRotationLimit(final Account account) {
|
||||
final RateLimiter messagesLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID);
|
||||
final RateLimiter mediaLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID);
|
||||
|
||||
final boolean isPaid = hasActiveVoucher(account);
|
||||
|
||||
final CompletionStage<Boolean> hasSetMessagesPermits =
|
||||
messagesLimiter.hasAvailablePermitsAsync(account.getUuid(), 1);
|
||||
final CompletionStage<Boolean> hasSetMediaPermits = isPaid
|
||||
? mediaLimiter.hasAvailablePermitsAsync(account.getUuid(), 1)
|
||||
: CompletableFuture.completedFuture(true);
|
||||
|
||||
return hasSetMessagesPermits.thenCombine(hasSetMediaPermits, (hasMessage, hasMedia) -> {
|
||||
if (hasMedia && hasMessage) {
|
||||
return new BackupIdRotationLimit(true, Duration.ZERO);
|
||||
} else {
|
||||
final Duration timeToNextPermit = Collections.max(Arrays.asList(
|
||||
messagesLimiter.config().permitRegenerationDuration(),
|
||||
isPaid ? mediaLimiter.config().permitRegenerationDuration() : Duration.ZERO));
|
||||
return new BackupIdRotationLimit(false, timeToNextPermit);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public record Credential(BackupAuthCredentialResponse credential, Instant redemptionTime) {}
|
||||
|
||||
/**
|
||||
|
||||
@@ -40,10 +40,13 @@ import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -61,20 +64,6 @@ public class BackupManager {
|
||||
public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
|
||||
// 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);
|
||||
|
||||
// How many cdn object deletion requests can be outstanding at a time per backup deletion operation
|
||||
private static final int DELETION_CONCURRENCY = 10;
|
||||
|
||||
// How many cdn object copy requests can be outstanding at a time per batch copy-to-backup operation
|
||||
private static final int COPY_CONCURRENCY = 10;
|
||||
|
||||
// How often we should persist the current usage
|
||||
@VisibleForTesting
|
||||
static int USAGE_CHECKPOINT_COUNT = 10;
|
||||
|
||||
|
||||
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");
|
||||
@@ -100,6 +89,7 @@ public class BackupManager {
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
|
||||
private final SecureValueRecoveryClient secureValueRecoveryBClient;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public BackupManager(
|
||||
final BackupsDb backupsDb,
|
||||
@@ -110,7 +100,8 @@ public class BackupManager {
|
||||
final RemoteStorageManager remoteStorageManager,
|
||||
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
|
||||
final SecureValueRecoveryClient secureValueRecoveryBClient,
|
||||
final Clock clock) {
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.backupsDb = backupsDb;
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -120,6 +111,7 @@ public class BackupManager {
|
||||
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
|
||||
this.clock = clock;
|
||||
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
|
||||
@@ -238,6 +230,9 @@ public class BackupManager {
|
||||
checkBackupLevel(backupUser, BackupLevel.PAID);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Mono.fromFuture(() -> allowedCopies(backupUser, toCopy))
|
||||
.flatMapMany(quotaResult -> Flux.concat(
|
||||
|
||||
@@ -247,7 +242,7 @@ public class BackupManager {
|
||||
Flux.fromIterable(quotaResult.requestsToCopy())
|
||||
|
||||
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
|
||||
.buffer(USAGE_CHECKPOINT_COUNT)
|
||||
.buffer(backupConfiguration.usageCheckpointCount())
|
||||
.concatMap(copyParameters -> {
|
||||
final long quotaToConsume = copyParameters.stream()
|
||||
.mapToLong(CopyParameters::destinationObjectSize)
|
||||
@@ -265,7 +260,7 @@ public class BackupManager {
|
||||
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
|
||||
.thenReturn(copyResult);
|
||||
}),
|
||||
COPY_CONCURRENCY, 1),
|
||||
backupConfiguration.copyConcurrency(), 1),
|
||||
|
||||
// There wasn't enough quota remaining to perform these copies
|
||||
Flux.fromIterable(quotaResult.requestsToReject())
|
||||
@@ -317,11 +312,14 @@ public class BackupManager {
|
||||
})
|
||||
.sum();
|
||||
|
||||
final Duration maxQuotaStaleness =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxQuotaStaleness();
|
||||
|
||||
return backupsDb.getMediaUsage(backupUser)
|
||||
.thenComposeAsync(info -> {
|
||||
long remainingQuota = MAX_TOTAL_BACKUP_MEDIA_BYTES - info.usageInfo().bytesUsed();
|
||||
final boolean canStore = remainingQuota >= totalBytesAdded;
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(MAX_QUOTA_STALENESS))) {
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
|
||||
return CompletableFuture.completedFuture(remainingQuota);
|
||||
}
|
||||
|
||||
@@ -456,6 +454,9 @@ public class BackupManager {
|
||||
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
|
||||
final int deletionConcurrency =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
|
||||
|
||||
// Clients only include SVRB data with their messages backup-id
|
||||
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
|
||||
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
|
||||
@@ -467,7 +468,7 @@ public class BackupManager {
|
||||
// If there was already a pending swap, try to delete the cdn objects directly
|
||||
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
|
||||
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
|
||||
deletePrefix(backupUser.backupDir(), DELETION_CONCURRENCY)))));
|
||||
deletePrefix(backupUser.backupDir(), deletionConcurrency)))));
|
||||
}
|
||||
|
||||
|
||||
@@ -482,11 +483,13 @@ public class BackupManager {
|
||||
.withDescription("unsupported media cdn provided")
|
||||
.asRuntimeException();
|
||||
}
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Flux.usingWhen(
|
||||
|
||||
// Gather usage updates into the UsageBatcher so we don't have to update our backup record on every delete
|
||||
Mono.just(new UsageBatcher()),
|
||||
Mono.just(new UsageBatcher(backupConfiguration.usageCheckpointCount())),
|
||||
|
||||
// Deletes the objects, returning their former location. Tracks bytes removed so the quota can be updated on
|
||||
// completion
|
||||
@@ -495,7 +498,7 @@ public class BackupManager {
|
||||
// Delete the objects, allowing DELETION_CONCURRENCY operations out at a time
|
||||
.flatMapSequential(
|
||||
sd -> Mono.fromCompletionStage(remoteStorageManager.delete(cdnMediaPath(backupUser, sd.key()))),
|
||||
DELETION_CONCURRENCY)
|
||||
backupConfiguration.deletionConcurrency())
|
||||
.zipWithIterable(storageDescriptors)
|
||||
|
||||
// Track how much the remote storage manager indicated was deleted as part of the operation
|
||||
@@ -531,9 +534,14 @@ public class BackupManager {
|
||||
*/
|
||||
private static class UsageBatcher {
|
||||
|
||||
private final int usageCheckpointCount;
|
||||
private long runningCountDelta = 0;
|
||||
private long runningBytesDelta = 0;
|
||||
|
||||
UsageBatcher(int usageCheckpointCount) {
|
||||
this.usageCheckpointCount = usageCheckpointCount;
|
||||
}
|
||||
|
||||
record UsageUpdate(long countDelta, long bytesDelta) {}
|
||||
|
||||
/**
|
||||
@@ -546,7 +554,7 @@ public class BackupManager {
|
||||
boolean update(long bytesDelta) {
|
||||
this.runningCountDelta += Long.signum(bytesDelta);
|
||||
this.runningBytesDelta += bytesDelta;
|
||||
return Math.abs(runningCountDelta) >= USAGE_CHECKPOINT_COUNT;
|
||||
return Math.abs(runningCountDelta) >= usageCheckpointCount;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -622,11 +630,10 @@ public class BackupManager {
|
||||
* List all backups stored in the backups table
|
||||
*
|
||||
* @param segments Number of segments to read in parallel from the underlying backup database
|
||||
* @param scheduler Scheduler for running downstream operations
|
||||
* @return Flux of {@link StoredBackupAttributes} for each backup record in the backups table
|
||||
*/
|
||||
public Flux<StoredBackupAttributes> listBackupAttributes(final int segments, final Scheduler scheduler) {
|
||||
return this.backupsDb.listBackupAttributes(segments, scheduler);
|
||||
public Flux<StoredBackupAttributes> listBackupAttributes(final int segments) {
|
||||
return this.backupsDb.listBackupAttributes(segments);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -254,8 +254,7 @@ public class BackupsDb {
|
||||
.updateItemBuilder()
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build())
|
||||
.thenAccept(updateItemResponse ->
|
||||
updateMetricsAfterRefresh(backupUser, today, updateItemResponse.attributes()));
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,10 +273,10 @@ public class BackupsDb {
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build())
|
||||
.thenAccept(updateItemResponse ->
|
||||
updateMetricsAfterRefresh(backupUser, today, updateItemResponse.attributes()));
|
||||
updateMetricsAfterUpload(backupUser, today, updateItemResponse.attributes()));
|
||||
}
|
||||
|
||||
private void updateMetricsAfterRefresh(final AuthenticatedBackupUser backupUser, final Instant today, final Map<String, AttributeValue> item) {
|
||||
private void updateMetricsAfterUpload(final AuthenticatedBackupUser backupUser, final Instant today, final Map<String, AttributeValue> item) {
|
||||
final Instant previousRefreshTime = Instant.ofEpochSecond(
|
||||
AttributeValues.getLong(item, ATTR_LAST_REFRESH, 0L));
|
||||
// Only publish a metric update once per day
|
||||
@@ -497,14 +496,12 @@ public class BackupsDb {
|
||||
}
|
||||
}
|
||||
|
||||
Flux<StoredBackupAttributes> listBackupAttributes(final int segments, final Scheduler scheduler) {
|
||||
Flux<StoredBackupAttributes> listBackupAttributes(final int segments) {
|
||||
if (segments < 1) {
|
||||
throw new IllegalArgumentException("Total number of segments must be positive");
|
||||
}
|
||||
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> dynamoClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(backupTableName)
|
||||
.consistentRead(true)
|
||||
@@ -519,9 +516,9 @@ public class BackupsDb {
|
||||
"#backupDir", ATTR_BACKUP_DIR,
|
||||
"#mediaDir", ATTR_MEDIA_DIR))
|
||||
.projectionExpression("#backupIdHash, #refresh, #mediaRefresh, #bytesUsed, #numObjects, #backupDir, #mediaDir")
|
||||
.build())
|
||||
.items())
|
||||
.sequential()
|
||||
.build()))
|
||||
// Don't use the SDK's item publisher, works around https://github.com/aws/aws-sdk-java-v2/issues/6411
|
||||
.concatMap(page -> Flux.fromIterable(page.items()))
|
||||
.filter(item -> item.containsKey(KEY_BACKUP_ID_HASH))
|
||||
.map(item -> new StoredBackupAttributes(
|
||||
AttributeValues.getByteArray(item, KEY_BACKUP_ID_HASH, null),
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param deletionConcurrency How many cdn object deletion requests can be outstanding at a time per backup deletion operation
|
||||
* @param copyConcurrency How many cdn object copy requests can be outstanding at a time per batch copy-to-backup operation
|
||||
* @param usageCheckpointCount When doing batch operations, how often persist usage deltas
|
||||
* @param maxQuotaStaleness The maximum age of a quota estimate that can be used to enforce a quota limit
|
||||
*/
|
||||
public record DynamicBackupConfiguration(
|
||||
Integer deletionConcurrency,
|
||||
Integer copyConcurrency,
|
||||
Integer usageCheckpointCount,
|
||||
Duration maxQuotaStaleness) {
|
||||
|
||||
public DynamicBackupConfiguration {
|
||||
if (deletionConcurrency == null) {
|
||||
deletionConcurrency = 10;
|
||||
}
|
||||
if (copyConcurrency == null) {
|
||||
copyConcurrency = 10;
|
||||
}
|
||||
if (usageCheckpointCount == null) {
|
||||
usageCheckpointCount = 10;
|
||||
}
|
||||
if (maxQuotaStaleness == null) {
|
||||
maxQuotaStaleness = Duration.ofSeconds(10);
|
||||
}
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration() {
|
||||
this(null, null, null, null);
|
||||
}
|
||||
}
|
||||
+7
@@ -64,6 +64,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicRestDeprecationConfiguration restDeprecation = new DynamicRestDeprecationConfiguration(Map.of());
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -114,4 +118,7 @@ public class DynamicConfiguration {
|
||||
return restDeprecation;
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
}
|
||||
+28
@@ -163,6 +163,34 @@ public class ArchiveController {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public record BackupIdLimitResponse(
|
||||
@Schema(description = "If true, a call to PUT /v1/archive/backupid may succeed without waiting")
|
||||
boolean hasPermitsRemaining,
|
||||
@Schema(description = "How long to wait before a permit becomes available, in seconds")
|
||||
long retryAfterSeconds) {}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/backupid/limits")
|
||||
@Operation(
|
||||
summary = "Retrieve limits",
|
||||
description = """
|
||||
Determine whether the backup-id can currently be rotated
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved backup-id rotation limits", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "Invalid account authentication")
|
||||
public CompletionStage<BackupIdLimitResponse> checkLimits(@Auth final AuthenticatedDevice authenticatedDevice) {
|
||||
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
return backupAuthManager.checkBackupIdRotationLimit(account).thenApply(limit ->
|
||||
new BackupIdLimitResponse(limit.hasPermitsRemaining(), limit.nextPermitAvailable().getSeconds()));
|
||||
});
|
||||
}
|
||||
|
||||
public record RedeemBackupReceiptRequest(
|
||||
@Schema(description = "Presentation of a ZK receipt encoded in standard padded base64", implementation = String.class)
|
||||
@JsonDeserialize(using = Deserializer.class)
|
||||
|
||||
+10
-6
@@ -72,7 +72,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
@@ -86,6 +86,10 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -415,19 +419,19 @@ public class SubscriptionController {
|
||||
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level,
|
||||
currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType);
|
||||
return new SetSubscriptionLevelSuccessResponse(level);
|
||||
} catch (SubscriptionException.InvalidLevel e) {
|
||||
} catch (SubscriptionInvalidLevelException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of(
|
||||
new SubscriptionController.SetSubscriptionLevelErrorResponse.Error(
|
||||
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL,
|
||||
null))))
|
||||
.build());
|
||||
} catch (SubscriptionException.PaymentRequiresAction e) {
|
||||
} catch (SubscriptionPaymentRequiresActionException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
|
||||
.build());
|
||||
} catch (SubscriptionException.InvalidArguments e) {
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
|
||||
@@ -768,7 +772,7 @@ public class SubscriptionController {
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
|
||||
} catch (SubscriptionException.ReceiptRequestedForOpenPayment e) {
|
||||
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -802,7 +806,7 @@ public class SubscriptionController {
|
||||
|
||||
manager
|
||||
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
|
||||
} catch (SubscriptionException.InvalidArguments e) {
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
throw new ClientErrorException(Status.CONFLICT);
|
||||
|
||||
+5
-1
@@ -51,10 +51,14 @@ public record IncomingMessage(int type,
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(clock.millis())
|
||||
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
|
||||
.setStory(story)
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent);
|
||||
|
||||
if (story) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
|
||||
if (sourceServiceIdentifier != null && sourceDeviceId != null) {
|
||||
envelopeBuilder
|
||||
.setSourceServiceId(sourceServiceIdentifier.toServiceIdentifierString())
|
||||
|
||||
+5
-1
@@ -46,9 +46,13 @@ public record OutgoingMessageEntity(UUID guid,
|
||||
.setServerTimestamp(serverTimestamp())
|
||||
.setDestinationServiceId(destinationUuid().toServiceIdentifierString())
|
||||
.setServerGuid(guid().toString())
|
||||
.setStory(story)
|
||||
.setUrgent(urgent);
|
||||
|
||||
if (story) {
|
||||
// Avoid sending this field if it's false.
|
||||
builder.setStory(true);
|
||||
}
|
||||
|
||||
if (sourceUuid() != null) {
|
||||
builder.setSourceServiceId(sourceUuid().toServiceIdentifierString());
|
||||
builder.setSourceDevice(sourceDevice());
|
||||
|
||||
+5
-1
@@ -168,9 +168,13 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent)
|
||||
.setStory(story)
|
||||
.setContent(entry.getValue().getPayload());
|
||||
|
||||
if (story) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
|
||||
spamCheckResult.token().ifPresent(reportSpamToken ->
|
||||
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken)));
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ public abstract class BaseRateLimiters<T extends RateLimiterDescriptor> {
|
||||
return requireNonNull(rateLimiterByDescriptor.get(handle));
|
||||
}
|
||||
|
||||
protected static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
|
||||
public static ClusterLuaScript defaultScript(final FaultTolerantRedisClusterClient cacheCluster) {
|
||||
try {
|
||||
return ClusterLuaScript.fromResource(
|
||||
cacheCluster, "lua/validate_rate_limit.lua", ScriptOutputType.INTEGER);
|
||||
|
||||
+17
-9
@@ -12,8 +12,16 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
|
||||
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
|
||||
@VisibleForTesting
|
||||
@@ -25,20 +33,20 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
public Response toResponse(final SubscriptionException exception) {
|
||||
|
||||
// Some exceptions have specific error body formats
|
||||
if (exception instanceof SubscriptionException.InvalidAmount e) {
|
||||
if (exception instanceof SubscriptionInvalidAmountException e) {
|
||||
return Response
|
||||
.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", e.getErrorCode()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionException.ProcessorException e) {
|
||||
if (exception instanceof SubscriptionProcessorException e) {
|
||||
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
|
||||
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionException.ChargeFailurePaymentRequired e) {
|
||||
if (exception instanceof SubscriptionChargeFailurePaymentRequiredException e) {
|
||||
return Response
|
||||
.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
|
||||
@@ -48,11 +56,11 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
|
||||
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
|
||||
final Response.Status status = (switch (exception) {
|
||||
case SubscriptionException.NotFound e -> Response.Status.NOT_FOUND;
|
||||
case SubscriptionException.Forbidden e -> Response.Status.FORBIDDEN;
|
||||
case SubscriptionException.InvalidArguments e -> Response.Status.BAD_REQUEST;
|
||||
case SubscriptionException.ProcessorConflict e -> Response.Status.CONFLICT;
|
||||
case SubscriptionException.PaymentRequired e -> Response.Status.PAYMENT_REQUIRED;
|
||||
case SubscriptionNotFoundException e -> Response.Status.NOT_FOUND;
|
||||
case SubscriptionForbiddenException e -> Response.Status.FORBIDDEN;
|
||||
case SubscriptionInvalidArgumentsException e -> Response.Status.BAD_REQUEST;
|
||||
case SubscriptionProcessorConflictException e -> Response.Status.CONFLICT;
|
||||
case SubscriptionPaymentRequiredException e -> Response.Status.PAYMENT_REQUIRED;
|
||||
default -> Response.Status.INTERNAL_SERVER_ERROR;
|
||||
});
|
||||
|
||||
|
||||
+6
-3
@@ -69,14 +69,17 @@ public class FaultTolerantRedisClient {
|
||||
redisUri.setLibraryVersion(null);
|
||||
|
||||
this.redisClient = RedisClient.create(clientResourcesBuilder.build(), redisUri);
|
||||
this.redisClient.setOptions(ClientOptions.builder()
|
||||
final ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder()
|
||||
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
|
||||
// for asynchronous commands
|
||||
.timeoutOptions(TimeoutOptions.builder()
|
||||
.fixedTimeout(commandTimeout)
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
.publishOnScheduler(true);
|
||||
|
||||
NettyUtil.setSocketTimeoutsIfApplicable(clientOptionsBuilder);
|
||||
|
||||
this.redisClient.setOptions(clientOptionsBuilder.build());
|
||||
|
||||
this.stringConnection = redisClient.connect();
|
||||
this.binaryConnection = redisClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
+7
-3
@@ -89,7 +89,8 @@ public class FaultTolerantRedisClusterClient {
|
||||
clientResourcesBuilder.nettyCustomizer(lettuceShardCircuitBreaker).
|
||||
build(),
|
||||
redisUris);
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
|
||||
final ClusterClientOptions.Builder clusterClientOptionsBuilder = ClusterClientOptions.builder()
|
||||
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
@@ -99,8 +100,11 @@ public class FaultTolerantRedisClusterClient {
|
||||
.timeoutOptions(TimeoutOptions.builder()
|
||||
.fixedTimeout(commandTimeout)
|
||||
.build())
|
||||
.publishOnScheduler(true)
|
||||
.build());
|
||||
.publishOnScheduler(true);
|
||||
|
||||
NettyUtil.setSocketTimeoutsIfApplicable(clusterClientOptionsBuilder);
|
||||
|
||||
this.clusterClient.setOptions(clusterClientOptionsBuilder.build());
|
||||
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import io.lettuce.core.ClientOptions;
|
||||
import io.lettuce.core.SocketOptions;
|
||||
import io.lettuce.core.resource.EpollProvider;
|
||||
import java.time.Duration;
|
||||
|
||||
public class NettyUtil {
|
||||
static final Duration TCP_KEEPALIVE_IDLE = Duration.ofSeconds(30);
|
||||
static final Duration TCP_KEEPALIVE_INTERVAL = Duration.ofSeconds(30);
|
||||
static final Duration TCP_USER_TIMEOUT = Duration.ofSeconds(30);
|
||||
|
||||
static void setSocketTimeoutsIfApplicable(final ClientOptions.Builder clientOptionsBuilder) {
|
||||
if (EpollProvider.isAvailable()) {
|
||||
// These socket options are only available with epoll native transport.
|
||||
clientOptionsBuilder.socketOptions(SocketOptions.builder()
|
||||
.keepAlive(SocketOptions.KeepAliveOptions.builder()
|
||||
.interval(TCP_KEEPALIVE_INTERVAL)
|
||||
.idle(TCP_KEEPALIVE_IDLE)
|
||||
.enable()
|
||||
.build())
|
||||
.tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
|
||||
.enable()
|
||||
.tcpUserTimeout(TCP_USER_TIMEOUT)
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -322,6 +322,9 @@ public class Accounts {
|
||||
existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElse(null),
|
||||
existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElse(null));
|
||||
|
||||
// Carry over the existing backup voucher to the new account
|
||||
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
|
||||
|
||||
+19
@@ -34,6 +34,7 @@ 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.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
@@ -109,6 +110,24 @@ public class IssuedReceiptsManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the recorded issuances for a particular item
|
||||
*
|
||||
* @param processorItemId The itemId within the processor to clear
|
||||
* @param processor The processor
|
||||
* @return a future that yields true if the item was deleted, false if the item already did not exist
|
||||
*/
|
||||
public CompletableFuture<Boolean> clearIssuance(String processorItemId, PaymentProvider processor) {
|
||||
final AttributeValue key = dynamoDbKey(processor, processorItemId);
|
||||
final DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_PROCESSOR_ITEM_ID, key))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build();
|
||||
return dynamoDbAsyncClient.deleteItem(deleteItemRequest)
|
||||
.thenApply(item -> item.hasAttributes() && !item.attributes().isEmpty());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static AttributeValue dynamoDbKey(final PaymentProvider processor, String processorItemId) {
|
||||
if (processor == PaymentProvider.STRIPE) {
|
||||
|
||||
@@ -145,15 +145,20 @@ public class MessagesManager {
|
||||
|
||||
return insertSharedMultiRecipientMessagePayload(multiRecipientMessage)
|
||||
.thenCompose(sharedMrmKey -> {
|
||||
final Envelope prototypeMessage = Envelope.newBuilder()
|
||||
final Envelope.Builder envelopeBuilder = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp == 0 ? serverTimestamp : clientTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setStory(isStory)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent)
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
|
||||
.build();
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
|
||||
|
||||
if (isStory) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
|
||||
final Envelope prototypeMessage = envelopeBuilder.build();
|
||||
|
||||
final Map<Account, Map<Byte, Boolean>> clientPresenceByAccountAndDevice = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
+8
-5
@@ -15,6 +15,9 @@ import javax.annotation.Nonnull;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
|
||||
public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
|
||||
@Nonnull byte[] subscriberUser,
|
||||
@@ -25,10 +28,10 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
|
||||
public static SubscriberCredentials process(
|
||||
Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
String subscriberId,
|
||||
Clock clock) throws SubscriptionException{
|
||||
Clock clock) throws SubscriptionException {
|
||||
Instant now = clock.instant();
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new SubscriptionException.Forbidden("must not use authenticated connection for subscriber operations");
|
||||
throw new SubscriptionForbiddenException("must not use authenticated connection for subscriber operations");
|
||||
}
|
||||
byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId);
|
||||
byte[] subscriberUser = getUser(subscriberBytes);
|
||||
@@ -37,15 +40,15 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes,
|
||||
return new SubscriberCredentials(subscriberBytes, subscriberUser, subscriberKey, hmac, now);
|
||||
}
|
||||
|
||||
private static byte[] convertSubscriberIdStringToBytes(String subscriberId) throws SubscriptionException.NotFound {
|
||||
private static byte[] convertSubscriberIdStringToBytes(String subscriberId) throws SubscriptionNotFoundException {
|
||||
try {
|
||||
byte[] bytes = Base64.getUrlDecoder().decode(subscriberId);
|
||||
if (bytes.length != 32) {
|
||||
throw new SubscriptionException.NotFound();
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
return bytes;
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new SubscriptionException.NotFound(e);
|
||||
throw new SubscriptionNotFoundException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-164
@@ -1,164 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
|
||||
public class SubscriptionException extends Exception {
|
||||
|
||||
private @Nullable String errorDetail;
|
||||
|
||||
public SubscriptionException(Exception cause) {
|
||||
this(cause, null);
|
||||
}
|
||||
|
||||
SubscriptionException(Exception cause, String errorDetail) {
|
||||
super(cause);
|
||||
this.errorDetail = errorDetail;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return An error message suitable to include in a client response
|
||||
*/
|
||||
public Optional<String> errorDetail() {
|
||||
return Optional.ofNullable(errorDetail);
|
||||
}
|
||||
|
||||
public static class NotFound extends SubscriptionException {
|
||||
|
||||
public NotFound() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
public NotFound(Exception cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Forbidden extends SubscriptionException {
|
||||
|
||||
public Forbidden(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
|
||||
public static class InvalidArguments extends SubscriptionException {
|
||||
|
||||
public InvalidArguments(final String message, final Exception cause) {
|
||||
super(cause, message);
|
||||
}
|
||||
|
||||
public InvalidArguments(final String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class InvalidLevel extends InvalidArguments {
|
||||
|
||||
public InvalidLevel() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class InvalidAmount extends InvalidArguments {
|
||||
private String errorCode;
|
||||
|
||||
public InvalidAmount(String errorCode) {
|
||||
super(null, null);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
|
||||
public static class PaymentRequiresAction extends InvalidArguments {
|
||||
|
||||
public PaymentRequiresAction(String message) {
|
||||
super(message, null);
|
||||
}
|
||||
|
||||
public PaymentRequiresAction() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class PaymentRequired extends SubscriptionException {
|
||||
|
||||
public PaymentRequired() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public PaymentRequired(String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ChargeFailurePaymentRequired extends SubscriptionException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public ChargeFailurePaymentRequired(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class ProcessorException extends SubscriptionException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public ProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open
|
||||
* state
|
||||
*/
|
||||
public static class ReceiptRequestedForOpenPayment extends SubscriptionException {
|
||||
|
||||
public ReceiptRequestedForOpenPayment() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProcessorConflict extends SubscriptionException {
|
||||
public ProcessorConflict() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public ProcessorConflict(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+74
-71
@@ -4,7 +4,6 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.stripe.exception.StripeException;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
@@ -31,7 +30,14 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
/**
|
||||
@@ -65,18 +71,18 @@ public class SubscriptionManager {
|
||||
* Cancel a subscription with the upstream payment provider and remove the subscription from the table
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
* @throws SubscriptionException.NotFound if the provided credentials are incorrect or the subscriber does not
|
||||
* exist
|
||||
* @throws SubscriptionException.InvalidArguments if a precondition for cancellation was not met
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
* @throws SubscriptionNotFoundException if the provided credentials are incorrect or the subscriber does not
|
||||
* exist
|
||||
* @throws SubscriptionInvalidArgumentsException if a precondition for cancellation was not met
|
||||
*/
|
||||
public void deleteSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionException.NotFound, SubscriptionException.InvalidArguments, RateLimitExceededException {
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
if (getResult == Subscriptions.GetResult.NOT_STORED
|
||||
|| getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionException.NotFound();
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
|
||||
// a missing customer ID is OK; it means the subscriber never started to add a payment method, so we can skip cancelling
|
||||
@@ -94,22 +100,22 @@ public class SubscriptionManager {
|
||||
* already exists, its last access time will be updated.
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @throws SubscriptionException.Forbidden if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
*/
|
||||
public void updateSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionException.Forbidden {
|
||||
throws SubscriptionForbiddenException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionException.Forbidden("subscriberId mismatch");
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
// create a customer and write it to ddb
|
||||
final Subscriptions.Record updatedRecord = subscriptions.create(subscriberCredentials.subscriberUser(),
|
||||
subscriberCredentials.hmac(),
|
||||
subscriberCredentials.now()).join();
|
||||
if (updatedRecord == null) {
|
||||
throw new SubscriptionException.Forbidden("subscriberId mismatch");
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
}
|
||||
} else {
|
||||
// already exists so just touch access time and return
|
||||
@@ -119,7 +125,7 @@ public class SubscriptionManager {
|
||||
|
||||
public Optional<SubscriptionInformation> getSubscriptionInformation(
|
||||
final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionException.Forbidden, SubscriptionException.NotFound, SubscriptionException.InvalidArguments, RateLimitExceededException {
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, RateLimitExceededException {
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
if (record.subscriptionId == null) {
|
||||
return Optional.empty();
|
||||
@@ -132,17 +138,17 @@ public class SubscriptionManager {
|
||||
* Get the subscriber record
|
||||
*
|
||||
* @param subscriberCredentials Subscriber credentials derived from the subscriberId
|
||||
* @throws SubscriptionException.Forbidden if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionException.NotFound if the subscriber did not exist
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist
|
||||
*/
|
||||
public Subscriptions.Record getSubscriber(final SubscriberCredentials subscriberCredentials)
|
||||
throws SubscriptionException.Forbidden, SubscriptionException.NotFound {
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException {
|
||||
final Subscriptions.GetResult getResult =
|
||||
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
|
||||
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
|
||||
throw new SubscriptionException.Forbidden("subscriberId mismatch");
|
||||
throw new SubscriptionForbiddenException("subscriberId mismatch");
|
||||
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
|
||||
throw new SubscriptionException.NotFound();
|
||||
throw new SubscriptionNotFoundException();
|
||||
} else {
|
||||
return getResult.record;
|
||||
}
|
||||
@@ -161,34 +167,31 @@ public class SubscriptionManager {
|
||||
* @param expiration A function that takes a {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem}
|
||||
* and returns the expiration time of the receipt
|
||||
* @return the requested ZK receipt credential
|
||||
* @throws SubscriptionException.Forbidden if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionException.NotFound if the subscriber did not exist or did not have a
|
||||
* subscription attached
|
||||
* @throws SubscriptionException.InvalidArguments if the receipt credential request failed verification
|
||||
* @throws SubscriptionException.PaymentRequired if the subscription is in a state does not grant the
|
||||
* user an entitlement
|
||||
* @throws SubscriptionException.ChargeFailurePaymentRequired if the subscription is in a state does not grant the
|
||||
* user an entitlement because a charge failed to go
|
||||
* through
|
||||
* @throws SubscriptionException.ReceiptRequestedForOpenPayment if a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a
|
||||
* subscription attached
|
||||
* @throws SubscriptionInvalidArgumentsException if the receipt credential request failed verification
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is in a state does not grant the
|
||||
* user an entitlement
|
||||
* @throws SubscriptionReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
*/
|
||||
public ReceiptResult createReceiptCredentials(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final SubscriptionController.GetReceiptCredentialsRequest request,
|
||||
final Function<CustomerAwareSubscriptionPaymentProcessor.ReceiptItem, Instant> expiration)
|
||||
throws SubscriptionException.Forbidden, SubscriptionException.NotFound, SubscriptionException.InvalidArguments, SubscriptionException.ChargeFailurePaymentRequired, SubscriptionException.PaymentRequired, RateLimitExceededException, SubscriptionException.ReceiptRequestedForOpenPayment {
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
if (record.subscriptionId == null) {
|
||||
throw new SubscriptionException.NotFound();
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
|
||||
ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest());
|
||||
} catch (InvalidInputException e) {
|
||||
throw new SubscriptionException.InvalidArguments("invalid receipt credential request", e);
|
||||
throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e);
|
||||
}
|
||||
|
||||
final PaymentProvider processor = record.getProcessorCustomer().orElseThrow().processor();
|
||||
@@ -204,7 +207,7 @@ public class SubscriptionManager {
|
||||
expiration.apply(receipt).getEpochSecond(),
|
||||
receipt.level());
|
||||
} catch (VerificationFailedException e) {
|
||||
throw new SubscriptionException.InvalidArguments("receipt credential request failed verification", e);
|
||||
throw new SubscriptionInvalidArgumentsException("receipt credential request failed verification", e);
|
||||
}
|
||||
return new ReceiptResult(receiptCredentialResponse, receipt, processor);
|
||||
}
|
||||
@@ -228,18 +231,18 @@ public class SubscriptionManager {
|
||||
* @param <R> The return type of the paymentSetupFunction, which should be used by a client
|
||||
* to configure the newly created payment method
|
||||
* @return The return value of the paymentSetupFunction
|
||||
* @throws SubscriptionException.Forbidden if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionException.NotFound if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionException.ProcessorConflict if the new payment processor the existing processor associated with
|
||||
* the subscriberId
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriberId
|
||||
*/
|
||||
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> R addPaymentMethodToCustomer(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final T subscriptionPaymentProcessor,
|
||||
final ClientPlatform clientPlatform,
|
||||
final BiFunction<T, String, R> paymentSetupFunction)
|
||||
throws SubscriptionException.Forbidden, SubscriptionException.NotFound, SubscriptionException.ProcessorConflict {
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
|
||||
|
||||
Subscriptions.Record record = this.getSubscriber(subscriberCredentials);
|
||||
if (record.getProcessorCustomer().isEmpty()) {
|
||||
@@ -253,7 +256,7 @@ public class SubscriptionManager {
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("processor must now exist")));
|
||||
|
||||
if (processorCustomer.processor() != subscriptionPaymentProcessor.getProvider()) {
|
||||
throw new SubscriptionException.ProcessorConflict("existing processor does not match");
|
||||
throw new SubscriptionProcessorConflictException("existing processor does not match");
|
||||
}
|
||||
return paymentSetupFunction.apply(subscriptionPaymentProcessor, processorCustomer.customerId());
|
||||
}
|
||||
@@ -288,13 +291,13 @@ public class SubscriptionManager {
|
||||
* @param subscriptionTemplateId Specifies the product associated with the provided level within the payment
|
||||
* processor
|
||||
* @param transitionValidator A function that checks if the level update is valid
|
||||
* @throws SubscriptionException.InvalidArguments if the transitionValidator failed for the level transition, or the
|
||||
* subscription could not be created because the payment provider
|
||||
* requires additional action, or there was a failure because an
|
||||
* idempotency key was reused on a * modified request
|
||||
* @throws SubscriptionException.ProcessorConflict if the new payment processor the existing processor associated
|
||||
* with the subscriber
|
||||
* @throws SubscriptionException.ProcessorException if there was no payment method on the customer
|
||||
* @throws SubscriptionInvalidArgumentsException if the transitionValidator failed for the level transition, or the
|
||||
* subscription could not be created because the payment provider
|
||||
* requires additional action, or there was a failure because an
|
||||
* idempotency key was reused on a * modified request
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriber
|
||||
* @throws SubscriptionProcessorException if there was no payment method on the customer
|
||||
*/
|
||||
public void updateSubscriptionLevelForCustomer(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
@@ -305,7 +308,7 @@ public class SubscriptionManager {
|
||||
final String idempotencyKey,
|
||||
final String subscriptionTemplateId,
|
||||
final LevelTransitionValidator transitionValidator)
|
||||
throws SubscriptionException.InvalidArguments, SubscriptionException.ProcessorConflict, SubscriptionException.ProcessorException {
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
if (record.subscriptionId != null) {
|
||||
// we already have a subscription in our records so let's check the level and currency,
|
||||
@@ -319,7 +322,7 @@ public class SubscriptionManager {
|
||||
return;
|
||||
}
|
||||
if (!transitionValidator.isTransitionValid(existingLevelAndCurrency.level(), level)) {
|
||||
throw new SubscriptionException.InvalidLevel();
|
||||
throw new SubscriptionInvalidLevelException();
|
||||
}
|
||||
final CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updatedSubscriptionId =
|
||||
processor.updateSubscription(subscription, subscriptionTemplateId, level, idempotencyKey);
|
||||
@@ -353,20 +356,20 @@ public class SubscriptionManager {
|
||||
* @param purchaseToken The client provided purchaseToken that represents a purchased subscription in the
|
||||
* play store
|
||||
* @return the subscription level for the accepted subscription
|
||||
* @throws SubscriptionException.Forbidden if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionException.NotFound if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionException.ProcessorConflict if the new payment processor the existing processor associated with
|
||||
* the subscriberId
|
||||
* @throws SubscriptionException.PaymentRequired if the subscription is not in a state that grants the user an
|
||||
* entitlement
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriberId
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an
|
||||
* entitlement
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
*/
|
||||
public long updatePlayBillingPurchaseToken(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final GooglePlayBillingManager googlePlayBillingManager,
|
||||
final String purchaseToken)
|
||||
throws SubscriptionException.ProcessorConflict, SubscriptionException.Forbidden, SubscriptionException.NotFound, RateLimitExceededException, SubscriptionException.PaymentRequired {
|
||||
throws SubscriptionProcessorConflictException, SubscriptionForbiddenException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionPaymentRequiredException {
|
||||
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the purchaseToken. Changes to the
|
||||
// subscription always just result in a new purchaseToken
|
||||
@@ -377,7 +380,7 @@ public class SubscriptionManager {
|
||||
// Check the record for an existing subscription
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) {
|
||||
throw new SubscriptionException.ProcessorConflict("existing processor does not match");
|
||||
throw new SubscriptionProcessorConflictException("existing processor does not match");
|
||||
}
|
||||
|
||||
// If we're replacing an existing purchaseToken, cancel it first
|
||||
@@ -406,26 +409,26 @@ public class SubscriptionManager {
|
||||
* @param originalTransactionId The client provided originalTransactionId that represents a purchased subscription in
|
||||
* the app store
|
||||
* @return the subscription level for the accepted subscription
|
||||
* @throws SubscriptionException.Forbidden if the subscriber credentials are incorrect
|
||||
* @throws SubscriptionException.NotFound if the originalTransactionId does not exist
|
||||
* @throws SubscriptionException.ProcessorConflict if the new payment processor the existing processor associated with
|
||||
* the subscriber
|
||||
* @throws SubscriptionException.InvalidArguments if the originalTransactionId is malformed or does not represent a
|
||||
* valid subscription
|
||||
* @throws SubscriptionException.PaymentRequired if the subscription is not in a state that grants the user an
|
||||
* entitlement
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials are incorrect
|
||||
* @throws SubscriptionNotFoundException if the originalTransactionId does not exist
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with
|
||||
* the subscriber
|
||||
* @throws SubscriptionInvalidArgumentsException if the originalTransactionId is malformed or does not represent a
|
||||
* valid subscription
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an
|
||||
* entitlement
|
||||
* @throws RateLimitExceededException if rate-limited
|
||||
*/
|
||||
public long updateAppStoreTransactionId(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final AppleAppStoreManager appleAppStoreManager,
|
||||
final String originalTransactionId)
|
||||
throws SubscriptionException.Forbidden, SubscriptionException.NotFound, SubscriptionException.ProcessorConflict, SubscriptionException.InvalidArguments, SubscriptionException.PaymentRequired, RateLimitExceededException {
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException {
|
||||
|
||||
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
|
||||
if (record.processorCustomer != null
|
||||
&& record.processorCustomer.processor() != PaymentProvider.APPLE_APP_STORE) {
|
||||
throw new SubscriptionException.ProcessorConflict("existing processor does not match");
|
||||
throw new SubscriptionProcessorConflictException("existing processor does not match");
|
||||
}
|
||||
|
||||
// For IAP providers, the subscriptionId and the customerId are both just the identifier for the subscription in
|
||||
|
||||
+202
-65
@@ -8,17 +8,21 @@ import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.hash.Hashing;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import java.time.Clock;
|
||||
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.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
///
|
||||
@@ -38,7 +42,21 @@ public class FoundationDbMessageStore {
|
||||
private final Clock clock;
|
||||
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private static final int MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE = 300;
|
||||
private static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
/// The (approximate) transaction size beyond which we do not add more messages in a transaction. The estimated size
|
||||
/// includes only message payloads (and not key reads/writes) which we assume will dominate the total
|
||||
/// transaction size. Note that the FDB [docs](https://apple.github.io/foundationdb/known-limitations.html) currently
|
||||
/// suggest a limit of 1MB to avoid performance issues, although the hard limit is 10MB
|
||||
private static final long MAX_MESSAGE_CHUNK_SIZE = DataSize.megabytes(1).toBytes();
|
||||
|
||||
/// Result of inserting a message for a particular device
|
||||
///
|
||||
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
|
||||
/// otherwise
|
||||
/// @param present whether the device is online
|
||||
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases, final Executor executor, final Clock clock) {
|
||||
this.databases = databases;
|
||||
@@ -46,75 +64,195 @@ public class FoundationDbMessageStore {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Insert a message bundle for a set of devices belonging to a single recipient. A message may not be inserted if the
|
||||
/// device is not present (as determined from its presence key) and the message is ephemeral. If all messages in the
|
||||
/// bundle don't end up being inserted, we won't return a versionstamp since the transaction was read-only.
|
||||
/// Convenience method for inserting a single recipient message bundle. See [#insert(Map)] for details.
|
||||
///
|
||||
/// @param aci destination account identifier
|
||||
/// @param messagesByDeviceId a map of deviceId => message envelope
|
||||
/// @return a future that completes with a [Versionstamp] of the committed transaction if at least one message was
|
||||
/// inserted
|
||||
public CompletableFuture<Optional<Versionstamp>> insert(final AciServiceIdentifier aci,
|
||||
/// @param aciServiceIdentifier accountId of the recipient
|
||||
/// @param messagesByDeviceId a map of message envelopes by deviceId to be inserted
|
||||
/// @return a future that yields a map deviceId => the presence state and versionstamp of the transaction in which the
|
||||
/// device's message was inserted (if any)
|
||||
public CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
|
||||
// We use Database#runAsync and not Database#run here because the latter would commit the transaction synchronously
|
||||
// and we would like to avoid any potential blocking in native code that could unexpectedly pin virtual threads. See https://forums.foundationdb.org/t/fdbdatabase-usage-from-java-api/593/2
|
||||
// for details.
|
||||
return getShardForAci(aci).runAsync(transaction -> insert(aci, messagesByDeviceId, transaction)
|
||||
.thenApply(hasMutations -> {
|
||||
if (hasMutations) {
|
||||
return transaction.getVersionstamp();
|
||||
}
|
||||
return CompletableFuture.completedFuture((byte[]) null);
|
||||
}))
|
||||
.thenComposeAsync(Function.identity(), executor)
|
||||
.thenApply(versionstampBytes -> Optional.ofNullable(versionstampBytes).map(Versionstamp::complete));
|
||||
}
|
||||
|
||||
private CompletableFuture<Boolean> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final Transaction transaction) {
|
||||
final List<CompletableFuture<Pair<Boolean, Boolean>>> messageInsertFutures = messagesByDeviceId.entrySet()
|
||||
.stream()
|
||||
.map(e -> {
|
||||
final byte deviceId = e.getKey();
|
||||
final MessageProtos.Envelope message = e.getValue();
|
||||
final byte[] presenceKey = getPresenceKey(aci, deviceId);
|
||||
return transaction.get(presenceKey)
|
||||
.thenApply(this::isClientPresent)
|
||||
.thenApply(isPresent -> {
|
||||
boolean hasMutations = false;
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
deviceQueueSubspace.packWithVersionstamp(Tuple.from(
|
||||
Versionstamp.incomplete())), message.toByteArray());
|
||||
hasMutations = true;
|
||||
}
|
||||
return new Pair<>(isPresent, hasMutations);
|
||||
});
|
||||
})
|
||||
.toList();
|
||||
return CompletableFuture.allOf(messageInsertFutures.toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> {
|
||||
final boolean anyClientPresent = messageInsertFutures
|
||||
.stream()
|
||||
.anyMatch(future -> future.join().first());
|
||||
final boolean hasMutations = messageInsertFutures
|
||||
.stream()
|
||||
.anyMatch(future -> future.join().second());
|
||||
if (anyClientPresent && hasMutations) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
}
|
||||
return hasMutations;
|
||||
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId))
|
||||
.thenApply(resultsByServiceIdentifier -> {
|
||||
assert resultsByServiceIdentifier.size() == 1;
|
||||
|
||||
return resultsByServiceIdentifier.get(aciServiceIdentifier);
|
||||
});
|
||||
}
|
||||
|
||||
private Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
/// Insert a multi-recipient message bundle. Destination ACIs are grouped by shard number. Each shard then starts a
|
||||
/// potentially multi-transaction operation. Messages are inserted in chunks to avoid transaction size limits.
|
||||
///
|
||||
/// @param messagesByServiceIdentifier a map of accountId to message envelopes by deviceId
|
||||
/// @return a future that yields a map containing the presence states of devices and versionstamps corresponding to
|
||||
/// committed transactions during this operation
|
||||
///
|
||||
/// @implNote All messages belonging to the same recipient are always committed in the same transaction for
|
||||
/// simplicity. A message may not be inserted if the device is not present (as determined from its presence key) and
|
||||
/// the message is ephemeral. If no messages in a transaction end up being inserted, we won't commit it since the
|
||||
/// transaction was read-only. As such, no corresponding versionstamp is generated.
|
||||
public CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier) {
|
||||
|
||||
if (messagesByServiceIdentifier.entrySet()
|
||||
.stream()
|
||||
.anyMatch(entry -> entry.getValue().isEmpty())) {
|
||||
throw new IllegalArgumentException("One or more message bundles is empty");
|
||||
}
|
||||
|
||||
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
|
||||
messagesByServiceIdentifier.entrySet().stream()
|
||||
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
|
||||
|
||||
final List<CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>>> chunkFutures =
|
||||
new ArrayList<>();
|
||||
|
||||
messagesByShardId.forEach((shardId, messagesForShard) -> {
|
||||
final Database shard = databases[shardId];
|
||||
|
||||
int start = 0, current = 0;
|
||||
int estimatedTransactionSize = 0;
|
||||
|
||||
while (current < messagesForShard.size()) {
|
||||
estimatedTransactionSize += messagesForShard.get(current).getValue().values()
|
||||
.stream()
|
||||
.mapToInt(MessageProtos.Envelope::getSerializedSize)
|
||||
.sum();
|
||||
|
||||
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
|
||||
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, current)));
|
||||
|
||||
start = current;
|
||||
estimatedTransactionSize = 0;
|
||||
} else {
|
||||
current++;
|
||||
}
|
||||
}
|
||||
|
||||
assert start < messagesForShard.size();
|
||||
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, messagesForShard.size())));
|
||||
});
|
||||
|
||||
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> chunkFutures.stream()
|
||||
.map(CompletableFuture::join)
|
||||
.reduce(new HashMap<>(), (a, b) -> {
|
||||
a.putAll(b);
|
||||
return a;
|
||||
}));
|
||||
}
|
||||
|
||||
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
|
||||
final Database database,
|
||||
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
|
||||
|
||||
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
|
||||
|
||||
// In a message bundle (single-recipient or MRM) the ephemerality should be the same for all envelopes, so just get the first.
|
||||
final boolean ephemeral = messagesByAccountIdentifier.stream()
|
||||
.findFirst()
|
||||
.flatMap(entry -> entry.getValue().values().stream().findFirst())
|
||||
.map(MessageProtos.Envelope::getEphemeral)
|
||||
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
messagesByAccountIdentifier.forEach(entry ->
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
|
||||
|
||||
return CompletableFuture.allOf(insertFuturesByAci.values().toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> {
|
||||
final boolean anyClientPresent = insertFuturesByAci.values()
|
||||
.stream()
|
||||
.map(CompletableFuture::join)
|
||||
.flatMap(presenceByDeviceId -> presenceByDeviceId.values().stream())
|
||||
.anyMatch(isPresent -> isPresent);
|
||||
if (anyClientPresent || !ephemeral) {
|
||||
return transaction.getVersionstamp()
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes)));
|
||||
}
|
||||
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
|
||||
});
|
||||
})
|
||||
.thenCompose(Function.identity())
|
||||
.thenApply(maybeVersionstamp -> insertFuturesByAci.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
|
||||
assert entry.getValue().isDone();
|
||||
final Map<Byte, Boolean> presenceByDeviceId = entry.getValue().join();
|
||||
|
||||
return presenceByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, presenceEntry -> {
|
||||
final Optional<Versionstamp> insertResultVersionstamp;
|
||||
if (presenceEntry.getValue() || !ephemeral) {
|
||||
assert maybeVersionstamp.isPresent();
|
||||
insertResultVersionstamp = maybeVersionstamp;
|
||||
} else {
|
||||
insertResultVersionstamp = Optional.empty();
|
||||
}
|
||||
return new InsertResult(insertResultVersionstamp, presenceEntry.getValue());
|
||||
}));
|
||||
})));
|
||||
}
|
||||
|
||||
/// Insert a message bundle for a single recipient in an ongoing transaction.
|
||||
///
|
||||
/// @implNote A message for a device is not inserted if it is offline and the message is ephemeral. Additionally, the
|
||||
/// message watch key is updated iff at least one receiving device is present.
|
||||
///
|
||||
/// @param aci accountId of the recipient
|
||||
/// @param messagesByDeviceId map of destination deviceId => message envelopes
|
||||
/// @param transaction the ongoing transaction
|
||||
/// @return a future that yields the presence state of each destination device
|
||||
private CompletableFuture<Map<Byte, Boolean>> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final Transaction transaction) {
|
||||
|
||||
final Map<Byte, CompletableFuture<Boolean>> messageInsertFuturesByDeviceId = messagesByDeviceId.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> {
|
||||
final byte deviceId = e.getKey();
|
||||
final MessageProtos.Envelope message = e.getValue();
|
||||
final byte[] presenceKey = getPresenceKey(aci, deviceId);
|
||||
|
||||
return transaction.get(presenceKey)
|
||||
.thenApply(this::isClientPresent)
|
||||
.thenApply(isPresent -> {
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
getDeviceQueueSubspace(aci, deviceId)
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete())), message.toByteArray());
|
||||
}
|
||||
|
||||
return isPresent;
|
||||
});
|
||||
}));
|
||||
|
||||
return CompletableFuture.allOf(messageInsertFuturesByDeviceId.values().toArray(CompletableFuture[]::new))
|
||||
.thenApplyAsync(_ -> {
|
||||
final Map<Byte, Boolean> presenceByDeviceId = messageInsertFuturesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
|
||||
assert entry.getValue().isDone();
|
||||
return entry.getValue().join();
|
||||
}));
|
||||
|
||||
final boolean anyClientPresent = presenceByDeviceId.values().stream().anyMatch(present -> present);
|
||||
|
||||
if (anyClientPresent) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
}
|
||||
|
||||
return presenceByDeviceId;
|
||||
}, executor);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
}
|
||||
|
||||
private int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
@VisibleForTesting
|
||||
int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
|
||||
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
|
||||
}
|
||||
@@ -139,7 +277,7 @@ public class FoundationDbMessageStore {
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceQueueSubspace(aci, deviceId).pack("p");
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -151,7 +289,6 @@ public class FoundationDbMessageStore {
|
||||
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
|
||||
// containing the timestamp (seconds since epoch) that the client updates periodically.
|
||||
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
|
||||
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE;
|
||||
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= PRESENCE_STALE_THRESHOLD.toSeconds();
|
||||
}
|
||||
|
||||
}
|
||||
+43
-30
@@ -41,7 +41,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
/**
|
||||
@@ -114,16 +113,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @return the subscription level of the valid transaction.
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionException.NotFound If the provided originalTransactionId was not found
|
||||
* @throws SubscriptionException.PaymentRequired If the originalTransactionId exists but is in a state that does not
|
||||
* @throws SubscriptionNotFoundException If the provided originalTransactionId was not found
|
||||
* @throws SubscriptionPaymentRequiredException If the originalTransactionId exists but is in a state that does not
|
||||
* grant the user an entitlement
|
||||
* @throws SubscriptionException.InvalidArguments If the transaction is valid but does not contain a subscription
|
||||
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription
|
||||
*/
|
||||
public Long validateTransaction(final String originalTransactionId)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound, SubscriptionException.PaymentRequired {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final DecodedTransaction tx = lookupAndValidateTransaction(originalTransactionId);
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionException.PaymentRequired();
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
return getLevel(tx);
|
||||
}
|
||||
@@ -137,25 +136,29 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
* this method.
|
||||
*
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @throws SubscriptionException.NotFound If the provided originalTransactionId was not found
|
||||
* @throws SubscriptionException.InvalidArguments If the transaction is valid but does not contain a subscription, or
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription, or
|
||||
* the transaction has not already been cancelled with storekit
|
||||
*/
|
||||
@Override
|
||||
public void cancelAllActiveSubscriptions(String originalTransactionId)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (tx.signedTransaction.getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction.getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo.getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
throw new SubscriptionException.InvalidArguments("must cancel subscription with storekit before deleting");
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (tx.signedTransaction.getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction.getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo.getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
throw new SubscriptionInvalidArgumentsException("must cancel subscription with storekit before deleting");
|
||||
}
|
||||
} catch (SubscriptionNotFoundException _) {
|
||||
// If the subscription is not found there is no need to do anything, so we can squash it
|
||||
}
|
||||
// The subscription will not auto-renew, so we can stop tracking it
|
||||
// The subscription will not auto-renew, so we can stop tracking it
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String originalTransactionId)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction.getStatus()) {
|
||||
case ACTIVE -> SubscriptionStatus.ACTIVE;
|
||||
@@ -181,10 +184,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String originalTransactionId)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound, SubscriptionException.PaymentRequired {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionException.PaymentRequired();
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
|
||||
// A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is
|
||||
@@ -198,11 +201,21 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
}
|
||||
|
||||
private DecodedTransaction lookup(final String originalTransactionId)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
try {
|
||||
return lookupAndValidateTransaction(originalTransactionId);
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
// Shouldn't happen because we previously validated this transactionId before storing it
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private DecodedTransaction lookupAndValidateTransaction(final String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final StatusResponse statuses = getAllSubscriptions(originalTransactionId);
|
||||
final SubscriptionGroupIdentifierItem item = statuses.getData().stream()
|
||||
.filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst()
|
||||
.orElseThrow(() -> new SubscriptionException.InvalidArguments("transaction did not contain a backup subscription", null));
|
||||
.orElseThrow(() -> new SubscriptionInvalidArgumentsException("transaction did not contain a backup subscription", null));
|
||||
|
||||
final List<DecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(this::decode)
|
||||
@@ -210,7 +223,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
.toList();
|
||||
|
||||
if (txs.isEmpty()) {
|
||||
throw new SubscriptionException.InvalidArguments("transactionId did not include a paid subscription", null);
|
||||
throw new SubscriptionInvalidArgumentsException("transactionId did not include a paid subscription", null);
|
||||
}
|
||||
|
||||
if (txs.size() > 1) {
|
||||
@@ -222,13 +235,13 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
// Get All Subscriptions only requires that the transaction be some transaction associated with the
|
||||
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
|
||||
// SubscriptionManager.
|
||||
throw new SubscriptionException.InvalidArguments("transactionId was not the transaction's originalTransactionId", null);
|
||||
throw new SubscriptionInvalidArgumentsException("transactionId was not the transaction's originalTransactionId", null);
|
||||
}
|
||||
return txs.getFirst();
|
||||
}
|
||||
|
||||
private StatusResponse getAllSubscriptions(final String originalTransactionId)
|
||||
throws SubscriptionException.NotFound, SubscriptionException.InvalidArguments, RateLimitExceededException {
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
try {
|
||||
@@ -236,9 +249,9 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
} catch (final APIException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", e.getApiError().name()).increment();
|
||||
throw switch (e.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND, TRANSACTION_ID_NOT_FOUND -> new SubscriptionException.NotFound();
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND, TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionException.InvalidArguments(e.getApiErrorMessage());
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
default -> e;
|
||||
};
|
||||
} catch (final IOException e) {
|
||||
@@ -246,7 +259,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
} catch (SubscriptionException.NotFound | SubscriptionException.InvalidArguments | RateLimitExceededException e) {
|
||||
} catch (SubscriptionNotFoundException | SubscriptionInvalidArgumentsException | RateLimitExceededException e) {
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
@@ -290,11 +303,11 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(tx.transaction.getCurrency(), amount));
|
||||
}
|
||||
|
||||
private long getLevel(final DecodedTransaction tx) throws SubscriptionException.InvalidArguments {
|
||||
private long getLevel(final DecodedTransaction tx) {
|
||||
final Long level = productIdToLevel.get(tx.transaction.getProductId());
|
||||
if (level == null) {
|
||||
throw new SubscriptionException.InvalidArguments(
|
||||
"Transaction for unknown productId " + tx.transaction.getProductId());
|
||||
throw new UncheckedIOException(new IOException(
|
||||
"Transaction for unknown productId " + tx.transaction.getProductId()));
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
+10
-12
@@ -38,7 +38,6 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -46,7 +45,6 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
|
||||
@@ -207,7 +205,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return switch (unsuccessfulTx.getProcessorResponseCode()) {
|
||||
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
|
||||
CompletableFuture.failedFuture(
|
||||
new SubscriptionException.ProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
|
||||
new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
|
||||
|
||||
default -> {
|
||||
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
|
||||
@@ -362,11 +360,11 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
@Override
|
||||
public SubscriptionId createSubscription(String customerId, String planId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionException.ProcessorConflict, SubscriptionException.ProcessorException {
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
|
||||
if (paymentMethod == null) {
|
||||
throw new SubscriptionException.ProcessorConflict();
|
||||
throw new SubscriptionProcessorConflictException();
|
||||
}
|
||||
|
||||
final Optional<Subscription> maybeExistingSubscription = paymentMethod.getSubscriptions().stream()
|
||||
@@ -400,7 +398,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
throw Optional
|
||||
.ofNullable(result.getTarget())
|
||||
.flatMap(subscription -> subscription.getTransactions().stream().findFirst())
|
||||
.map(transaction -> new SubscriptionException.ProcessorException(getProvider(),
|
||||
.map(transaction -> new SubscriptionProcessorException(getProvider(),
|
||||
createChargeFailure(transaction)))
|
||||
.orElseThrow(() -> new BraintreeException(result.getMessage()));
|
||||
}
|
||||
@@ -415,7 +413,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(Object subscriptionObj, String planId, long level,
|
||||
String idempotencyKey) throws SubscriptionException.ProcessorConflict, SubscriptionException.ProcessorException {
|
||||
String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
@@ -427,7 +425,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
endSubscription(subscription);
|
||||
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict()));
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionProcessorConflictException()));
|
||||
|
||||
final Customer customer = transaction.getCustomer();
|
||||
|
||||
@@ -579,17 +577,17 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
throws SubscriptionException.ReceiptRequestedForOpenPayment, SubscriptionException.ChargeFailurePaymentRequired {
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(SubscriptionException.ReceiptRequestedForOpenPayment::new);
|
||||
.orElseThrow(SubscriptionReceiptRequestedForOpenPaymentException::new);
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true);
|
||||
if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals(
|
||||
SubscriptionStatus.PAST_DUE)) {
|
||||
throw new SubscriptionException.ReceiptRequestedForOpenPayment();
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
throw new SubscriptionException.ChargeFailurePaymentRequired(getProvider(), createChargeFailure(transaction));
|
||||
throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(transaction));
|
||||
}
|
||||
|
||||
final Instant paidAt = transaction.getSubscriptionDetails().getBillingPeriodStartDate().toInstant();
|
||||
|
||||
+10
-12
@@ -6,9 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
/**
|
||||
@@ -42,11 +40,11 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* @param paymentMethodToken a processor-specific token previously acquired at
|
||||
* {@link #createPaymentMethodSetupToken}
|
||||
* @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update
|
||||
* @throws SubscriptionException.InvalidArguments If the paymentMethodToken is invalid or the payment method has not
|
||||
* @throws SubscriptionInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
|
||||
* finished being set up
|
||||
*/
|
||||
void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionException.InvalidArguments;
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException;
|
||||
|
||||
Object getSubscription(String subscriptionId);
|
||||
|
||||
@@ -58,14 +56,14 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* @param level The level of the subscription
|
||||
* @param lastSubscriptionCreatedAt The timestamp of the last successfully created subscription
|
||||
* @return A subscription identifier
|
||||
* @throws SubscriptionException.ProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionException.InvalidArguments If there was a failure because an idempotency key was reused on a
|
||||
* @throws SubscriptionProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a
|
||||
* modified request, or if the payment requires additional steps
|
||||
* before charging
|
||||
* @throws SubscriptionException.ProcessorConflict If there was no payment method on the customer
|
||||
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
|
||||
*/
|
||||
SubscriptionId createSubscription(String customerId, String templateId, long level, long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionException.ProcessorException, SubscriptionException.InvalidArguments, SubscriptionException.ProcessorConflict;
|
||||
throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException;
|
||||
|
||||
/**
|
||||
* Update an existing subscription on a customer
|
||||
@@ -75,14 +73,14 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* @param level The target level of the subscription
|
||||
* @param idempotencyKey An idempotency key to prevent retries of successful requests
|
||||
* @return A subscription identifier
|
||||
* @throws SubscriptionException.ProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionException.InvalidArguments If there was a failure because an idempotency key was reused on a
|
||||
* @throws SubscriptionProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a
|
||||
* modified request, or if the payment requires additional steps
|
||||
* before charging
|
||||
* @throws SubscriptionException.ProcessorConflict If there was no payment method on the customer
|
||||
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
|
||||
*/
|
||||
SubscriptionId updateSubscription(Object subscription, String templateId, long level, String idempotencyKey)
|
||||
throws SubscriptionException.InvalidArguments, SubscriptionException.ProcessorException, SubscriptionException.ProcessorConflict;
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException, SubscriptionProcessorConflictException;
|
||||
|
||||
/**
|
||||
* @param subscription
|
||||
|
||||
+13
-14
@@ -46,7 +46,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
|
||||
/**
|
||||
* Manages subscriptions made with the Play Billing API
|
||||
@@ -134,7 +133,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
* @return A stage that completes when the purchase has been successfully acknowledged
|
||||
*/
|
||||
public void acknowledgePurchase()
|
||||
throws RateLimitExceededException, SubscriptionException.NotFound {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
if (!requiresAck) {
|
||||
// We've already acknowledged this purchase on a previous attempt, nothing to do
|
||||
return;
|
||||
@@ -155,12 +154,12 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
* @param purchaseToken The play store billing purchaseToken that represents a subscription purchase
|
||||
* @return A {@link ValidatedToken} that can be acknowledged
|
||||
* @throws RateLimitExceededException If rate-limited by play-billing
|
||||
* @throws SubscriptionException.NotFound If the provided purchaseToken was not found in play-billing
|
||||
* @throws SubscriptionException.PaymentRequired If the purchaseToken exists but is in a state that does not grant the
|
||||
* @throws SubscriptionNotFoundException If the provided purchaseToken was not found in play-billing
|
||||
* @throws SubscriptionPaymentRequiredException If the purchaseToken exists but is in a state that does not grant the
|
||||
* user an entitlement
|
||||
*/
|
||||
public ValidatedToken validateToken(String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionException.NotFound, SubscriptionException.PaymentRequired {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final SubscriptionState state = SubscriptionState
|
||||
.fromString(subscription.getSubscriptionState())
|
||||
@@ -175,7 +174,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
if (state != SubscriptionState.ACTIVE
|
||||
&& state != SubscriptionState.IN_GRACE_PERIOD
|
||||
&& state != SubscriptionState.CANCELED) {
|
||||
throw new SubscriptionException.PaymentRequired(
|
||||
throw new SubscriptionPaymentRequiredException(
|
||||
"Cannot acknowledge purchase for subscription in state " + subscription.getSubscriptionState());
|
||||
}
|
||||
|
||||
@@ -221,14 +220,14 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
executeTokenOperation(pub ->
|
||||
pub.purchases().subscriptions().cancel(packageName, purchase.getProductId(), purchaseToken));
|
||||
} catch (SubscriptionException.NotFound e) {
|
||||
// If the subscription is not found, no need to do anything so we can squash it
|
||||
} catch (SubscriptionNotFoundException e) {
|
||||
// If the subscription is not found there is no need to do anything, so we can squash it
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionException.NotFound {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final SubscriptionPrice price = getSubscriptionPrice(subscription);
|
||||
@@ -300,7 +299,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionException.NotFound, SubscriptionException.PaymentRequired {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final AcknowledgementState acknowledgementState = AcknowledgementState
|
||||
.fromString(subscription.getAcknowledgementState())
|
||||
@@ -321,7 +320,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
// We don't need to check any state at this point, just whether the subscription is currently valid. If the
|
||||
// subscription is in a grace period, the expiration time will be dynamically extended, see
|
||||
// https://developer.android.com/google/play/billing/lifecycle/subscriptions#grace-period
|
||||
throw new SubscriptionException.PaymentRequired();
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
|
||||
return new ReceiptItem(
|
||||
@@ -345,13 +344,13 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
* @return A stage that completes with the result of the API call
|
||||
*/
|
||||
private <R> R executeTokenOperation(final ApiCall<R> apiCall)
|
||||
throws RateLimitExceededException, SubscriptionException.NotFound {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
try {
|
||||
return apiCall.req(androidPublisher).execute();
|
||||
} catch (HttpResponseException e) {
|
||||
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()
|
||||
|| e.getStatusCode() == Response.Status.GONE.getStatusCode()) {
|
||||
throw new SubscriptionException.NotFound();
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
if (e.getStatusCode() == Response.Status.TOO_MANY_REQUESTS.getStatusCode()) {
|
||||
throw new RateLimitExceededException(null);
|
||||
@@ -368,7 +367,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
}
|
||||
|
||||
private SubscriptionPurchaseV2 lookupSubscription(final String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionException.NotFound {
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
|
||||
}
|
||||
|
||||
|
||||
+19
-21
@@ -65,7 +65,6 @@ import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -76,7 +75,6 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
@@ -175,7 +173,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
@Override
|
||||
public void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionException.InvalidArguments {
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
|
||||
CustomerUpdateParams params = CustomerUpdateParams.builder()
|
||||
.setInvoiceSettings(InvoiceSettings.builder()
|
||||
.setDefaultPaymentMethod(paymentMethodId)
|
||||
@@ -185,7 +183,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
stripeClient.customers().update(customerId, params, commonOptions());
|
||||
} catch (InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw new SubscriptionException.InvalidArguments(e.getMessage());
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -209,7 +207,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment intent. May throw a {@link SubscriptionException.InvalidAmount} if stripe rejects the
|
||||
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the
|
||||
* attempt if the amount is too large or too small
|
||||
*/
|
||||
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
|
||||
@@ -234,7 +232,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small","amount_too_large" ->
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidAmount(errorCode));
|
||||
throw ExceptionUtils.wrap(new SubscriptionInvalidAmountException(errorCode));
|
||||
default -> throw new CompletionException(e);
|
||||
}
|
||||
}
|
||||
@@ -286,7 +284,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
@Override
|
||||
public SubscriptionId createSubscription(String customerId, String priceId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionException.ProcessorException, SubscriptionException.InvalidArguments {
|
||||
throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException {
|
||||
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
|
||||
// retries this request
|
||||
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
@@ -308,12 +306,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
|
||||
return new SubscriptionId(subscription.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
throw new SubscriptionException.InvalidArguments(e.getStripeError().getMessage());
|
||||
throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
throw new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
|
||||
throw new SubscriptionException.PaymentRequiresAction();
|
||||
throw new SubscriptionPaymentRequiresActionException();
|
||||
}
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -321,7 +319,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
@Override
|
||||
public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey)
|
||||
throws SubscriptionException.InvalidArguments, SubscriptionException.ProcessorException {
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException {
|
||||
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
@@ -360,9 +358,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
|
||||
return new SubscriptionId(subscription1.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
throw new SubscriptionException.InvalidArguments(e.getStripeError().getMessage());
|
||||
throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
throw new SubscriptionException.ProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -607,27 +605,27 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
throws SubscriptionException.ChargeFailurePaymentRequired, SubscriptionException.PaymentRequired, SubscriptionException.ReceiptRequestedForOpenPayment {
|
||||
throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject();
|
||||
return convertInvoiceToReceipt(invoice, subscriptionId);
|
||||
}
|
||||
|
||||
private ReceiptItem convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId)
|
||||
throws SubscriptionException.ReceiptRequestedForOpenPayment, SubscriptionException.ChargeFailurePaymentRequired, SubscriptionException.PaymentRequired {
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException {
|
||||
if (latestSubscriptionInvoice == null) {
|
||||
throw new SubscriptionException.ReceiptRequestedForOpenPayment();
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase("open", latestSubscriptionInvoice.getStatus())) {
|
||||
throw new SubscriptionException.ReceiptRequestedForOpenPayment();
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (!StringUtils.equalsIgnoreCase("paid", latestSubscriptionInvoice.getStatus())) {
|
||||
final Charge charge = latestSubscriptionInvoice.getChargeObject();
|
||||
if (charge != null && (charge.getFailureCode() != null || charge.getFailureMessage() != null)) {
|
||||
// If the charge object has a failure reason we can present to the user, create a detailed exception
|
||||
throw new SubscriptionException.ChargeFailurePaymentRequired(getProvider(), createChargeFailure(charge));
|
||||
throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(charge));
|
||||
} else {
|
||||
// Otherwise, return a generic payment required error
|
||||
throw new SubscriptionException.PaymentRequired();
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -689,12 +687,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
// This usually indicates that the client has made requests out of order, either by not confirming
|
||||
// the SetupIntent or not having the user authorize the transaction.
|
||||
logger.debug("setupIntent {} missing expected fields", setupIntentId);
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.ProcessorConflict());
|
||||
throw ExceptionUtils.wrap(new SubscriptionProcessorConflictException());
|
||||
}
|
||||
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
|
||||
} catch (StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.NotFound());
|
||||
throw ExceptionUtils.wrap(new SubscriptionNotFoundException());
|
||||
}
|
||||
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
|
||||
throw ExceptionUtils.wrap(e);
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionChargeFailurePaymentRequiredException extends SubscriptionPaymentRequiredException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public SubscriptionChargeFailurePaymentRequiredException(final PaymentProvider processor,
|
||||
final ChargeFailure chargeFailure) {
|
||||
super();
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
|
||||
}
|
||||
+3
-1
@@ -80,7 +80,9 @@ public class SubscriptionCurrencyUtil {
|
||||
* BigDecimal)
|
||||
*/
|
||||
static BigDecimal convertGoogleMoneyToApiAmount(final Money money) {
|
||||
final BigDecimal fractionalComponent = BigDecimal.valueOf(money.getNanos()).scaleByPowerOfTen(-9);
|
||||
final BigDecimal fractionalComponent = money.getNanos() == null
|
||||
? BigDecimal.ZERO
|
||||
: BigDecimal.valueOf(money.getNanos()).scaleByPowerOfTen(-9);
|
||||
final BigDecimal amount = BigDecimal.valueOf(money.getUnits()).add(fractionalComponent);
|
||||
return convertConfiguredAmountToApiAmount(money.getCurrencyCode(), amount);
|
||||
}
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class SubscriptionException extends Exception {
|
||||
|
||||
private @Nullable String errorDetail;
|
||||
|
||||
public SubscriptionException(Exception cause) {
|
||||
this(cause, null);
|
||||
}
|
||||
|
||||
SubscriptionException(Exception cause, String errorDetail) {
|
||||
super(cause);
|
||||
this.errorDetail = errorDetail;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return An error message suitable to include in a client response
|
||||
*/
|
||||
public Optional<String> errorDetail() {
|
||||
return Optional.ofNullable(errorDetail);
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionForbiddenException extends SubscriptionException {
|
||||
|
||||
public SubscriptionForbiddenException(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionInvalidAmountException extends SubscriptionInvalidArgumentsException {
|
||||
|
||||
private String errorCode;
|
||||
|
||||
public SubscriptionInvalidAmountException(String errorCode) {
|
||||
super(null, null);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionInvalidArgumentsException extends SubscriptionException {
|
||||
|
||||
public SubscriptionInvalidArgumentsException(final String message, final Exception cause) {
|
||||
super(cause, message);
|
||||
}
|
||||
|
||||
public SubscriptionInvalidArgumentsException(final String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionInvalidLevelException extends SubscriptionInvalidArgumentsException {
|
||||
|
||||
public SubscriptionInvalidLevelException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionNotFoundException extends SubscriptionException {
|
||||
|
||||
public SubscriptionNotFoundException() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
public SubscriptionNotFoundException(Exception cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
+13
-25
@@ -6,9 +6,6 @@ package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface SubscriptionPaymentProcessor {
|
||||
|
||||
@@ -29,22 +26,16 @@ public interface SubscriptionPaymentProcessor {
|
||||
*
|
||||
* @param subscriptionId A subscriptionId that potentially corresponds to a valid subscription
|
||||
* @return A {@link ReceiptItem} if the subscription is valid
|
||||
*
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionException.NotFound If the provided subscriptionId could not be found with
|
||||
* the provider
|
||||
* @throws SubscriptionException.InvalidArguments If the subscriptionId locates a subscription that
|
||||
* cannot be used to generate a receipt
|
||||
* @throws SubscriptionException.PaymentRequired If the subscription is in a state does not grant the
|
||||
* user an entitlement
|
||||
* @throws SubscriptionException.ChargeFailurePaymentRequired If the subscription is in a state does not grant the
|
||||
* user an entitlement because a charge failed to go
|
||||
* through
|
||||
* @throws SubscriptionException.ReceiptRequestedForOpenPayment If a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided subscriptionId could not be found with
|
||||
* the provider
|
||||
* @throws SubscriptionPaymentRequiredException If the subscription is in a state does not grant the
|
||||
* user an entitlement
|
||||
* @throws SubscriptionReceiptRequestedForOpenPaymentException If a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
*/
|
||||
ReceiptItem getReceiptItem(String subscriptionId)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound, SubscriptionException.ChargeFailurePaymentRequired, SubscriptionException.PaymentRequired, SubscriptionException.ReceiptRequestedForOpenPayment;
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionChargeFailurePaymentRequiredException, SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
|
||||
/**
|
||||
* Cancel all active subscriptions for this key within the payment processor.
|
||||
@@ -52,22 +43,19 @@ public interface SubscriptionPaymentProcessor {
|
||||
* @param key An identifier for the subscriber within the payment provider, corresponds to the customerId field in the
|
||||
* subscriptions table
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionException.NotFound If the provided key was not found with the provider
|
||||
* @throws SubscriptionException.InvalidArguments If a precondition for cancellation was not met
|
||||
* @throws SubscriptionInvalidArgumentsException If a precondition for cancellation was not met
|
||||
*/
|
||||
void cancelAllActiveSubscriptions(String key)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound;
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException;
|
||||
|
||||
/**
|
||||
* Retrieve subscription information from the processor
|
||||
*
|
||||
* @param subscriptionId The identifier with the processor to retrieve information for
|
||||
* @return {@link SubscriptionInformation} from the provider
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionException.NotFound If the provided key was not found with the provider
|
||||
* @throws SubscriptionException.InvalidArguments If the subscription exists on the provider but does not represent a
|
||||
* valid subscription
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided key was not found with the provider
|
||||
*/
|
||||
SubscriptionInformation getSubscriptionInformation(final String subscriptionId)
|
||||
throws SubscriptionException.InvalidArguments, RateLimitExceededException, SubscriptionException.NotFound;
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionPaymentRequiredException extends SubscriptionException {
|
||||
|
||||
public SubscriptionPaymentRequiredException() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public SubscriptionPaymentRequiredException(String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionPaymentRequiresActionException extends SubscriptionInvalidArgumentsException {
|
||||
|
||||
public SubscriptionPaymentRequiresActionException(String message) {
|
||||
super(message, null);
|
||||
}
|
||||
|
||||
public SubscriptionPaymentRequiresActionException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionProcessorConflictException extends SubscriptionException {
|
||||
|
||||
public SubscriptionProcessorConflictException() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public SubscriptionProcessorConflictException(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
public class SubscriptionProcessorException extends SubscriptionException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public SubscriptionProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public ChargeFailure getChargeFailure() {
|
||||
return chargeFailure;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
/**
|
||||
* Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open state
|
||||
*/
|
||||
public class SubscriptionReceiptRequestedForOpenPaymentException extends SubscriptionException {
|
||||
|
||||
public SubscriptionReceiptRequestedForOpenPaymentException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+30
-11
@@ -5,24 +5,23 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class BackupMetricsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
@@ -67,17 +66,37 @@ public class BackupMetricsCommand extends AbstractCommandWithDependencies {
|
||||
"timeSinceLastRefresh"));
|
||||
final DistributionSummary timeSinceLastMediaRefresh = Metrics.summary(name(getClass(),
|
||||
"timeSinceLastMediaRefresh"));
|
||||
final DistributionSummary numMediaObjects = Metrics.summary(name(getClass(),
|
||||
"numObjects"));
|
||||
final DistributionSummary mediaBytesUsed = Metrics.summary(name(getClass(),
|
||||
"bytesUsed"));
|
||||
|
||||
final Counter freeTierBackups = Metrics.counter(name(getClass(), "backups"), "tier", "free");
|
||||
final Counter paidTierBackups = Metrics.counter(name(getClass(), "backups"), "tier", "paid");
|
||||
|
||||
|
||||
final BackupManager backupManager = commandDependencies.backupManager();
|
||||
final Long backupsExpired = backupManager
|
||||
.listBackupAttributes(segments, Schedulers.parallel())
|
||||
final Long backupsCrawled = backupManager
|
||||
.listBackupAttributes(segments)
|
||||
.doOnNext(backupMetadata -> {
|
||||
timeSinceLastRefresh.record(timeSince(backupMetadata.lastRefresh()).getSeconds());
|
||||
timeSinceLastMediaRefresh.record(timeSince(backupMetadata.lastMediaRefresh()).getSeconds());
|
||||
|
||||
final boolean hasMediaTier = Duration
|
||||
.between(backupMetadata.lastMediaRefresh(), backupMetadata.lastRefresh())
|
||||
.abs()
|
||||
.compareTo(Duration.ofDays(1)) < 1;
|
||||
if (hasMediaTier) {
|
||||
numMediaObjects.record(backupMetadata.numObjects());
|
||||
mediaBytesUsed.record(backupMetadata.bytesUsed());
|
||||
paidTierBackups.increment();
|
||||
} else {
|
||||
freeTierBackups.increment();
|
||||
}
|
||||
})
|
||||
.count()
|
||||
.block();
|
||||
logger.info("Crawled {} backups", backupsExpired);
|
||||
logger.info("Crawled {} backups", backupsCrawled);
|
||||
}
|
||||
|
||||
private Duration timeSince(Instant t) {
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ public class BackupUsageRecalculationCommand extends AbstractCommandWithDependen
|
||||
|
||||
final BackupManager backupManager = commandDependencies.backupManager();
|
||||
final Long backupsConsidered = backupManager
|
||||
.listBackupAttributes(segments, Schedulers.parallel())
|
||||
.listBackupAttributes(segments)
|
||||
.flatMap(attrs -> Mono.fromCompletionStage(() -> backupManager.recalculateQuota(attrs)).doOnNext(maybeRecalculationResult -> maybeRecalculationResult.ifPresent(recalculationResult -> {
|
||||
if (!recalculationResult.newUsage().equals(recalculationResult.oldUsage())) {
|
||||
logger.info("Recalculated usage. oldUsage={}, newUsage={}, lastRefresh={}, lastMediaRefresh={}",
|
||||
|
||||
+3
-1
@@ -22,7 +22,9 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
public class CertificateCommand extends Command {
|
||||
|
||||
private static final Set<Integer> RESERVED_CERTIFICATE_IDS = Set.of(
|
||||
0xdeadc357 // Reserved for testing; see https://github.com/signalapp/libsignal-client/pull/118
|
||||
// Reserved for testing in libsignal.
|
||||
0xdeadc357, // "dead cert", one considered revoked
|
||||
0x7357c357 // "test cert", one signed with a testing trust root
|
||||
);
|
||||
|
||||
public CertificateCommand() {
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor;
|
||||
|
||||
public class ClearIssuedReceiptRedemptionsCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(ClearIssuedReceiptRedemptionsCommand.class);
|
||||
|
||||
public ClearIssuedReceiptRedemptionsCommand() {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(WhisperServerConfiguration configuration, Environment environment) {
|
||||
|
||||
}
|
||||
}, "clear-issued-receipt-redemptions", "Clear issued receipt redemptions");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
subparser.addArgument("-s", "--subscriber-id")
|
||||
.dest("subscriberId")
|
||||
.type(String.class)
|
||||
.required(true)
|
||||
.help("The subscriber-id whose receipt redemptions should be clear");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(Environment environment, Namespace namespace, WhisperServerConfiguration configuration,
|
||||
CommandDependencies deps) throws Exception {
|
||||
try {
|
||||
final String subscriberId = namespace.getString("subscriberId");
|
||||
|
||||
final SubscriberCredentials creds = SubscriberCredentials
|
||||
.process(Optional.empty(), subscriberId, Clock.systemUTC());
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = deps.issuedReceiptsManager();
|
||||
final SubscriptionManager subscriptionManager = deps.subscriptionManager();
|
||||
|
||||
final Subscriptions.Record subscriber = subscriptionManager.getSubscriber(creds);
|
||||
final PaymentProvider processorType = subscriber.getProcessorCustomer()
|
||||
.orElseThrow(() -> new IllegalArgumentException("susbcriber did not have a subscription"))
|
||||
.processor();
|
||||
final SubscriptionPaymentProcessor processor = switch (processorType) {
|
||||
case APPLE_APP_STORE -> deps.appleAppStoreManager();
|
||||
case GOOGLE_PLAY_BILLING -> deps.googlePlayBillingManager();
|
||||
default ->
|
||||
throw new IllegalStateException("Cannot clear issued receipts for a non-IAP processor: " + processorType);
|
||||
};
|
||||
final SubscriptionPaymentProcessor.ReceiptItem receiptItem = processor.getReceiptItem(subscriber.subscriptionId);
|
||||
final boolean deleted = issuedReceiptsManager.clearIssuance(receiptItem.itemId(), processorType).join();
|
||||
logger.info("Deleted issuances for receiptItem: {}, subscriberId: {}, hadExistingIssuances: {}",
|
||||
receiptItem.itemId(), subscriberId, deleted);
|
||||
} catch (Exception ex) {
|
||||
logger.warn("Removal Exception", ex);
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
-2
@@ -11,16 +11,23 @@ import com.codahale.metrics.MetricRegistry;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Clock;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.SynchronousQueue;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerService;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
@@ -72,6 +79,10 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
@@ -101,6 +112,9 @@ record CommandDependencies(
|
||||
ClientResources.Builder redisClusterClientResourcesBuilder,
|
||||
BackupManager backupManager,
|
||||
IssuedReceiptsManager issuedReceiptsManager,
|
||||
GooglePlayBillingManager googlePlayBillingManager,
|
||||
AppleAppStoreManager appleAppStoreManager,
|
||||
SubscriptionManager subscriptionManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
@@ -110,7 +124,7 @@ record CommandDependencies(
|
||||
final String name,
|
||||
final Environment environment,
|
||||
final WhisperServerConfiguration configuration)
|
||||
throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeyException {
|
||||
throws IOException, GeneralSecurityException, InvalidInputException {
|
||||
Clock clock = Clock.systemUTC();
|
||||
|
||||
environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
@@ -300,7 +314,8 @@ record CommandDependencies(
|
||||
configuration.getCdn3StorageManagerConfiguration()),
|
||||
secureValueRecoveryBCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock);
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
@@ -309,6 +324,30 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(),
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
|
||||
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getZkConfig().serverSecret().value());
|
||||
final ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
|
||||
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
|
||||
new ByteArrayInputStream(configuration.getGooglePlayBilling().credentialsJson().value().getBytes(StandardCharsets.UTF_8)),
|
||||
configuration.getGooglePlayBilling().packageName(),
|
||||
configuration.getGooglePlayBilling().applicationName(),
|
||||
configuration.getGooglePlayBilling().productIdToLevel());
|
||||
AppleAppStoreManager appleAppStoreManager = new AppleAppStoreManager(
|
||||
configuration.getAppleAppStore().env(),
|
||||
configuration.getAppleAppStore().bundleId(),
|
||||
configuration.getAppleAppStore().appAppleId(),
|
||||
configuration.getAppleAppStore().issuerId(),
|
||||
configuration.getAppleAppStore().keyId(),
|
||||
configuration.getAppleAppStore().encodedKey().value(),
|
||||
configuration.getAppleAppStore().subscriptionGroupId(),
|
||||
configuration.getAppleAppStore().productIdToLevel(),
|
||||
configuration.getAppleAppStore().appleRootCerts(),
|
||||
configuration.getAppleAppStore().retryConfigurationName());
|
||||
final SubscriptionManager subscriptionManager = new SubscriptionManager(
|
||||
new Subscriptions(configuration.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient),
|
||||
List.of(googlePlayBillingManager, appleAppStoreManager),
|
||||
zkReceiptOperations,
|
||||
issuedReceiptsManager);
|
||||
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, configuration.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, configuration.getFcmConfiguration().credentials().value());
|
||||
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
|
||||
@@ -345,6 +384,9 @@ record CommandDependencies(
|
||||
redisClientResourcesBuilder,
|
||||
backupManager,
|
||||
issuedReceiptsManager,
|
||||
googlePlayBillingManager,
|
||||
appleAppStoreManager,
|
||||
subscriptionManager,
|
||||
dynamicConfigurationManager,
|
||||
dynamoDbAsyncClient,
|
||||
phoneNumberIdentifiers,
|
||||
|
||||
+26
@@ -9,6 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -57,6 +58,7 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -511,6 +513,26 @@ public class BackupAuthManagerTest {
|
||||
return clientOps.createReceiptCredentialPresentation(receiptCredential);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void testCheckLimits(
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean messageLimited,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean mediaLimited,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean hasVoucher) {
|
||||
clock.pin(Instant.EPOCH);
|
||||
final BackupAuthManager authManager = create(BackupLevel.FREE, rateLimiter(aci, messageLimited, mediaLimited));
|
||||
final Account account = new MockAccountBuilder()
|
||||
.backupVoucher(hasVoucher
|
||||
? new Account.BackupVoucher(1, Instant.EPOCH.plus(Duration.ofSeconds(1)))
|
||||
: null)
|
||||
.build();
|
||||
final BackupAuthManager.BackupIdRotationLimit limit = authManager.checkBackupIdRotationLimit(account)
|
||||
.toCompletableFuture().join();
|
||||
final boolean expectHasPermits = !messageLimited && (!mediaLimited || !hasVoucher);
|
||||
final Duration expectedDuration = expectHasPermits ? Duration.ZERO : Duration.ofDays(1);
|
||||
assertThat(limit.hasPermitsRemaining()).isEqualTo(expectHasPermits);
|
||||
assertThat(limit.nextPermitAvailable()).isEqualTo(expectedDuration);
|
||||
}
|
||||
|
||||
|
||||
@CartesianTest
|
||||
void testChangeIdRateLimits(
|
||||
@@ -643,11 +665,15 @@ public class BackupAuthManagerTest {
|
||||
final RateLimiters limiters = mock(RateLimiters.class);
|
||||
|
||||
final RateLimiter allowLimiter = mock(RateLimiter.class);
|
||||
when(allowLimiter.hasAvailablePermitsAsync(eq(aci), anyInt())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
when(allowLimiter.validateAsync(aci)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(allowLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
|
||||
final RateLimiter denyLimiter = mock(RateLimiter.class);
|
||||
when(denyLimiter.hasAvailablePermitsAsync(eq(aci), anyInt())).thenReturn(CompletableFuture.completedFuture(false));
|
||||
when(denyLimiter.validateAsync(aci))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
when(denyLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID))
|
||||
.thenReturn(rateLimitBackupId ? denyLimiter : allowLimiter);
|
||||
|
||||
+40
-33
@@ -73,10 +73,13 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
@@ -109,6 +112,8 @@ public class BackupManagerTest {
|
||||
private final RemoteStorageManager remoteStorageManager = mock(RemoteStorageManager.class);
|
||||
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
|
||||
private final UUID aci = UUID.randomUUID();
|
||||
private final DynamicBackupConfiguration backupConfiguration = new DynamicBackupConfiguration(
|
||||
3, 4, 5, Duration.ofSeconds(30));
|
||||
|
||||
|
||||
private static final SecureValueRecoveryConfiguration CFG = new SecureValueRecoveryConfiguration(
|
||||
@@ -139,6 +144,12 @@ public class BackupManagerTest {
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(),
|
||||
testClock);
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getBackupConfiguration()).thenReturn(backupConfiguration);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
this.backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
backupAuthTestUtil.params,
|
||||
@@ -148,7 +159,8 @@ public class BackupManagerTest {
|
||||
remoteStorageManager,
|
||||
svrbCredentialGenerator,
|
||||
svrbClient,
|
||||
testClock);
|
||||
testClock,
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -490,7 +502,7 @@ public class BackupManagerTest {
|
||||
.map(source -> new CopyParameters(3, source, 100, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)))
|
||||
.toList();
|
||||
|
||||
final int slowIndex = BackupManager.USAGE_CHECKPOINT_COUNT - 1;
|
||||
final int slowIndex = backupConfiguration.usageCheckpointCount() - 1;
|
||||
final CompletableFuture<Void> slow = new CompletableFuture<>();
|
||||
when(remoteStorageManager.copy(eq(3), anyString(), eq(100), any(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -507,15 +519,14 @@ public class BackupManagerTest {
|
||||
|
||||
// Copying can start on the next batch of USAGE_CHECKPOINT_COUNT before the current one is done, so we should see
|
||||
// at least one usage update, and at most 2
|
||||
final UsageInfo usage = backupsDb.getMediaUsage(backupUser).join().usageInfo();
|
||||
final long bytesPerObject = COPY_ENCRYPTION_PARAM.outputSize(100);
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo()).isIn(
|
||||
new UsageInfo(
|
||||
bytesPerObject * BackupManager.USAGE_CHECKPOINT_COUNT,
|
||||
BackupManager.USAGE_CHECKPOINT_COUNT),
|
||||
bytesPerObject * backupConfiguration.usageCheckpointCount(),
|
||||
backupConfiguration.usageCheckpointCount()),
|
||||
new UsageInfo(
|
||||
2 * bytesPerObject * BackupManager.USAGE_CHECKPOINT_COUNT,
|
||||
2 * BackupManager.USAGE_CHECKPOINT_COUNT));
|
||||
2 * bytesPerObject * backupConfiguration.usageCheckpointCount(),
|
||||
2L * backupConfiguration.usageCheckpointCount()));
|
||||
|
||||
// We should still be waiting since we have a slow delete
|
||||
assertThat(future).isNotDone();
|
||||
@@ -558,6 +569,7 @@ public class BackupManagerTest {
|
||||
final List<CopyResult> results = backupManager.copyToBackup(backupUser, toCopy)
|
||||
.collectList().block();
|
||||
|
||||
assertThat(results).hasSize(3);
|
||||
assertThat(results.get(0).outcome()).isEqualTo(CopyResult.Outcome.SUCCESS);
|
||||
assertThat(results.get(1).outcome()).isEqualTo(CopyResult.Outcome.SOURCE_NOT_FOUND);
|
||||
assertThat(results.get(2).outcome()).isEqualTo(CopyResult.Outcome.SOURCE_WRONG_LENGTH);
|
||||
@@ -565,7 +577,7 @@ public class BackupManagerTest {
|
||||
// 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(toCopy.get(0).destinationObjectSize());
|
||||
.isEqualTo(toCopy.getFirst().destinationObjectSize());
|
||||
assertThat(AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_COUNT, -1L)).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@@ -590,7 +602,7 @@ public class BackupManagerTest {
|
||||
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)
|
||||
.plus(backupConfiguration.maxQuotaStaleness())
|
||||
.minus(Duration.ofSeconds(1)));
|
||||
|
||||
// Try to copy
|
||||
@@ -611,7 +623,7 @@ public class BackupManagerTest {
|
||||
// set the backupsDb to be totally 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));
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(backupConfiguration.maxQuotaStaleness()));
|
||||
|
||||
// Should recalculate quota and copy can succeed
|
||||
assertThat(copy(backupUser).outcome()).isEqualTo(CopyResult.Outcome.SUCCESS);
|
||||
@@ -619,7 +631,7 @@ public class BackupManagerTest {
|
||||
// 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));
|
||||
.isEqualTo(Instant.ofEpochSecond(0).plus(backupConfiguration.maxQuotaStaleness()));
|
||||
assertThat(info.usageInfo().bytesUsed()).isEqualTo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES);
|
||||
assertThat(info.usageInfo().numObjects()).isEqualTo(1001);
|
||||
}
|
||||
@@ -643,7 +655,7 @@ public class BackupManagerTest {
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(originalRemainingSpace, 1000)).join();
|
||||
|
||||
if (doesReaclc) {
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(BackupManager.MAX_QUOTA_STALENESS).plus(Duration.ofSeconds(1)));
|
||||
testClock.pin(Instant.ofEpochSecond(0).plus(backupConfiguration.maxQuotaStaleness()).plus(Duration.ofSeconds(1)));
|
||||
when(remoteStorageManager.calculateBytesUsed(eq(backupMediaPrefix)))
|
||||
.thenReturn(CompletableFuture.completedFuture(new UsageInfo(afterRecalcRemainingSpace, 1000)));
|
||||
}
|
||||
@@ -670,7 +682,9 @@ public class BackupManagerTest {
|
||||
backupsDb.setMediaUsage(backupUser, oldUsage).join();
|
||||
when(remoteStorageManager.calculateBytesUsed(eq(backupMediaPrefix)))
|
||||
.thenReturn(CompletableFuture.completedFuture(newUsage));
|
||||
final StoredBackupAttributes attrs = backupManager.listBackupAttributes(1, Schedulers.immediate()).single().block();
|
||||
final StoredBackupAttributes attrs = backupManager.listBackupAttributes(1)
|
||||
.single()
|
||||
.blockOptional().orElseThrow();
|
||||
|
||||
testClock.pin(Instant.ofEpochSecond(456));
|
||||
assertThat(backupManager.recalculateQuota(attrs).toCompletableFuture().join())
|
||||
@@ -738,7 +752,8 @@ public class BackupManagerTest {
|
||||
// The original prefix to expire should be flagged as requiring expiration
|
||||
final ExpiredBackup expiredBackup = backupManager
|
||||
.getExpiredBackups(1, Schedulers.immediate(), Instant.ofEpochSecond(1L))
|
||||
.collectList().block()
|
||||
.collectList()
|
||||
.blockOptional().orElseThrow()
|
||||
.getFirst();
|
||||
assertThat(expiredBackup.hashedBackupId()).isEqualTo(hashedBackupId(original.backupId()));
|
||||
assertThat(expiredBackup.prefixToDelete()).isEqualTo(original.backupDir());
|
||||
@@ -770,11 +785,6 @@ public class BackupManagerTest {
|
||||
public void deleteWrongCredentialType() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(16);
|
||||
final String backupMediaKey = "%s/%s/%s".formatted(
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
BackupManager.encodeMediaIdForCdn(mediaId));
|
||||
|
||||
assertThatThrownBy(() ->
|
||||
backupManager.deleteMedia(backupUser, List.of(new BackupManager.StorageDescriptor(5, mediaId))).then().block())
|
||||
.isInstanceOf(StatusRuntimeException.class)
|
||||
@@ -798,7 +808,7 @@ public class BackupManagerTest {
|
||||
BackupLevel.PAID);
|
||||
|
||||
// 100 objects, each 2 bytes large
|
||||
final List<byte[]> mediaIds = IntStream.range(0, 100).mapToObj(ig -> TestRandomUtil.nextBytes(16)).toList();
|
||||
final List<byte[]> mediaIds = IntStream.range(0, 100).mapToObj(_ -> TestRandomUtil.nextBytes(16)).toList();
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(200, 100)).join();
|
||||
|
||||
// One object is slow to delete
|
||||
@@ -806,7 +816,7 @@ public class BackupManagerTest {
|
||||
final String slowMediaKey = "%s/%s/%s".formatted(
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
BackupManager.encodeMediaIdForCdn(mediaIds.get(BackupManager.USAGE_CHECKPOINT_COUNT + 3)));
|
||||
BackupManager.encodeMediaIdForCdn(mediaIds.get(backupConfiguration.usageCheckpointCount() + 3)));
|
||||
|
||||
when(remoteStorageManager.delete(anyString())).thenReturn(CompletableFuture.completedFuture(2L));
|
||||
when(remoteStorageManager.delete(slowMediaKey)).thenReturn(slowFuture);
|
||||
@@ -819,21 +829,17 @@ public class BackupManagerTest {
|
||||
.toList());
|
||||
final ArrayBlockingQueue<BackupManager.StorageDescriptor> sds = new ArrayBlockingQueue<>(100);
|
||||
final CompletableFuture<Void> future = flux.doOnNext(sds::add).then().toFuture();
|
||||
for (int i = 0; i < BackupManager.USAGE_CHECKPOINT_COUNT; i++) {
|
||||
for (int i = 0; i < backupConfiguration.usageCheckpointCount(); i++) {
|
||||
sds.poll(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo())
|
||||
.isEqualTo(new UsageInfo(
|
||||
200 - (2 * BackupManager.USAGE_CHECKPOINT_COUNT),
|
||||
100 - BackupManager.USAGE_CHECKPOINT_COUNT));
|
||||
// We should still be waiting since we have a slow delete
|
||||
assertThat(future).isNotDone();
|
||||
// But we should checkpoint the usage periodically
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo())
|
||||
.isEqualTo(new UsageInfo(
|
||||
200 - (2 * BackupManager.USAGE_CHECKPOINT_COUNT),
|
||||
100 - BackupManager.USAGE_CHECKPOINT_COUNT));
|
||||
200 - (2L * backupConfiguration.usageCheckpointCount()),
|
||||
100 - backupConfiguration.usageCheckpointCount()));
|
||||
|
||||
slowFuture.complete(2L);
|
||||
future.join();
|
||||
@@ -860,7 +866,7 @@ public class BackupManagerTest {
|
||||
// fail deletion 3, otherwise return the corresponding object's size as i
|
||||
final CompletableFuture<Long> deleteResult = i == 3
|
||||
? CompletableFuture.failedFuture(new IOException("oh no"))
|
||||
: CompletableFuture.completedFuture(Long.valueOf(i));
|
||||
: CompletableFuture.completedFuture((long) i);
|
||||
|
||||
when(remoteStorageManager.delete(backupMediaKey)).thenReturn(deleteResult);
|
||||
}
|
||||
@@ -870,7 +876,8 @@ public class BackupManagerTest {
|
||||
final List<BackupManager.StorageDescriptor> deleted = backupManager
|
||||
.deleteMedia(backupUser, descriptors)
|
||||
.onErrorComplete()
|
||||
.collectList().block();
|
||||
.collectList()
|
||||
.blockOptional().orElseThrow();
|
||||
// first two objects should be deleted
|
||||
assertThat(deleted.size()).isEqualTo(2);
|
||||
assertThat(backupsDb.getMediaUsage(backupUser).join().usageInfo())
|
||||
@@ -901,7 +908,7 @@ public class BackupManagerTest {
|
||||
@Test
|
||||
public void listExpiredBackups() {
|
||||
final List<AuthenticatedBackupUser> backupUsers = IntStream.range(0, 10)
|
||||
.mapToObj(i -> backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID))
|
||||
.mapToObj(_ -> backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID))
|
||||
.toList();
|
||||
for (int i = 0; i < backupUsers.size(); i++) {
|
||||
testClock.pin(days(i));
|
||||
@@ -919,7 +926,7 @@ public class BackupManagerTest {
|
||||
final List<ExpiredBackup> expired = backupManager
|
||||
.getExpiredBackups(1, Schedulers.immediate(), day)
|
||||
.collectList()
|
||||
.block();
|
||||
.blockOptional().orElseThrow();
|
||||
|
||||
// all the backups tht should be expired at t=i should be returned (ones with expiration time 0,1,...i-1)
|
||||
assertThat(expired.size()).isEqualTo(expectedHashes.size());
|
||||
@@ -1153,7 +1160,7 @@ public class BackupManagerTest {
|
||||
* Retrieve an existing BackupUser from the database
|
||||
*/
|
||||
private AuthenticatedBackupUser retrieveBackupUser(final byte[] backupId, final BackupCredentialType credentialType, final BackupLevel backupLevel) {
|
||||
final BackupsDb.AuthenticationData authData = backupsDb.retrieveAuthenticationData(backupId).join().get();
|
||||
final BackupsDb.AuthenticationData authData = backupsDb.retrieveAuthenticationData(backupId).join().orElseThrow();
|
||||
return new AuthenticatedBackupUser(backupId, credentialType, backupLevel, authData.backupDir(), authData.mediaDir(), null);
|
||||
}
|
||||
|
||||
|
||||
@@ -236,7 +236,7 @@ public class BackupsDbTest {
|
||||
backupsDb.trackMedia(users.get(1), 10, 100).join();
|
||||
backupsDb.trackMedia(users.get(2), 1, 1000).join();
|
||||
|
||||
final List<StoredBackupAttributes> sbms = backupsDb.listBackupAttributes(1, Schedulers.immediate())
|
||||
final List<StoredBackupAttributes> sbms = backupsDb.listBackupAttributes(1)
|
||||
.sort(Comparator.comparing(StoredBackupAttributes::lastRefresh))
|
||||
.collectList()
|
||||
.block();
|
||||
|
||||
+21
@@ -182,6 +182,27 @@ public class ArchiveControllerTest {
|
||||
backupAuthTestUtil.getRequest(mediaBackupKey, aci));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"true, 0",
|
||||
"false, 1",
|
||||
"false, 12345"
|
||||
})
|
||||
public void backupIdLimits(boolean hasPermits, long waitSeconds) {
|
||||
when(backupAuthManager.checkBackupIdRotationLimit(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupAuthManager.BackupIdRotationLimit(hasPermits, Duration.ofSeconds(waitSeconds))));
|
||||
|
||||
final ArchiveController.BackupIdLimitResponse response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid/limits")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(ArchiveController.BackupIdLimitResponse.class);
|
||||
|
||||
assertThat(response.hasPermitsRemaining()).isEqualTo(hasPermits);
|
||||
assertThat(response.retryAfterSeconds()).isEqualTo(waitSeconds);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redeemReceipt() throws InvalidInputException, VerificationFailedException {
|
||||
final ServerSecretParams params = ServerSecretParams.generate();
|
||||
|
||||
+18
-13
@@ -21,15 +21,12 @@ import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.stripe.exception.ApiException;
|
||||
import com.stripe.model.PaymentIntent;
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.Clock;
|
||||
@@ -79,7 +76,8 @@ import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
@@ -95,6 +93,13 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -338,7 +343,7 @@ class SubscriptionControllerTest {
|
||||
|
||||
when(BRAINTREE_MANAGER.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
|
||||
anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new SubscriptionException.ProcessorException(PaymentProvider.BRAINTREE,
|
||||
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
|
||||
new ChargeFailure("2046", "Declined", null, null, null))));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
|
||||
@@ -417,7 +422,7 @@ class SubscriptionControllerTest {
|
||||
@Test
|
||||
void createSubscriptionProcessorDeclined() throws SubscriptionException {
|
||||
when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenThrow(new SubscriptionException.ProcessorException(PaymentProvider.STRIPE,
|
||||
.thenThrow(new SubscriptionProcessorException(PaymentProvider.STRIPE,
|
||||
new ChargeFailure("card_declined", "Insufficient funds", null, null, null)));
|
||||
|
||||
final String level = String.valueOf(levelId);
|
||||
@@ -491,9 +496,9 @@ class SubscriptionControllerTest {
|
||||
|
||||
@Test
|
||||
void stripePaymentIntentRequiresAction()
|
||||
throws SubscriptionException.InvalidArguments, SubscriptionException.ProcessorException {
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException {
|
||||
when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenThrow(new SubscriptionException.PaymentRequiresAction());
|
||||
.thenThrow(new SubscriptionPaymentRequiresActionException());
|
||||
|
||||
final String level = String.valueOf(levelId);
|
||||
final String idempotencyKey = UUID.randomUUID().toString();
|
||||
@@ -688,7 +693,7 @@ class SubscriptionControllerTest {
|
||||
"201, M4",
|
||||
})
|
||||
void setSubscriptionLevel(long levelId, String expectedProcessorId)
|
||||
throws SubscriptionException.ProcessorConflict, SubscriptionException.ProcessorException {
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
// set up record
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
@@ -735,7 +740,7 @@ class SubscriptionControllerTest {
|
||||
@MethodSource
|
||||
void setSubscriptionLevelExistingSubscription(final String existingCurrency, final long existingLevel,
|
||||
final String requestCurrency, final long requestLevel, final boolean expectUpdate)
|
||||
throws SubscriptionException.ProcessorConflict, SubscriptionException.ProcessorException {
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
// set up record
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
@@ -854,7 +859,7 @@ class SubscriptionControllerTest {
|
||||
|
||||
@Test
|
||||
public void setAppStoreTransactionId()
|
||||
throws SubscriptionException.InvalidArguments, SubscriptionException.PaymentRequired, RateLimitExceededException, SubscriptionException.NotFound {
|
||||
throws SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final String originalTxId = "aTxId";
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
@@ -1003,7 +1008,7 @@ class SubscriptionControllerTest {
|
||||
b(new ProcessorCustomer("customer", PaymentProvider.STRIPE).toDynamoBytes()),
|
||||
Subscriptions.KEY_SUBSCRIPTION_ID, s("subscriptionId"))))));
|
||||
when(STRIPE_MANAGER.getReceiptItem(any()))
|
||||
.thenThrow(new SubscriptionException.ChargeFailurePaymentRequired(
|
||||
.thenThrow(new SubscriptionChargeFailurePaymentRequiredException(
|
||||
PaymentProvider.STRIPE,
|
||||
new ChargeFailure("card_declined", "Insufficient funds", null, null, null)));
|
||||
|
||||
@@ -1027,7 +1032,7 @@ class SubscriptionControllerTest {
|
||||
@ParameterizedTest
|
||||
@CsvSource({"5, P45D", "201, P13D"})
|
||||
public void createReceiptCredential(long level, Duration expectedExpirationWindow)
|
||||
throws InvalidInputException, VerificationFailedException, SubscriptionException.ChargeFailurePaymentRequired, SubscriptionException.ReceiptRequestedForOpenPayment {
|
||||
throws InvalidInputException, VerificationFailedException, SubscriptionChargeFailurePaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
|
||||
-1
@@ -199,7 +199,6 @@ class MessagesAnonymousGrpcServiceTest extends
|
||||
.setServerTimestamp(CLOCK.millis())
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent)
|
||||
.setStory(false)
|
||||
.setContent(ByteString.copyFrom(payload));
|
||||
|
||||
if (includeReportSpamToken) {
|
||||
|
||||
+3
-3
@@ -332,12 +332,12 @@ class FaultTolerantRedisClusterClientTest {
|
||||
final LettuceShardCircuitBreaker.ChannelCircuitBreakerHandler channelCircuitBreakerHandler =
|
||||
ctx.channel().pipeline().get(LettuceShardCircuitBreaker.ChannelCircuitBreakerHandler.class);
|
||||
|
||||
urisToChannelBreakers.computeIfAbsent(getRedisURI(ctx.channel()), ignored -> new HashSet<>())
|
||||
urisToChannelBreakers.computeIfAbsent(getRedisURI(remoteAddress), ignored -> new HashSet<>())
|
||||
.add(channelCircuitBreakerHandler);
|
||||
}
|
||||
|
||||
private static RedisURI getRedisURI(Channel channel) {
|
||||
final InetSocketAddress inetAddress = (InetSocketAddress) channel.remoteAddress();
|
||||
private static RedisURI getRedisURI(SocketAddress remoteAddress) {
|
||||
final InetSocketAddress inetAddress = (InetSocketAddress) remoteAddress;
|
||||
return RedisURI.create(inetAddress.getHostString(), inetAddress.getPort());
|
||||
}
|
||||
|
||||
|
||||
@@ -495,6 +495,10 @@ class AccountsTest {
|
||||
final UUID existingPni = UUID.randomUUID();
|
||||
final Account existingAccount = generateAccount(e164, existingUuid, existingPni, List.of(device));
|
||||
|
||||
// Backup vouchers should be carried over accross re-registration
|
||||
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
|
||||
existingAccount.setBackupVoucher(bv);
|
||||
|
||||
createAccount(existingAccount);
|
||||
|
||||
final byte[] usernameHash = TestRandomUtil.nextBytes(32);
|
||||
@@ -531,6 +535,8 @@ class AccountsTest {
|
||||
assertThat(result.getEncryptedUsername()).isEmpty();
|
||||
assertArrayEquals(result.getReservedUsernameHash().orElseThrow(), usernameHash);
|
||||
|
||||
assertThat(result.getBackupVoucher()).isEqualTo(bv);
|
||||
|
||||
// should keep the same usernameLink, now encryptedUsername should be set
|
||||
accounts.confirmUsernameHash(result, usernameHash, encryptedUsername).join();
|
||||
item = readAccount(existingUuid);
|
||||
|
||||
-1
@@ -181,7 +181,6 @@ public class ChangeNumberManagerTest {
|
||||
.setUpdatedPni(updatedPhoneNumberIdentifiersByAccount.get(account).toString())
|
||||
.setUrgent(true)
|
||||
.setEphemeral(false)
|
||||
.setStory(false)
|
||||
.build();
|
||||
|
||||
verify(messageSender).sendMessages(argThat(a -> a.getIdentifier(IdentityType.ACI).equals(aci)),
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class FoundationDbClusterExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private FoundationDbDatabaseLifecycleManager[] databaseLifecycleManagers;
|
||||
private Database[] databases;
|
||||
|
||||
public FoundationDbClusterExtension(final int numInstances) {
|
||||
this.databaseLifecycleManagers = new FoundationDbDatabaseLifecycleManager[numInstances];
|
||||
this.databases = new Database[numInstances];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeAll(final ExtensionContext context) throws IOException {
|
||||
if (databaseLifecycleManagers[0] == null) {
|
||||
final String serviceContainerNamePrefix = System.getProperty("foundationDb.serviceContainerNamePrefix");
|
||||
|
||||
for (int i = 0; i < databaseLifecycleManagers.length; i++) {
|
||||
final FoundationDbDatabaseLifecycleManager databaseLifecycleManager = serviceContainerNamePrefix != null
|
||||
? new ServiceContainerFoundationDbDatabaseLifecycleManager(serviceContainerNamePrefix + i)
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
databaseLifecycleManagers[i] = databaseLifecycleManager;
|
||||
databases[i] = databaseLifecycleManager.getDatabase();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public Database[] getDatabases() {
|
||||
return databases;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Throwable {
|
||||
if (databaseLifecycleManagers[0] != null) {
|
||||
for (final FoundationDbDatabaseLifecycleManager databaseLifecycleManager : databaseLifecycleManagers) {
|
||||
databaseLifecycleManager.closeDatabase();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
public class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private static FoundationDbDatabaseLifecycleManager databaseLifecycleManager;
|
||||
|
||||
@Override
|
||||
public void beforeAll(final ExtensionContext context) throws IOException {
|
||||
if (databaseLifecycleManager == null) {
|
||||
final String serviceContainerName = System.getProperty("foundationDb.serviceContainerName");
|
||||
|
||||
databaseLifecycleManager = serviceContainerName != null
|
||||
? new ServiceContainerFoundationDbDatabaseLifecycleManager(serviceContainerName)
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
|
||||
context.getRoot().getStore(ExtensionContext.Namespace.GLOBAL).put(getClass().getName(), this);
|
||||
}
|
||||
}
|
||||
|
||||
public Database getDatabase() {
|
||||
return databaseLifecycleManager.getDatabase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Throwable {
|
||||
if (databaseLifecycleManager != null) {
|
||||
databaseLifecycleManager.closeDatabase();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
public class FoundationDbTest {
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbExtension FOUNDATION_DB_EXTENSION = new FoundationDbExtension();
|
||||
|
||||
@Test
|
||||
void setGetValue() {
|
||||
final byte[] key = "test".getBytes(StandardCharsets.UTF_8);
|
||||
final byte[] value = TestRandomUtil.nextBytes(16);
|
||||
|
||||
FOUNDATION_DB_EXTENSION.getDatabase().run(transaction -> {
|
||||
transaction.set(key, value);
|
||||
return null;
|
||||
});
|
||||
|
||||
final byte[] retrievedValue = FOUNDATION_DB_EXTENSION.getDatabase().run(transaction -> transaction.get(key).join());
|
||||
|
||||
assertArrayEquals(value, retrievedValue);
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -152,15 +152,17 @@ class MessagesManagerTest {
|
||||
final boolean isEphemeral = ThreadLocalRandom.current().nextBoolean();
|
||||
final boolean isUrgent = ThreadLocalRandom.current().nextBoolean();
|
||||
|
||||
final Envelope prototypeExpectedMessage = Envelope.newBuilder()
|
||||
final Envelope.Builder expectedEnvelopeBuilder = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp)
|
||||
.setServerTimestamp(CLOCK.millis())
|
||||
.setStory(isStory)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent)
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey))
|
||||
.build();
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
|
||||
if (isStory) {
|
||||
expectedEnvelopeBuilder.setStory(true);
|
||||
}
|
||||
final Envelope prototypeExpectedMessage = expectedEnvelopeBuilder.build();
|
||||
|
||||
assertEquals(expectedPresenceByAccountAndDeviceId,
|
||||
messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp, isStory, isEphemeral, isUrgent).join());
|
||||
|
||||
+231
-30
@@ -3,9 +3,11 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.ByteString;
|
||||
@@ -14,16 +16,21 @@ import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
@@ -35,7 +42,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@@ -43,7 +50,7 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
class FoundationDbMessageStoreTest {
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbExtension FOUNDATION_DB_EXTENSION = new FoundationDbExtension();
|
||||
static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(2);
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
@@ -52,7 +59,7 @@ class FoundationDbMessageStoreTest {
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
new Database[]{FOUNDATION_DB_EXTENSION.getDatabase()},
|
||||
FOUNDATION_DB_EXTENSION.getDatabases(),
|
||||
Executors.newVirtualThreadPerTaskExecutor(),
|
||||
CLOCK);
|
||||
}
|
||||
@@ -60,7 +67,7 @@ class FoundationDbMessageStoreTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void insert(final long presenceUpdatedBeforeSeconds, final boolean ephemeral, final boolean expectMessagesInserted,
|
||||
final boolean expectVersionstampUpdated) {
|
||||
final boolean expectVersionstampUpdated, final boolean expectPresenceState) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Byte> deviceIds = IntStream.range(Device.PRIMARY_ID, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(i -> (byte) i)
|
||||
@@ -68,15 +75,19 @@ class FoundationDbMessageStoreTest {
|
||||
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, 1, presenceUpdatedBeforeSeconds));
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Optional<Versionstamp> versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> result = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(result);
|
||||
|
||||
final Optional<Versionstamp> returnedVersionstamp = result.values().stream().findFirst()
|
||||
.flatMap(FoundationDbMessageStore.InsertResult::versionstamp);
|
||||
if (expectMessagesInserted) {
|
||||
assertTrue(versionstamp.isPresent());
|
||||
assertTrue(returnedVersionstamp.isPresent());
|
||||
assertTrue(result.values().stream().allMatch(insertResult -> returnedVersionstamp.equals(insertResult.versionstamp())));
|
||||
final Map<Byte, MessageProtos.Envelope> storedMessagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), deviceId -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(getMessageByVersionstamp(aci, deviceId, versionstamp.get()));
|
||||
return MessageProtos.Envelope.parseFrom(
|
||||
getMessageByVersionstamp(aci, deviceId, returnedVersionstamp.get()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -84,28 +95,32 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
assertEquals(messagesByDeviceId, storedMessagesByDeviceId);
|
||||
} else {
|
||||
assertTrue(versionstamp.isEmpty());
|
||||
assertTrue(result.values().stream().allMatch(insertResult -> insertResult.versionstamp().isEmpty()));
|
||||
}
|
||||
|
||||
if (expectVersionstampUpdated) {
|
||||
assertEquals(versionstamp, getMessagesAvailableWatch(aci),
|
||||
final Optional<Versionstamp> messagesAvailableWatchVersionstamp = getMessagesAvailableWatch(aci);
|
||||
assertTrue(messagesAvailableWatchVersionstamp.isPresent());
|
||||
assertEquals(returnedVersionstamp, messagesAvailableWatchVersionstamp,
|
||||
"messages available versionstamp should be the versionstamp of the last insert transaction");
|
||||
} else {
|
||||
assertTrue(getMessagesAvailableWatch(aci).isEmpty());
|
||||
}
|
||||
|
||||
assertTrue(result.values().stream().allMatch(insertResult -> insertResult.present() == expectPresenceState));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> insert() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Non-ephemeral messages with all devices online",
|
||||
10L, false, true, true),
|
||||
10L, false, true, true, true),
|
||||
Arguments.argumentSet(
|
||||
"Ephemeral messages with presence updated exactly at the second before which the device would be considered offline",
|
||||
300L, true, true, true),
|
||||
300L, true, true, true, true),
|
||||
Arguments.argumentSet("Non-ephemeral messages for with all devices offline",
|
||||
310L, false, true, false),
|
||||
310L, false, true, false, false),
|
||||
Arguments.argumentSet("Ephemeral messages with all devices offline",
|
||||
310L, true, false, false)
|
||||
310L, true, false, false, false)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -113,10 +128,15 @@ class FoundationDbMessageStoreTest {
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
final Optional<Versionstamp> secondMessageVersionstamp = foundationDbMessageStore.insert(aci,
|
||||
foundationDbMessageStore.insert(Map.of(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false)))).join();
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> secondMessageInsertResult = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
assertEquals(secondMessageVersionstamp, getMessagesAvailableWatch(aci));
|
||||
|
||||
final Optional<Versionstamp> messagesAvailableWatchVersionstamp = getMessagesAvailableWatch(aci);
|
||||
assertTrue(messagesAvailableWatchVersionstamp.isPresent());
|
||||
assertEquals(
|
||||
secondMessageInsertResult.get(Device.PRIMARY_ID).versionstamp(),
|
||||
messagesAvailableWatchVersionstamp);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -130,24 +150,29 @@ class FoundationDbMessageStoreTest {
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Optional<Versionstamp> versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
assertTrue(versionstamp.isPresent(),
|
||||
"versionstamp should be present since at least one message should be inserted");
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> result = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(result);
|
||||
final Optional<Versionstamp> returnedVersionstamp = result.get(Device.PRIMARY_ID).versionstamp();
|
||||
assertTrue(returnedVersionstamp.isPresent(),
|
||||
"versionstamp should be present for online device");
|
||||
|
||||
assertArrayEquals(
|
||||
messagesByDeviceId.get(Device.PRIMARY_ID).toByteArray(),
|
||||
getMessageByVersionstamp(aci, Device.PRIMARY_ID, versionstamp.get()),
|
||||
getMessageByVersionstamp(aci, Device.PRIMARY_ID, returnedVersionstamp.get()),
|
||||
"Message for primary should always be stored since it has a recently updated presence");
|
||||
|
||||
if (ephemeral) {
|
||||
assertTrue(IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(deviceId -> getMessageByVersionstamp(aci, (byte) deviceId, versionstamp.get()))
|
||||
.mapToObj(deviceId -> getMessageByVersionstamp(aci, (byte) deviceId, returnedVersionstamp.get()))
|
||||
.allMatch(Objects::isNull), "Ephemeral messages for non-present devices must not be stored");
|
||||
assertTrue(IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(deviceId -> result.get((byte) deviceId).versionstamp())
|
||||
.allMatch(Optional::isEmpty),
|
||||
"Unexpected versionstamp found for one or more devices that didn't have any messages inserted");
|
||||
} else {
|
||||
IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID)
|
||||
.forEach(deviceId -> {
|
||||
final byte[] messageBytes = getMessageByVersionstamp(aci, (byte) deviceId, versionstamp.get());
|
||||
final byte[] messageBytes = getMessageByVersionstamp(aci, (byte) deviceId, returnedVersionstamp.get());
|
||||
assertEquals(messagesByDeviceId.get((byte) deviceId).toByteArray(), messageBytes,
|
||||
"Non-ephemeral messages must always be stored");
|
||||
});
|
||||
@@ -169,23 +194,184 @@ class FoundationDbMessageStoreTest {
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(5))), true),
|
||||
Arguments.argumentSet("Presence updated same second as current time",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(0))), true),
|
||||
Arguments.argumentSet("Presence updated exactly at the second before which it would have been considered offline",
|
||||
Arguments.argumentSet(
|
||||
"Presence updated exactly at the second before which it would have been considered offline",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(300))), true),
|
||||
Arguments.argumentSet("Presence expired",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(400))), false)
|
||||
);
|
||||
}
|
||||
|
||||
/// Represents a cohort of recipients with the same config
|
||||
record MultiRecipientTestConfig(int shardNum, int numRecipients, boolean devicePresent,
|
||||
boolean generateEphemeralMessages, boolean expectMessagesInserted) {}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void insertMultiRecipient(final List<MultiRecipientTestConfig> testConfigs, final DataSize contentSize,
|
||||
final int[] expectedNumTransactionsByShard) {
|
||||
// Generate a list of ACIs for each test config
|
||||
final List<List<AciServiceIdentifier>> acisByConfig = testConfigs.stream()
|
||||
.map(testConfig -> IntStream.range(0, testConfig.numRecipients())
|
||||
.mapToObj(_ -> generateRandomAciForShard(testConfig.shardNum()))
|
||||
.toList())
|
||||
.toList();
|
||||
|
||||
// Generate MRM bundles for each ACI, for each test config. Later, we'll assert if the stored messages (if expected)
|
||||
// are the same as those we generated.
|
||||
final List<Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> mrmByConfig = IntStream.range(0,
|
||||
testConfigs.size())
|
||||
.mapToObj(i -> {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig testConfig = testConfigs.get(i);
|
||||
return acis.stream()
|
||||
.collect(Collectors.toMap(
|
||||
Function.identity(),
|
||||
_ -> Map.of(Device.PRIMARY_ID,
|
||||
generateRandomMessage(testConfig.generateEphemeralMessages(), (int) contentSize.toBytes()))));
|
||||
|
||||
})
|
||||
.toList();
|
||||
|
||||
// Create the consolidated MRM bundle by ACI.
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> mrmBundle = new HashMap<>();
|
||||
mrmByConfig.forEach(mrmBundle::putAll);
|
||||
|
||||
// Write a presence key for the cohort of recipients if the config indicates that the device must be present.
|
||||
for (int i = 0; i < testConfigs.size(); i++) {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig testConfig = testConfigs.get(i);
|
||||
if (testConfig.devicePresent()) {
|
||||
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L));
|
||||
}
|
||||
}
|
||||
|
||||
final Map<AciServiceIdentifier, Map<Byte, FoundationDbMessageStore.InsertResult>> result = foundationDbMessageStore.insert(mrmBundle).join();
|
||||
assertNotNull(result);
|
||||
|
||||
// Compute the set of versionstamps by shard number from the individual device insert results, so that we can
|
||||
// assert that each shard has the expected number of committed transactions.
|
||||
final Map<Integer, Set<Versionstamp>> returnedVersionstampsByShard = new HashMap<>();
|
||||
result.forEach((aci, deviceResults) -> {
|
||||
final int shardNum = foundationDbMessageStore.hashAciToShardNumber(aci);
|
||||
final Set<Versionstamp> versionstampSet = returnedVersionstampsByShard.computeIfAbsent(shardNum, _ -> new HashSet<>());
|
||||
deviceResults.forEach((_, deviceResult) -> deviceResult.versionstamp().ifPresent(versionstampSet::add));
|
||||
});
|
||||
|
||||
final int[] returnedNumVersionstampsByShard = new int[FOUNDATION_DB_EXTENSION.getDatabases().length];
|
||||
for (int i = 0; i < returnedNumVersionstampsByShard.length; i++) {
|
||||
returnedNumVersionstampsByShard[i] = returnedVersionstampsByShard.getOrDefault(i, Collections.emptySet()).size();
|
||||
}
|
||||
|
||||
assertArrayEquals(expectedNumTransactionsByShard, returnedNumVersionstampsByShard);
|
||||
|
||||
// For each cohort of recipients, check whether the stored messages (if expected) are the same as those we inserted
|
||||
// and whether the returned device presence states are the same as the configured states.
|
||||
IntStream.range(0, testConfigs.size()).forEach(i -> {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig shardConfig = testConfigs.get(i);
|
||||
if (shardConfig.expectMessagesInserted()) {
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> storedMrmBundle = acis.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), aci -> {
|
||||
final List<KeyValue> items = getItemsInDeviceQueue(aci, Device.PRIMARY_ID);
|
||||
assertEquals(1, items.size());
|
||||
try {
|
||||
final MessageProtos.Envelope envelope = MessageProtos.Envelope.parseFrom(items.getFirst().getValue());
|
||||
return Map.of(Device.PRIMARY_ID, envelope);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
assertEquals(mrmByConfig.get(i), storedMrmBundle,
|
||||
"Stored message bundle does not match inserted message bundle");
|
||||
} else {
|
||||
assertEquals(0, acis
|
||||
.stream()
|
||||
.mapToInt(aci -> getItemsInDeviceQueue(aci, Device.PRIMARY_ID).size())
|
||||
.sum(), "Unexpected messages found in device queue");
|
||||
}
|
||||
|
||||
assertTrue(acis
|
||||
.stream()
|
||||
.allMatch(
|
||||
aci -> result.get(aci).get(Device.PRIMARY_ID).present() == shardConfig.devicePresent()),
|
||||
"Device presence state from insert result does not match expected state");
|
||||
});
|
||||
}
|
||||
|
||||
static Stream<Arguments> insertMultiRecipient() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Multiple recipients on a single shard should result in a single transaction",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, true, false, true)),
|
||||
DataSize.bytes(128), new int[] {1, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard exceeding the transaction limit should be broken up into multiple transactions",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 15, true, false, true)),
|
||||
DataSize.kilobytes(90), new int[] {2, 0}),
|
||||
Arguments.argumentSet("Multiple recipients on different shards should result in multiple transactions",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, true, false, true),
|
||||
new MultiRecipientTestConfig(1, 5, true, false, true)),
|
||||
DataSize.bytes(128), new int[] {1, 1}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on different shards each exceeding the transaction limit should be broken up into multiple transactions on each shard",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 15, true, false, true),
|
||||
new MultiRecipientTestConfig(1, 15, true, false, true)),
|
||||
DataSize.kilobytes(90), new int[] {2, 2}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard with ephemeral messages and no devices present should result in no transactions committed",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, false, true, false)),
|
||||
DataSize.bytes(128), new int[] {0, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on different shards with ephemeral messages and no devices present should result in no transactions committed",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, false, true, false),
|
||||
new MultiRecipientTestConfig(1, 5, false, true, false)),
|
||||
DataSize.bytes(128), new int[] {0, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on two shards with one shard having no devices present should result in only one transaction",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 5, false, true, false),
|
||||
new MultiRecipientTestConfig(1, 5, true, true, true)),
|
||||
DataSize.bytes(128), new int[] {0, 1}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard with some recipients having no devices present should result in only one transaction",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 3, false, true, false),
|
||||
new MultiRecipientTestConfig(0, 3, true, true, true)),
|
||||
DataSize.bytes(128), new int[] {1, 0}),
|
||||
Arguments.argumentSet(
|
||||
"Multiple recipients on a single shard with total size just exceeding 2 chunks should result in 3 transactions",
|
||||
List.of(
|
||||
new MultiRecipientTestConfig(0, 23, true, false, true)),
|
||||
DataSize.kilobytes(90), new int[] {3, 0})
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertEmptyBundle() {
|
||||
assertThrows(IllegalArgumentException.class, () -> foundationDbMessageStore.insert(
|
||||
Map.of(generateRandomAciForShard(0), Collections.emptyMap())));
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
|
||||
return generateRandomMessage(ephemeral, 16);
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(contentSize)))
|
||||
.setEphemeral(ephemeral)
|
||||
.build();
|
||||
}
|
||||
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId,
|
||||
final Versionstamp versionstamp) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase().read(transaction -> {
|
||||
return foundationDbMessageStore.getShardForAci(aci).read(transaction -> {
|
||||
final byte[] key = foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
|
||||
.pack(Tuple.from(versionstamp));
|
||||
return transaction.get(key);
|
||||
@@ -193,7 +379,7 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
|
||||
private Optional<Versionstamp> getMessagesAvailableWatch(final AciServiceIdentifier aci) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase()
|
||||
return foundationDbMessageStore.getShardForAci(aci)
|
||||
.read(transaction -> transaction.get(foundationDbMessageStore.getMessagesAvailableWatchKey(aci))
|
||||
.thenApply(value -> value == null ? null : Tuple.fromBytes(value).getVersionstamp(0))
|
||||
.thenApply(Optional::ofNullable))
|
||||
@@ -202,7 +388,7 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci, final byte deviceId, final int serverId,
|
||||
final long secondsBeforeCurrentTime) {
|
||||
FOUNDATION_DB_EXTENSION.getDatabase().run(transaction -> {
|
||||
foundationDbMessageStore.getShardForAci(aci).run(transaction -> {
|
||||
final byte[] presenceKey = foundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final long presenceUpdateEpochSeconds = getEpochSecondsBeforeClock(secondsBeforeCurrentTime);
|
||||
final long presenceValue = constructPresenceValue(serverId, presenceUpdateEpochSeconds);
|
||||
@@ -219,4 +405,19 @@ class FoundationDbMessageStoreTest {
|
||||
return (long) (serverId & 0x0ffff) << 48 | (presenceUpdateEpochSeconds & 0x0000ffffffffffffL);
|
||||
}
|
||||
|
||||
private AciServiceIdentifier generateRandomAciForShard(final int shardNumber) {
|
||||
assert shardNumber < FOUNDATION_DB_EXTENSION.getDatabases().length;
|
||||
while (true) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
if (foundationDbMessageStore.hashAciToShardNumber(aci) == shardNumber) {
|
||||
return aci;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<KeyValue> getItemsInDeviceQueue(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return foundationDbMessageStore.getShardForAci(aci).readAsync(transaction -> AsyncUtil.collect(transaction.getRange(
|
||||
foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId).range()))).join();
|
||||
}
|
||||
|
||||
}
|
||||
+2
-7
@@ -34,16 +34,11 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
|
||||
class AppleAppStoreManagerTest {
|
||||
|
||||
@@ -101,7 +96,7 @@ class AppleAppStoreManagerTest {
|
||||
public void generateReceiptExpired()
|
||||
throws VerificationException, APIException, IOException {
|
||||
mockSubscription(Status.EXPIRED, AutoRenewStatus.ON);
|
||||
assertThatExceptionOfType(SubscriptionException.PaymentRequired.class)
|
||||
assertThatExceptionOfType(SubscriptionPaymentRequiredException.class)
|
||||
.isThrownBy(() -> appleAppStoreManager.getReceiptItem(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
@@ -196,7 +191,7 @@ class AppleAppStoreManagerTest {
|
||||
@EnumSource(mode = EnumSource.Mode.EXCLUDE, names = {"EXPIRED", "REVOKED"})
|
||||
public void cancelFailsForActiveSubscription(Status status) throws APIException, VerificationException, IOException {
|
||||
mockSubscription(status, AutoRenewStatus.ON);
|
||||
assertThatExceptionOfType(SubscriptionException.InvalidArguments.class)
|
||||
assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class)
|
||||
.isThrownBy(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
|
||||
+4
-5
@@ -41,7 +41,6 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
|
||||
@@ -133,7 +132,7 @@ class GooglePlayBillingManagerTest {
|
||||
switch (subscriptionState) {
|
||||
case ACTIVE, IN_GRACE_PERIOD, CANCELED -> assertThatNoException()
|
||||
.isThrownBy(() -> googlePlayBillingManager.validateToken(PURCHASE_TOKEN));
|
||||
default -> assertThatExceptionOfType(SubscriptionException.PaymentRequired.class)
|
||||
default -> assertThatExceptionOfType(SubscriptionPaymentRequiredException.class)
|
||||
.isThrownBy(() -> googlePlayBillingManager.validateToken(PURCHASE_TOKEN));
|
||||
}
|
||||
}
|
||||
@@ -234,7 +233,7 @@ class GooglePlayBillingManagerTest {
|
||||
// next second should be expired
|
||||
clock.setTimeInstant(day10.plus(Duration.ofSeconds(1)));
|
||||
|
||||
assertThatExceptionOfType(SubscriptionException.PaymentRequired.class)
|
||||
assertThatExceptionOfType(SubscriptionPaymentRequiredException.class)
|
||||
.isThrownBy(() -> googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN));
|
||||
}
|
||||
|
||||
@@ -272,8 +271,8 @@ class GooglePlayBillingManagerTest {
|
||||
|
||||
public static Stream<Arguments> tokenErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(404, SubscriptionException.NotFound.class),
|
||||
Arguments.of(410, SubscriptionException.NotFound.class),
|
||||
Arguments.of(404, SubscriptionNotFoundException.class),
|
||||
Arguments.of(410, SubscriptionNotFoundException.class),
|
||||
Arguments.of(400, HttpResponseException.class)
|
||||
);
|
||||
}
|
||||
|
||||
+1
-10
@@ -8,18 +8,11 @@ package org.whispersystems.textsecuregcm.subscriptions;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.braintreegateway.BraintreeGateway;
|
||||
import com.braintreegateway.Customer;
|
||||
import com.braintreegateway.CustomerGateway;
|
||||
import com.google.cloud.pubsub.v1.Publisher;
|
||||
import com.stripe.StripeClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
@@ -32,8 +25,6 @@ import com.stripe.service.SubscriptionService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionException;
|
||||
|
||||
class StripeManagerTest {
|
||||
|
||||
@@ -67,7 +58,7 @@ class StripeManagerTest {
|
||||
|
||||
when(subscriptionService.create(any(), any())).thenThrow(stripeException);
|
||||
when(stripeClient.subscriptions()).thenReturn(subscriptionService);
|
||||
assertThatExceptionOfType(SubscriptionException.PaymentRequiresAction.class).isThrownBy(() ->
|
||||
assertThatExceptionOfType(SubscriptionPaymentRequiresActionException.class).isThrownBy(() ->
|
||||
stripeManager.createSubscription("customerId", "priceId", 1, 0));
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.google.api.services.androidpublisher.model.Money;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.assertj.core.data.Percentage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SubscriptionCurrencyUtilTest {
|
||||
|
||||
@Test
|
||||
void convertGoogleMoneyToApiAmount() {
|
||||
Money money = new Money();
|
||||
money.setCurrencyCode("USD");
|
||||
money.setUnits(4L);
|
||||
|
||||
BigDecimal amt = SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(money);
|
||||
Assertions.assertThat(amt).isCloseTo(BigDecimal.valueOf(400), Percentage.withPercentage(0.0001));
|
||||
|
||||
money.setNanos(990000000);
|
||||
amt = SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(money);
|
||||
Assertions.assertThat(amt).isCloseTo(BigDecimal.valueOf(499), Percentage.withPercentage(0.0001));
|
||||
|
||||
}
|
||||
}
|
||||
+3
@@ -83,6 +83,9 @@ class FinishPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
//noinspection unchecked
|
||||
|
||||
+3
@@ -65,6 +65,9 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
|
||||
+3
@@ -50,6 +50,9 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
dynamoDbRecoveryManager);
|
||||
|
||||
namespace = new Namespace(Map.of(
|
||||
|
||||
+3
@@ -72,6 +72,9 @@ class StartPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
Submodule spam-filter updated: b7f042f993...4621b845d8.
Reference in new issue
Block a user