Make sandbox sourced receipts create resricted accounts

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-10-07 14:55:33 -05:00
1 parent e6aef34398
commit 4765492415
29 files changed
+624 -124

No files matched your search

+2
View File
@@ -145,6 +145,8 @@ dynamoDbTables:
tableName: Example_RemoteConfig
reportMessage:
tableName: Example_ReportMessage
sandboxAccounts:
tableName: Example_SandboxAccounts
scheduledJobs:
tableName: Example_ScheduledJobs
expiration: P7D
@@ -287,6 +287,7 @@ import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.SandboxAccounts;
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -823,10 +824,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getRegistrationWebAuthnConfiguration().challengeTtl(),
config.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
rateLimitersCluster);
final SandboxAccounts sandboxAccounts = new SandboxAccounts(
config.getDynamoDbTables().getSandboxAccounts().getTableName(), dynamoDbClient);
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
phoneNumberRecoveryPasswordsManager, sandboxAccounts, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
webAuthnCeremonyManager, totpManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
@@ -73,6 +73,7 @@ public class DynamoDbTables {
private final TableWithExpiration registrationRecovery;
private final Table remoteConfig;
private final Table reportMessage;
private final Table sandboxAccounts;
private final TableWithExpiration scheduledJobs;
private final Table subscriptions;
private final Table verificationSessions;
@@ -104,6 +105,7 @@ public class DynamoDbTables {
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
@JsonProperty("remoteConfig") final Table remoteConfig,
@JsonProperty("reportMessage") final Table reportMessage,
@JsonProperty("sandboxAccounts") final Table sandboxAccounts,
@JsonProperty("scheduledJobs") final TableWithExpiration scheduledJobs,
@JsonProperty("subscriptions") final Table subscriptions,
@JsonProperty("verificationSessions") final Table verificationSessions) {
@@ -134,6 +136,7 @@ public class DynamoDbTables {
this.registrationRecovery = registrationRecovery;
this.remoteConfig = remoteConfig;
this.reportMessage = reportMessage;
this.sandboxAccounts = sandboxAccounts;
this.scheduledJobs = scheduledJobs;
this.subscriptions = subscriptions;
this.verificationSessions = verificationSessions;
@@ -295,6 +298,12 @@ public class DynamoDbTables {
return reportMessage;
}
@NotNull
@Valid
public Table getSandboxAccounts() {
return sandboxAccounts;
}
@NotNull
@Valid
public TableWithExpiration getScheduledJobs() {
@@ -366,7 +366,7 @@ public class RegistrationController {
}
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
if (receiptLevel != ReceiptLevel.LOGIN.getValue()) {
if (receiptLevel != ReceiptLevel.LOGIN.getValue() && receiptLevel != ReceiptLevel.LOGIN_SANDBOX.getValue()) {
throw new BadRequestException("Invalid receipt level");
}
@@ -195,6 +195,10 @@ public class AppleAppStoreClient {
}
}
Environment getDefaultEnvironment() {
return defaultEnvironment;
}
private <T> T lookupByTransactionIdInEnvironment(final Environment env, final String transactionId, final Tags errorTags, final TransactionFinder<T> lookupFunction) throws APIException, IOException {
try {
return retry.executeCallable(() -> {
@@ -171,9 +171,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
if (transaction.getRevocationDate() != null) {
throw new PurchasePaymentRequiredException(getProvider());
}
ReceiptLevel receiptLevel = getLevel(transaction);
if (receiptLevel == ReceiptLevel.LOGIN && transaction.getEnvironment() != appleAppStoreClient.getDefaultEnvironment()) {
// This is a special case: if we had to resort to the fallback environment to resolve this transaction, we should
// mark the purchase to indicate it only gets a restricted entitlement.
receiptLevel = ReceiptLevel.LOGIN_SANDBOX;
}
return new PaymentDetails(
Objects.requireNonNull(transaction.getTransactionId()),
getLevel(transaction),
receiptLevel,
Instant.ofEpochMilli(transaction.getPurchaseDate()));
}
@@ -28,6 +28,9 @@ public class LoginPurchaseManager {
@VisibleForTesting
final static Duration LOGIN_EXPIRATION = Duration.ofDays(366 * 5);
@VisibleForTesting
final static Duration SANDBOX_LOGIN_EXPIRATION = Duration.ofDays(2);
/// Construct a LoginPurchaseManager
///
/// @param oneTimePaymentProcessors The processor to use for each supported [PaymentProvider]
@@ -65,23 +68,26 @@ public class LoginPurchaseManager {
}
final PaymentDetails paymentDetails = oneTimePaymentProcessor.claimOneTimePurchase(purchaseId);
if (paymentDetails.level() != ReceiptLevel.LOGIN) {
throw new PurchaseInvalidArgumentsException("purchase was for an unexpected product");
}
final Duration expirationDuration = switch (paymentDetails.level()) {
case LOGIN -> LOGIN_EXPIRATION;
case LOGIN_SANDBOX -> SANDBOX_LOGIN_EXPIRATION;
case ONE_TIME_DONATION, ONE_TIME_GIFT_DONATION, BACKUP_FREE, BACKUP_PAID, SUBSCRIPTION_LOW, SUBSCRIPTION_MEDIUM, SUBSCRIPTION_HIGH ->
throw new PurchaseInvalidArgumentsException("purchase was for an unexpected product");
};
// Calculating the expiration from the creation date works for IAP purchases. However, for other processors, the
// creation date of the payment intent might be days before the payment actually completed. If we support non-IAP
// processors we should attempt to get the latest date. see OneTimeDonationController/OneTimeDonationsManager
final Instant expiration = paymentDetails.created().plus(LOGIN_EXPIRATION).truncatedTo(ChronoUnit.DAYS);
final Instant expireAt = paymentDetails.created().plus(expirationDuration).truncatedTo(ChronoUnit.DAYS);
try {
issuedReceiptsManager.recordOneTimeIssuance(paymentDetails.id(), paymentProvider, receiptCredentialRequest,
expiration);
expireAt);
} catch (WriteConflictException _) {
throw new PurchaseReceiptAlreadyRedeemedException();
}
return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expiration.getEpochSecond(),
ReceiptLevel.LOGIN.getValue());
return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expireAt.getEpochSecond(),
paymentDetails.level().getValue());
}
}
@@ -19,6 +19,7 @@ public enum ReceiptLevel {
BACKUP_FREE(200L),
BACKUP_PAID(201L),
LOGIN(300L),
LOGIN_SANDBOX(301L),
SUBSCRIPTION_LOW(500),
SUBSCRIPTION_MEDIUM(1000),
SUBSCRIPTION_HIGH(2000);
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
/// One of the provided transaction write items to an account creation operation failed
class AccountCreationConditionException extends Exception {
private final int index;
AccountCreationConditionException(final int index) {
this.index = index;
}
/// @return The index of the item that caused a conditional check failure
public int getIndex() {
return index;
}
}
@@ -298,11 +298,25 @@ public class Accounts {
return true;
}
/// Create an account record via a receipt presentation
///
/// @param account The account to create
/// @param receiptCredentialPresentation A presentation of a receipt credential that grants the ability to create
/// one account
/// @param accountRecoveryPasswordInRequest The account-recovery-password supplied in the request
/// @param additionalWriteItems Additional items to include in the transaction
///
/// @return true
/// @throws AccountAlreadyExistsException An account was already created using this receipt
/// @throws ReceiptAlreadyRedeemedException The receipt was already used to create an account and this creation
/// request would require a new account
/// @throws AccountCreationConditionException One of the conditions in `additionalWriteItems` failed. The exception
/// contains the index of the [TransactWriteItem] that failed
boolean create(final Account account,
final ReceiptCredentialPresentation receiptCredentialPresentation,
final byte[] accountRecoveryPasswordInRequest,
final List<TransactWriteItem> additionalWriteItems)
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException, AccountCreationConditionException {
final Timer.Sample sample = Timer.start();
@@ -320,6 +334,7 @@ public class Accounts {
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
List.of(signalLoginReceiptConstraintPut, accountPut));
final int additionalWriteItemsStart = writeItems.size();
writeItems.addAll(additionalWriteItems);
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
@@ -358,7 +373,18 @@ public class Accounts {
throw new AccountAlreadyExistsException(existingAccount);
}
for (int i = additionalWriteItemsStart; i < e.cancellationReasons().size(); i++) {
if (conditionalCheckFailed(e.cancellationReasons().get(i))) {
// Indicate the first caller-supplied TransactWriteItem that failed
throw new AccountCreationConditionException(i - additionalWriteItemsStart);
}
}
final CancellationReason accountCancellationReason = e.cancellationReasons().get(1);
if (conditionalCheckFailed(accountCancellationReason)) {
throw new IllegalStateException("Tried to create an account with an ACI that already exists " + account.getAccountIdentifier());
}
if (TRANSACTION_CONFLICT.equals(accountCancellationReason.code())) {
// this should only happen if two clients manage to make concurrent create() calls
throw new ContestedOptimisticLockException();
@@ -1632,6 +1658,8 @@ public class Accounts {
.orElseGet(() -> Put.builder()
.tableName(accountsTableName)
.item(item)
.conditionExpression("attribute_not_exists(#uuid)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
.build());
return TransactWriteItem.builder()
@@ -86,6 +86,7 @@ import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -127,6 +128,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
name(AccountsManager.class, "registrationIdRedisKeyCounter");
private static final String CREATE_TIMER_NAME = name(AccountsManager.class, "create");
private static final String HAS_NUMBER_TAG_NAME = "hasNumber";
private static final String SANDBOX_POOL_EXHAUSTED_COUNTER_NAME =
name(AccountsManager.class, "sandboxAccountPoolExhausted");
private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class);
@@ -147,6 +150,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final DisconnectionRequestManager disconnectionRequestManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final SandboxAccounts sandboxAccounts;
private final ScheduledExecutorService messagesPollExecutor;
private final ScheduledExecutorService retryExecutor;
private final Clock clock;
@@ -289,6 +293,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static class UncheckedWebAuthnMismatchException extends NoStackTraceRuntimeException {
}
private sealed interface CreationDetails permits NumberDetails, NumberlessDetails {}
private record NumberDetails(boolean recentlyDeleted, String e164, UUID pni, IdentityKey pniIdentityKey) implements CreationDetails {}
private record NumberlessDetails(ReceiptCredentialPresentation receiptCredentialPresentation, byte[] authCredentialSalt) implements CreationDetails {}
public AccountsManager(final Accounts accounts,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final FaultTolerantRedisClusterClient cacheCluster,
@@ -302,6 +310,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final SecureValueRecoveryClient secureValueRecovery2Client,
final DisconnectionRequestManager disconnectionRequestManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final SandboxAccounts sandboxAccounts,
final ScheduledExecutorService messagesPollExecutor,
final ScheduledExecutorService retryExecutor,
final Clock clock,
@@ -321,6 +330,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.disconnectionRequestManager = disconnectionRequestManager;
this.phoneNumberRecoveryPasswordsManager = requireNonNull(phoneNumberRecoveryPasswordsManager);
this.sandboxAccounts = requireNonNull(sandboxAccounts);
this.messagesPollExecutor = messagesPollExecutor;
this.retryExecutor = retryExecutor;
this.clock = requireNonNull(clock);
@@ -394,16 +404,32 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
() -> new IllegalArgumentException("recovery password is required for accounts without phone numbers"));
// This salt is required for generating PNI-based auth credentials (e.g. group credentials) for accounts without a number
final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE];
SECURE_RANDOM.nextBytes(authCredentialSalt);
final byte[] authCredentialSalt = generateAuthCredentialSalt();
// We ignore this property on accounts without a number anyway, but ensure that it is false for consistency
accountAttributes.setDiscoverableByPhoneNumber(false);
final Timer.Sample sample = Timer.start();
final ReceiptLevel receiptLevel = ReceiptLevel.lookupLevel(receiptCredentialPresentation.getReceiptLevel())
.orElseThrow(() -> new IllegalStateException("Invalid receipt level"));
final NumberlessDetails numberlessDetails = new NumberlessDetails(receiptCredentialPresentation, authCredentialSalt);
final Timer.Sample sample = Timer.start();
try {
return create(Optional.empty(), Optional.empty(), Optional.of(receiptCredentialPresentation), Optional.of(authCredentialSalt), accountAttributes, aciIdentityKey, Optional.empty(), primaryDeviceSpec, userAgent);
return switch (receiptLevel) {
case LOGIN -> {
final UUID aci = UUID.randomUUID();
final List<TransactWriteItem> additionalWriteItems = keysWriteItems(aci, Optional.empty(), primaryDeviceSpec);
yield create(aci, numberlessDetails, accountAttributes, aciIdentityKey, primaryDeviceSpec, additionalWriteItems, userAgent);
}
case LOGIN_SANDBOX ->
createSandboxAccount(accountAttributes, aciIdentityKey, primaryDeviceSpec, numberlessDetails, userAgent);
default -> throw new IllegalStateException(
"Invalid receipt level: " + receiptCredentialPresentation.getReceiptLevel());
};
} catch (final AccountCreationConditionException e) {
logger.error("Unexpected condition exception while creating account", e);
throw new IllegalStateException(e);
} catch (final RuntimeException e) {
logger.error("Unexpected exception while creating account", e);
throw e;
@@ -429,49 +455,87 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final DeviceSpec primaryDeviceSpec,
@Nullable final String userAgent) {
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
final Timer.Sample sample = Timer.start();
try {
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
return accountLockManager.withLock(Set.of(pni), () -> {
try {
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is re-registering
final Optional<UUID> recentlyDeletedAci = findRecentlyDeletedAccountIdentifier(pni);
final UUID aci = recentlyDeletedAci.orElseGet(UUID::randomUUID);
return Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "true").record(() -> {
try {
return accountLockManager.withLock(Set.of(pni),
() -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent));
} catch (final ReceiptAlreadyRedeemedException e) {
throw new AssertionError("ReceiptAlreadyRedeemedException must never be thrown for accounts with numbers");
} catch (final RuntimeException e) {
logger.error("Unexpected exception while creating account", e);
throw e;
}
});
final NumberDetails numberDetails =
new NumberDetails(recentlyDeletedAci.isPresent(), number, pni, pniIdentityKey);
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysWriteItems(aci, Optional.of(pni), primaryDeviceSpec));
accountAttributes.recoveryPassword()
.map(phoneNumberRecoveryPassword ->
phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(pni, phoneNumberRecoveryPassword))
.ifPresent(additionalWriteItems::add);
return create(aci, numberDetails, accountAttributes, aciIdentityKey, primaryDeviceSpec, additionalWriteItems, userAgent);
} catch (final ReceiptAlreadyRedeemedException | AccountCreationConditionException e) {
throw new IllegalStateException("unexpected exception for account with a number", e);
}
});
} catch (final RuntimeException e) {
logger.error("Unexpected exception while creating account", e);
throw e;
} finally {
sample.stop(Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "true"));
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Account create(final Optional<String> maybeNumber,
final Optional<UUID> maybePni,
final Optional<ReceiptCredentialPresentation> maybeReceiptCredentialPresentation,
final Optional<byte[]> maybeAuthCredentialSalt,
/// Create a sandbox account without a phone number. Sandbox accounts use an account identifier claimed from the
/// [SandboxAccounts] pool.
///
/// @param accountAttributes the account-level attributes to set on the account
/// @param aciIdentityKey the ACI identity key to associate with the account
/// @param primaryDeviceSpec the attributes to set on the account's primary device
/// @param numberlessDetails details specific to account-creation without a number
/// @param userAgent the user agent of the client requesting to create an account
/// @return the created account
private Account createSandboxAccount(
final AccountAttributes accountAttributes,
final IdentityKey aciIdentityKey,
final Optional<IdentityKey> maybePniIdentityKey,
final DeviceSpec primaryDeviceSpec,
final NumberlessDetails numberlessDetails,
@Nullable final String userAgent) throws ReceiptAlreadyRedeemedException {
final List<UUID> candidates = new ArrayList<>(sandboxAccounts.getAvailable());
Collections.shuffle(candidates);
assert maybeNumber.isPresent() ^ maybeReceiptCredentialPresentation.isPresent();
for (final UUID candidate : candidates) {
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>();
final int sandboxClaimIndex = additionalWriteItems.size();
additionalWriteItems.add(sandboxAccounts.buildClaimWriteItem(candidate, clock.instant()));
additionalWriteItems.addAll(keysWriteItems(candidate, Optional.empty(), primaryDeviceSpec));
try {
return create(candidate, numberlessDetails, accountAttributes, aciIdentityKey, primaryDeviceSpec,
additionalWriteItems, userAgent);
} catch (final AccountCreationConditionException e) {
// If our sandbox claim failed, another registration claimed this identifier after we listed the available
// identifiers so we can just try the next one. Otherwise, this is an unexpected condition failure.
if (e.getIndex() != sandboxClaimIndex) {
throw new IllegalStateException(e);
}
}
}
Metrics.counter(SANDBOX_POOL_EXHAUSTED_COUNTER_NAME).increment();
throw new ReceiptAlreadyRedeemedException();
}
private Account create(
final UUID aci,
final CreationDetails creationDetails,
final AccountAttributes accountAttributes,
final IdentityKey aciIdentityKey,
final DeviceSpec primaryDeviceSpec,
final List<TransactWriteItem> additionalWriteItems,
@Nullable final String userAgent) throws ReceiptAlreadyRedeemedException, AccountCreationConditionException {
final Account account = new Account();
final Optional<UUID> maybeRecentlyDeletedAccountIdentifier =
maybePni.flatMap(accounts::findRecentlyDeletedAccountIdentifier);
maybeNumber.ifPresent(number -> {
account.setNumber(number, maybePni.orElseThrow(() -> new IllegalArgumentException("PNI must be provided if the account has a number")));
account.setPhoneNumberIdentityKey(maybePniIdentityKey.orElseThrow(() -> new IllegalArgumentException("PNI identity key must be provided if the account has a number")));
account.setRegistrationLockFromAttributes(accountAttributes);
});
maybeAuthCredentialSalt.ifPresent(account::setAuthCredentialSalt);
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is
// re-registering.
account.setAccountIdentifier(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
account.setAccountIdentifier(aci);
account.setIdentityKey(aciIdentityKey);
account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock, aciIdentityKey));
account.setUnidentifiedAccessKey(accountAttributes.getUnidentifiedAccessKey());
@@ -480,48 +544,43 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
accountAttributes.recoveryPassword().ifPresent(account::setAccountRecoveryPassword);
AccountCreationType accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent()
? AccountCreationType.RECENTLY_DELETED
: AccountCreationType.NEW;
final PushTokenType pushTokenType = PushTokenType.fromDeviceSpec(primaryDeviceSpec);
@Nullable PushTokenType previousPushTokenType = null;
AccountCreationType accountCreationType;
try {
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(),
account.getPhoneNumberIdentifier(),
Device.PRIMARY_ID,
primaryDeviceSpec.aciInfo().signedPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey),
primaryDeviceSpec.aciInfo().pqLastResortPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey)));
maybePni.ifPresent(phoneNumberIdentifier ->
accountAttributes.recoveryPassword().ifPresent(phoneNumberRecoveryPassword ->
additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword))));
if (maybeNumber.isPresent()) {
if (maybeRecentlyDeletedAccountIdentifier.isPresent()) {
// If we are re-using a recently deleted ACI, also obtain a lock for it so that clearing queues for the ACI synchronize against it
accountLockManager.withLock(Set.of(maybeRecentlyDeletedAccountIdentifier.get()), () -> {
switch (creationDetails) {
case NumberDetails numbered -> {
account.setNumber(numbered.e164(), numbered.pni());
account.setPhoneNumberIdentityKey(numbered.pniIdentityKey());
account.setRegistrationLockFromAttributes(accountAttributes);
if (numbered.recentlyDeleted()) {
accountCreationType = AccountCreationType.RECENTLY_DELETED;
// If we are re-using a recently deleted ACI, also obtain a lock for it so that clearing queues for the ACI synchronize against it
accountLockManager.withLock(Set.of(aci), () -> {
accounts.create(account, additionalWriteItems);
return null;
});
} else {
accountCreationType = AccountCreationType.NEW;
accounts.create(account, additionalWriteItems);
return null;
});
} else {
accounts.create(account, additionalWriteItems);
}
}
case NumberlessDetails numberless -> {
accountCreationType = AccountCreationType.NEW;
account.setAuthCredentialSalt(numberless.authCredentialSalt());
assert accountAttributes.recoveryPassword().isPresent();
accounts.create(account,
numberless.receiptCredentialPresentation(),
accountAttributes.recoveryPassword().get(),
additionalWriteItems);
}
} else {
assert accountAttributes.recoveryPassword().isPresent();
accounts.create(account,
maybeReceiptCredentialPresentation.get(),
accountAttributes.recoveryPassword().get(),
additionalWriteItems);
}
} catch (final AccountAlreadyExistsException e) {
accountCreationType = AccountCreationType.RE_REGISTRATION;
previousPushTokenType = PushTokenType.fromDevice(e.getExistingAccount().getPrimaryDevice());
reclaimAccount(account, e.getExistingAccount(), primaryDeviceSpec, accountAttributes);
}
@@ -535,6 +594,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return account;
}
private List<TransactWriteItem> keysWriteItems(final UUID aci, final Optional<UUID> pni, final DeviceSpec primaryDeviceSpec) {
return keysManager.buildWriteItemsForNewDevice(aci,
pni,
Device.PRIMARY_ID,
primaryDeviceSpec.aciInfo().signedPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey),
primaryDeviceSpec.aciInfo().pqLastResortPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey));
}
/// Recovers (re-registers) an account with a specific identifier. Callers are responsible for checking that the end
/// user has permission to recover the account (i.e. via an account recovery password).
///
@@ -576,11 +645,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
if (maybePniIdentityKey.isPresent()) {
throw new IllegalArgumentException("PNI identity key must not be provided if existing account does not have a phone number");
}
final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE];
SECURE_RANDOM.nextBytes(authCredentialSalt);
account.setAuthCredentialSalt(authCredentialSalt);
account.setAuthCredentialSalt(generateAuthCredentialSalt());
}
account.setIdentityKey(aciIdentityKey);
@@ -2303,4 +2368,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.map(AnnotatedWebAuthnCredential.class::cast)
.toList();
}
private static byte[] generateAuthCredentialSalt() {
final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE];
SECURE_RANDOM.nextBytes(authCredentialSalt);
return authCredentialSalt;
}
}
@@ -0,0 +1,127 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.Update;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
/// The pool of account identifiers available for short-lived sandbox accounts and whether they are currently in use.
public class SandboxAccounts {
// B: uuid; primary key
static final String KEY_ACCOUNT_UUID = "U";
// N: registration timestamp in epoch seconds. Only present if there is an active account with this ACI
static final String ATTR_REGISTERED_AT = "R";
private final String tableName;
private final DynamoDbClient dynamoDbClient;
/// @param uuid the sandbox ACI
/// @param registeredAt when an account registered with this ACI, or empty if the ACI is available
public record SandboxAccountReservation(UUID uuid, Optional<Instant> registeredAt) {}
public SandboxAccounts(final String tableName, final DynamoDbClient dynamoDbClient) {
this.tableName = tableName;
this.dynamoDbClient = dynamoDbClient;
}
/// Get sandbox ACIs that no account currently holds
public List<UUID> getAvailable() {
return dynamoDbClient.scanPaginator(ScanRequest.builder()
.tableName(tableName)
.filterExpression("attribute_not_exists(#registeredAt)")
.expressionAttributeNames(Map.of("#registeredAt", ATTR_REGISTERED_AT))
.build())
.items()
.stream()
.map(item -> AttributeValues.getUUID(item, KEY_ACCOUNT_UUID, null))
.toList();
}
/// Get every ACI in the pool along with its registration timestamp, if any.
public List<SandboxAccountReservation> getAll() {
return dynamoDbClient.scanPaginator(ScanRequest.builder().tableName(tableName).build())
.items()
.stream()
.map(item -> new SandboxAccountReservation(
AttributeValues.getUUID(item, KEY_ACCOUNT_UUID, null),
AttributeValues.get(item, ATTR_REGISTERED_AT)
.map(AttributeValue::n)
.map(Long::parseLong)
.map(Instant::ofEpochSecond)))
.toList();
}
/// Build a [TransactWriteItem] that claims a pool ACI for a new account. The transaction fails if the ACI is not in
/// the pool or is already claimed.
///
/// @param uuid the pool ACI to claim
/// @param registeredAt the registration time of the new account
public TransactWriteItem buildClaimWriteItem(final UUID uuid, final Instant registeredAt) {
return TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
.updateExpression("SET #registeredAt = :registeredAt")
.conditionExpression("attribute_exists(#uuid) AND attribute_not_exists(#registeredAt)")
.expressionAttributeNames(Map.of(
"#uuid", KEY_ACCOUNT_UUID,
"#registeredAt", ATTR_REGISTERED_AT))
.expressionAttributeValues(Map.of(
":registeredAt", AttributeValues.fromLong(registeredAt.getEpochSecond())))
.build())
.build();
}
/// Mark a previously used ACI as available. The corresponding account must be deleted first.
///
/// @param uuid the ACI to release
/// @param expectedRegisteredAt the registration timestamp the caller observed
/// @return true if the registration was cleared, or false if the ACI's registration timestamp no longer matches
/// `expectedRegisteredAt`
public boolean releaseAci(final UUID uuid, final Instant expectedRegisteredAt) {
try {
dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
.updateExpression("REMOVE #registeredAt")
.conditionExpression("#registeredAt = :expectedRegisteredAt")
.expressionAttributeNames(Map.of("#registeredAt", ATTR_REGISTERED_AT))
.expressionAttributeValues(Map.of(
":expectedRegisteredAt", AttributeValues.fromLong(expectedRegisteredAt.getEpochSecond())))
.build());
return true;
} catch (final ConditionalCheckFailedException _) {
return false;
}
}
/// Add an ACI to the pool. Adding an ACI that is already in the pool has no effect.
public void add(final UUID uuid) {
try {
dynamoDbClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
.conditionExpression("attribute_not_exists(#uuid)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
.build());
} catch (final ConditionalCheckFailedException _) {
// Already in the pool
}
}
}
@@ -82,6 +82,7 @@ import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.SandboxAccounts;
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -389,10 +390,12 @@ public record CommandDependencies(
configuration.getRegistrationWebAuthnConfiguration().challengeTtl(),
configuration.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
rateLimitersCluster);
final SandboxAccounts sandboxAccounts = new SandboxAccounts(
configuration.getDynamoDbTables().getSandboxAccounts().getTableName(), dynamoDbClient);
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
phoneNumberRecoveryPasswordsManager, sandboxAccounts, messagePollExecutor,
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(),
webAuthnCeremonyManager, totpManager);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
@@ -35,6 +35,7 @@ import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -196,8 +197,12 @@ class AppleAppStoreManagerTest {
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
}
@Test
public void getPaymentDetails()
@ParameterizedTest
@CsvSource({
"PRODUCTION, LOGIN",
"SANDBOX, LOGIN_SANDBOX",
})
public void getPaymentDetails(final Environment environment, final ReceiptLevel receiptLevel)
throws APIException, IOException, VerificationException, PurchaseException, RateLimitExceededException {
when(apiClient.getTransactionInfo(TRANSACTION_ID))
.thenReturn(new TransactionInfoResponse().signedTransactionInfo(SIGNED_TX_INFO));
@@ -206,14 +211,15 @@ class AppleAppStoreManagerTest {
.productId(ONE_TIME_PRODUCT_ID)
.type(Type.CONSUMABLE)
.inAppOwnershipType(InAppOwnershipType.PURCHASED)
.purchaseDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli());
.purchaseDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli())
.environment(environment);
when(signedDataVerifier.verifyAndDecodeTransaction(SIGNED_TX_INFO)).thenReturn(payload);
{
// PURCHASED payment
final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID);
assertThat(paymentDetails.id()).isEqualTo(TRANSACTION_ID);
assertThat(paymentDetails.level()).isEqualTo(ReceiptLevel.LOGIN);
assertThat(paymentDetails.level()).isEqualTo(receiptLevel);
assertThat(paymentDetails.created()).isEqualTo(Instant.EPOCH.plus(Duration.ofDays(1)));
}
@@ -19,6 +19,8 @@ import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.signal.libsignal.zkgroup.ServerSecretParams;
@@ -63,10 +65,11 @@ class LoginPurchaseManagerTest {
new ServerZkReceiptOperations(SERVER_SECRET_PARAMS));
}
@Test
void generateReceiptSuccess() throws Exception {
@ParameterizedTest
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"LOGIN_SANDBOX", "LOGIN"})
void generateReceiptSuccess(ReceiptLevel receiptLevel) throws Exception {
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
.thenReturn(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PURCHASED_AT));
.thenReturn(new PaymentDetails(PURCHASE_ID, receiptLevel, PURCHASED_AT));
final ReceiptCredentialResponse receipt =
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest());
@@ -74,25 +77,20 @@ class LoginPurchaseManagerTest {
clientZkReceiptOperations.receiveReceiptCredential(receiptCredentialRequestContext, receipt);
final Instant expectedExpiration = PURCHASED_AT
.plus(LoginPurchaseManager.LOGIN_EXPIRATION)
.plus(switch (receiptLevel) {
case LOGIN -> LoginPurchaseManager.LOGIN_EXPIRATION;
case LOGIN_SANDBOX -> LoginPurchaseManager.SANDBOX_LOGIN_EXPIRATION;
default -> throw new IllegalStateException();
})
.truncatedTo(ChronoUnit.DAYS);
assertThat(receiptCredential.getReceiptLevel()).isEqualTo(ReceiptLevel.LOGIN.getValue());
assertThat(receiptCredential.getReceiptLevel()).isEqualTo(receiptLevel.getValue());
assertThat(receiptCredential.getReceiptExpirationTime()).isEqualTo(expectedExpiration.getEpochSecond());
verify(issuedReceiptsManager).recordOneTimeIssuance(
PURCHASE_ID, PROVIDER, receiptCredentialRequestContext.getRequest(), expectedExpiration);
}
@Test
void generateReceiptUnknownLevel() throws Exception {
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
.thenReturn(new PaymentDetails(PURCHASE_ID, null, PURCHASED_AT));
assertThatExceptionOfType(PurchaseInvalidArgumentsException.class).isThrownBy(() ->
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest()));
verifyNoInteractions(issuedReceiptsManager);
}
@Test
void generateReceiptNonLoginLevel() throws Exception {
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
@@ -55,6 +55,7 @@ import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -171,6 +172,7 @@ public class AccountCreationDeletionIntegrationTest {
svr2Client,
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
mock(SandboxAccounts.class),
executor,
executor,
CLOCK,
@@ -310,7 +312,7 @@ public class AccountCreationDeletionIntegrationTest {
final Account account = accountsManager.create(accountAttributes,
new IdentityKey(aciKeyPair.getPublicKey()),
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1),
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
new DeviceSpec(
deviceName,
password,
@@ -538,7 +540,7 @@ public class AccountCreationDeletionIntegrationTest {
: accountsManager.create(new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(),
originalRecoveryPassword),
new IdentityKey(aciKeyPair.getPublicKey()),
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
new DeviceSpec(null,
"password?",
"OWI",
@@ -684,7 +686,7 @@ public class AccountCreationDeletionIntegrationTest {
} else {
account = accountsManager.create(accountAttributes,
new IdentityKey(aciKeyPair.getPublicKey()),
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1),
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
new DeviceSpec(
deviceName,
password,
@@ -734,7 +736,7 @@ public class AccountCreationDeletionIntegrationTest {
new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), null)
.setRecoveryPassword(recoveryPassword),
aciIdentityKey,
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
new DeviceSpec(null,
password,
"OWI",
@@ -777,7 +779,7 @@ public class AccountCreationDeletionIntegrationTest {
final Account retriedAccount = accountsManager.create(accountAttributes,
aciIdentityKey,
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
new DeviceSpec(deviceName,
password,
signalAgent,
@@ -831,7 +833,7 @@ public class AccountCreationDeletionIntegrationTest {
final Account existingAccount = accountsManager.create(
new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), recoveryPassword),
aciIdentityKey,
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
new DeviceSpec(null,
password,
"OWI",
@@ -849,7 +851,7 @@ public class AccountCreationDeletionIntegrationTest {
// Using a different account recovery password should throw an exception
new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), TestRandomUtil.nextBytes(16)),
aciIdentityKey,
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
new DeviceSpec(null,
password,
"OWI",
@@ -151,6 +151,7 @@ class AccountsManagerChangeNumberIntegrationTest {
svr2Client,
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
mock(SandboxAccounts.class),
executor,
executor,
mock(Clock.class),
@@ -132,6 +132,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
mock(SecureValueRecoveryClient.class),
mock(DisconnectionRequestManager.class),
phoneNumberRecoveryPasswordsManager,
mock(SandboxAccounts.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
mock(Clock.class),
@@ -67,6 +67,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
mock(SecureValueRecoveryClient.class),
mock(DisconnectionRequestManager.class),
mock(PhoneNumberRecoveryPasswordsManager.class),
mock(SandboxAccounts.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
Clock.systemUTC(),
@@ -137,6 +137,7 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
svr2Client,
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
mock(SandboxAccounts.class),
executor,
executor,
mock(Clock.class),
@@ -89,6 +89,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
@@ -107,6 +108,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -122,6 +124,7 @@ import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class AccountsManagerTest {
@@ -146,6 +149,7 @@ class AccountsManagerTest {
private static TestClock CLOCK;
private Accounts accounts;
private SandboxAccounts sandboxAccounts;
private PhoneNumberIdentifiers phoneNumberIdentifiers;
private KeysManager keysManager;
private MessagesManager messagesManager;
@@ -173,6 +177,7 @@ class AccountsManagerTest {
@BeforeEach
void setup() throws Exception {
accounts = mock(Accounts.class);
sandboxAccounts = mock(SandboxAccounts.class);
keysManager = mock(KeysManager.class);
messagesManager = mock(MessagesManager.class);
profilesManager = mock(ProfilesManager.class);
@@ -265,6 +270,7 @@ class AccountsManagerTest {
svr2Client,
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
sandboxAccounts,
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
CLOCK,
@@ -836,7 +842,7 @@ class AccountsManagerTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void testCreateFreshAccount(final boolean hasE164)
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException, AccountCreationConditionException {
when(accounts.create(any(), any())).thenReturn(true);
final Optional<String> maybeE164 = hasE164 ? Optional.of("+18005550123") : Optional.empty();
@@ -886,12 +892,50 @@ class AccountsManagerTest {
verifyNoInteractions(profilesManager);
}
@Test
void testCreateSandboxAccount() throws Exception {
CLOCK.pin(Instant.now());
final UUID sandboxAci = UUID.randomUUID();
final TransactWriteItem claim = TransactWriteItem.builder().build();
when(sandboxAccounts.getAvailable()).thenReturn(List.of(sandboxAci));
when(sandboxAccounts.buildClaimWriteItem(sandboxAci, CLOCK.instant())).thenReturn(claim);
final Account createdAccount = createSandboxAccount(sandboxAccountAttributes());
assertEquals(sandboxAci, createdAccount.getAccountIdentifier());
assertTrue(createdAccount.getNumber().isEmpty());
assertTrue(createdAccount.getAuthCredentialSalt().isPresent());
verify(accounts).create(argThat(account -> sandboxAci.equals(account.getAccountIdentifier())), any(), any(), argThat(list -> list.contains(claim)));
verify(keysManager).buildWriteItemsForNewDevice(eq(sandboxAci), eq(Optional.empty()), eq(Device.PRIMARY_ID),
notNull(), eq(Optional.empty()), notNull(), eq(Optional.empty()));
}
@Test
void testCreateSandboxAccountIdentifierUnavailable() throws Exception {
final UUID firstAci = UUID.randomUUID();
final UUID secondAci = UUID.randomUUID();
when(sandboxAccounts.getAvailable()).thenReturn(List.of(firstAci, secondAci));
when(accounts.create(any(), any(), any(), any()))
.thenThrow(new AccountCreationConditionException(0))
.thenReturn(true);
final Account createdAccount = createSandboxAccount(sandboxAccountAttributes());
final ArgumentCaptor<Account> accountCaptor = ArgumentCaptor.forClass(Account.class);
verify(accounts, times(2)).create(accountCaptor.capture(), any(), any(), any());
final List<UUID> attemptedAcis =
accountCaptor.getAllValues().stream().map(Account::getAccountIdentifier).toList();
assertEquals(Set.of(firstAci, secondAci), Set.copyOf(attemptedAcis));
assertEquals(attemptedAcis.getLast(), createdAccount.getAccountIdentifier());
}
@ParameterizedTest
@MethodSource
void testReregisterAccount(
final Optional<String> maybeE164,
final Optional<String> maybeExistingAccountE164)
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException, AccountCreationConditionException {
final UUID existingUuid = UUID.randomUUID();
final Integer pniRegistrationId = maybeE164.isPresent() ? 2 : null;
final AccountAttributes attributes = new AccountAttributes(false, 1, pniRegistrationId, null, null, maybeE164.isPresent(), null,
@@ -1774,9 +1818,38 @@ class AccountsManagerTest {
private Account createAccount(final AccountAttributes accountAttributes) throws ReceiptAlreadyRedeemedException {
final ECKeyPair aciKeyPair = ECKeyPair.generate();
final ReceiptCredentialPresentation receiptCredentialPresentation = mock(ReceiptCredentialPresentation.class);
when(receiptCredentialPresentation.getReceiptLevel()).thenReturn(ReceiptLevel.LOGIN.getValue());
return accountsManager.create(accountAttributes,
new IdentityKey(aciKeyPair.getPublicKey()),
mock(ReceiptCredentialPresentation.class),
receiptCredentialPresentation,
new DeviceSpec(
accountAttributes.getName(),
"password",
null,
accountAttributes.getCapabilities(),
new DeviceIdentityInfo(accountAttributes.getRegistrationId(), KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)),
Optional.empty(),
accountAttributes.getFetchesMessages(),
Optional.empty(),
Optional.empty()),
null);
}
private static AccountAttributes sandboxAccountAttributes() {
return new AccountAttributes(false, 1, null, null, null, false, null, TestRandomUtil.nextBytes(16));
}
private Account createSandboxAccount(final AccountAttributes accountAttributes)
throws ReceiptAlreadyRedeemedException {
final ECKeyPair aciKeyPair = ECKeyPair.generate();
final ReceiptCredentialPresentation receiptCredentialPresentation = mock(ReceiptCredentialPresentation.class);
when(receiptCredentialPresentation.getReceiptLevel()).thenReturn(ReceiptLevel.LOGIN_SANDBOX.getValue());
return accountsManager.create(accountAttributes,
new IdentityKey(aciKeyPair.getPublicKey()),
receiptCredentialPresentation,
new DeviceSpec(
accountAttributes.getName(),
"password",
@@ -153,6 +153,7 @@ class AccountsManagerUsernameIntegrationTest {
mock(SecureValueRecoveryClient.class),
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
mock(SandboxAccounts.class),
Executors.newSingleThreadScheduledExecutor(),
Executors.newSingleThreadScheduledExecutor(),
Clock.systemUTC(),
@@ -126,12 +126,14 @@ class AccountsTest {
Tables.DELETED_ACCOUNTS,
Tables.USED_LINK_DEVICE_TOKENS,
Tables.REDEEMED_RECEIPTS,
Tables.SANDBOX_ACCOUNTS,
// This is an unrelated table used to test "tag-along" transactional updates
Tables.CLIENT_RELEASES);
private final TestClock clock = TestClock.pinned(Instant.EPOCH);
private Accounts accounts;
private SandboxAccounts sandboxAccounts;
private record UsernameConstraint(UUID accountIdentifier, boolean confirmed, Optional<Instant> expiration) {
}
@@ -157,6 +159,8 @@ class AccountsTest {
Tables.USERNAMES.tableName(),
Tables.DELETED_ACCOUNTS.tableName(),
Tables.USED_LINK_DEVICE_TOKENS.tableName());
sandboxAccounts = new SandboxAccounts(Tables.SANDBOX_ACCOUNTS.tableName(), DYNAMO_DB_EXTENSION.getDynamoDbClient());
}
@ParameterizedTest
@@ -224,17 +228,16 @@ class AccountsTest {
assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier());
}
freshUser = number != null ? createAccount(account) : createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16));
assertThat(freshUser).isTrue();
verifyStoredState(Optional.ofNullable(number), account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, number != null);
if (number != null) {
// For an account with a number only, try creating it again. Numberless accounts cannot be created with an old ACI
freshUser = createAccount(account);
assertThat(freshUser).isTrue();
verifyStoredState(Optional.ofNullable(number), account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, number != null);
assertThat(account.getPhoneNumberIdentifier()).isPresent();
assertPhoneNumberConstraintExists(number, account.getAccountIdentifier());
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().get(), account.getAccountIdentifier());
} else {
assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier());
}
}
@@ -580,8 +583,43 @@ class AccountsTest {
final Account secondAccount =
generateAccount(null, UUID.randomUUID(), null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
assertThrows(ReceiptAlreadyRedeemedException.class,
() -> accounts.create(secondAccount, receiptCredentialPresentation, accountRecoveryPassword,
Collections.emptyList()));
() -> accounts.create(secondAccount, receiptCredentialPresentation, accountRecoveryPassword, Collections.emptyList()));
}
@Test
void testCreateSandboxAccount() throws Exception {
final UUID uuid = UUID.randomUUID();
sandboxAccounts.add(uuid);
final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16);
final Account account =
generateAccount(null, uuid, null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
accounts.create(account, receiptPresentation(), accountRecoveryPassword,
List.of(sandboxAccounts.buildClaimWriteItem(uuid, clock.instant())));
assertTrue(accounts.getByAccountIdentifier(uuid).isPresent());
assertEquals(List.of(new SandboxAccounts.SandboxAccountReservation(uuid, Optional.of(clock.instant()))),
sandboxAccounts.getAll());
}
@Test
void testCreateSandboxAccountAlreadyClaimed() throws Exception {
final UUID uuid = UUID.randomUUID();
sandboxAccounts.add(uuid);
// Mark the sandbox ACI as already used
DYNAMO_DB_EXTENSION.getDynamoDbClient().transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(sandboxAccounts.buildClaimWriteItem(uuid, clock.instant()))
.build());
final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16);
final Account account =
generateAccount(null, uuid, null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
assertThrows(AccountCreationConditionException.class,
() -> accounts.create(account, receiptPresentation(), accountRecoveryPassword,
List.of(sandboxAccounts.buildClaimWriteItem(uuid, clock.instant().plusSeconds(1)))));
assertTrue(accounts.getByAccountIdentifier(uuid).isEmpty());
}
@ParameterizedTest
@@ -2430,7 +2468,7 @@ class AccountsTest {
private boolean createNumberlessAccount(final Account account, final ReceiptCredentialPresentation receiptCredentialPresentation, final byte[] accountRecoveryPassword) {
try {
return accounts.create(account, receiptCredentialPresentation, accountRecoveryPassword, Collections.emptyList());
} catch (final AccountAlreadyExistsException | ReceiptAlreadyRedeemedException e) {
} catch (final AccountAlreadyExistsException | ReceiptAlreadyRedeemedException | AccountCreationConditionException e) {
throw new IllegalStateException(e);
}
}
@@ -152,6 +152,7 @@ public class AddRemoveDeviceIntegrationTest {
svr2Client,
mock(DisconnectionRequestManager.class),
phoneNumberRecoveryPasswordsManager,
mock(SandboxAccounts.class),
scheduledExecutorService,
scheduledExecutorService,
clock,
@@ -343,6 +343,15 @@ public final class DynamoDbExtensionSchema {
.build()),
List.of(), List.of()),
SANDBOX_ACCOUNTS("sandbox_accounts_test",
SandboxAccounts.KEY_ACCOUNT_UUID,
null,
List.of(AttributeDefinition.builder()
.attributeName(SandboxAccounts.KEY_ACCOUNT_UUID)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(), List.of()),
SCHEDULED_JOBS("scheduled_jobs_test",
JobScheduler.KEY_SCHEDULER_NAME,
JobScheduler.ATTR_RUN_AT,
@@ -20,8 +20,14 @@ public class ReceiptCredentialTestUtil {
public static ReceiptCredentialPresentation receiptPresentation()
throws InvalidInputException, VerificationFailedException {
return receiptPresentation(1);
}
public static ReceiptCredentialPresentation receiptPresentation(final long receiptLevel)
throws InvalidInputException, VerificationFailedException {
return receiptPresentation(new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)), Instant.now().plus(
Duration.ofDays(30)), 1);
Duration.ofDays(30)), receiptLevel);
}
public static ReceiptCredentialPresentation receiptPresentation(final Instant expiresAt, final long receiptLevel)
@@ -0,0 +1,77 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
class SandboxAccountsTest {
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.SANDBOX_ACCOUNTS);
private SandboxAccounts sandboxAccounts;
@BeforeEach
void setUp() {
sandboxAccounts = new SandboxAccounts(Tables.SANDBOX_ACCOUNTS.tableName(), DYNAMO_DB_EXTENSION.getDynamoDbClient());
}
@Test
void addClaimRelease() {
final Instant now = Instant.now();
final UUID first = UUID.randomUUID();
final UUID second = UUID.randomUUID();
sandboxAccounts.add(first);
sandboxAccounts.add(second);
assertThat(sandboxAccounts.getAvailable()).containsExactlyInAnyOrder(first, second);
assertThat(sandboxAccounts.getAll()).containsExactlyInAnyOrder(
new SandboxAccounts.SandboxAccountReservation(first, Optional.empty()),
new SandboxAccounts.SandboxAccountReservation(second, Optional.empty()));
claim(first, now);
assertThat(sandboxAccounts.getAvailable()).containsExactly(second);
assertThat(sandboxAccounts.getAll()).containsExactlyInAnyOrder(
new SandboxAccounts.SandboxAccountReservation(first, Optional.of(now.truncatedTo(ChronoUnit.SECONDS))),
new SandboxAccounts.SandboxAccountReservation(second, Optional.empty()));
assertThat(sandboxAccounts.releaseAci(first, now.truncatedTo(ChronoUnit.SECONDS))).isTrue();
assertThat(sandboxAccounts.releaseAci(first, now.truncatedTo(ChronoUnit.SECONDS))).isFalse();
assertThat(sandboxAccounts.getAvailable()).containsExactlyInAnyOrder(first, second);
}
@Test
void claimFailure() {
final Instant now = Instant.now();
final UUID notInPool = UUID.randomUUID();
final UUID alreadyClaimed = UUID.randomUUID();
sandboxAccounts.add(alreadyClaimed);
claim(alreadyClaimed, now);
assertThrows(TransactionCanceledException.class, () -> claim(alreadyClaimed, now));
assertThrows(TransactionCanceledException.class, () -> claim(notInPool, now));
}
private void claim(final UUID aci, final Instant registeredAt) {
DYNAMO_DB_EXTENSION.getDynamoDbClient().transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(sandboxAccounts.buildClaimWriteItem(aci, registeredAt))
.build());
}
}
@@ -33,6 +33,7 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -356,7 +357,7 @@ public class AccountsHelper {
private static ReceiptCredentialPresentation generateReceiptCredentialPresentation() {
try {
return ReceiptCredentialTestUtil.receiptPresentation();
return ReceiptCredentialTestUtil.receiptPresentation(ReceiptLevel.LOGIN.getValue());
} catch (final InvalidInputException | VerificationFailedException e) {
throw new AssertionError("Failed to generate receipt credential presentation", e);
}
@@ -151,6 +151,8 @@ dynamoDbTables:
tableName: remote_config_test
reportMessage:
tableName: report_messages_test
sandboxAccounts:
tableName: sandbox_accounts_test
scheduledJobs:
tableName: scheduled_jobs_test
expiration: P7D