From 713ab0314e35b5a72669f6d761237ecadf5f4103 Mon Sep 17 00:00:00 2001 From: Ameya Lokare Date: Thu, 30 Jul 2026 21:25:41 -0700 Subject: [PATCH] Allow registration of Signal Logins --- .../org/signal/integration/Operations.java | 1 + .../java/org/signal/integration/TestUser.java | 2 +- .../textsecuregcm/WhisperServerService.java | 12 +- .../AccountIdentityResponseBuilder.java | 3 +- .../controllers/RegistrationController.java | 133 +++- .../entities/AccountAttributes.java | 9 +- .../entities/AccountIdentityResponse.java | 5 +- .../entities/PhoneVerificationRequest.java | 31 +- .../entities/RegistrationRequest.java | 38 +- .../textsecuregcm/storage/Accounts.java | 78 ++- .../storage/AccountsManager.java | 58 +- .../PhoneNumberRecoveryPasswordsManager.java | 6 +- .../ReceiptAlreadyRedeemedException.java | 12 + .../storage/RedeemedReceiptsManager.java | 43 ++ .../workers/CommandDependencies.java | 7 + .../controllers/AccountControllerTest.java | 12 +- .../RegistrationControllerTest.java | 493 ++++++++++++++- ...ccountCreationDeletionIntegrationTest.java | 186 +++++- ...ntsManagerChangeNumberIntegrationTest.java | 5 +- ...ConcurrentModificationIntegrationTest.java | 3 + ...igrateRecoveryPasswordIntegrationTest.java | 2 + .../storage/AccountsManagerTest.java | 86 ++- ...ccountsManagerUsernameIntegrationTest.java | 2 + .../textsecuregcm/storage/AccountsTest.java | 580 ++++++++++++------ .../AddRemoveDeviceIntegrationTest.java | 2 + .../storage/ReceiptCredentialTestUtil.java | 50 ++ .../tests/util/AccountsHelper.java | 12 +- 27 files changed, 1582 insertions(+), 289 deletions(-) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/ReceiptAlreadyRedeemedException.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/ReceiptCredentialTestUtil.java diff --git a/integration-tests/src/main/java/org/signal/integration/Operations.java b/integration-tests/src/main/java/org/signal/integration/Operations.java index f9b366159..99feb6327 100644 --- a/integration-tests/src/main/java/org/signal/integration/Operations.java +++ b/integration-tests/src/main/java/org/signal/integration/Operations.java @@ -96,6 +96,7 @@ public final class Operations { // register account final RegistrationRequest registrationRequest = new RegistrationRequest(null, registrationPassword, + null, accountAttributes, true, new IdentityKey(aciIdentityKeyPair.getPublicKey()), diff --git a/integration-tests/src/main/java/org/signal/integration/TestUser.java b/integration-tests/src/main/java/org/signal/integration/TestUser.java index 07c9b2b8c..52021bdea 100644 --- a/integration-tests/src/main/java/org/signal/integration/TestUser.java +++ b/integration-tests/src/main/java/org/signal/integration/TestUser.java @@ -134,7 +134,7 @@ public class TestUser { public AccountAttributes accountAttributes() { return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, - DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES) + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null) .setUnidentifiedAccessKey(unidentifiedAccessKey) .setRecoveryPassword(registrationPassword); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index c2b5a2ab7..a2eb9f838 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -542,10 +542,16 @@ public class WhisperServerService extends Application h.length > 0).orElse(null), account.getUsernameLinkHandle(), storageCapable, - new Entitlements(badges, backupEntitlement)); + new Entitlements(badges, backupEntitlement), + account.getAuthCredentialSalt().orElse(null)); } public static AccountIdentityResponse fromAccount(final Account account) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java index fa3910382..2918c5c1a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java @@ -13,6 +13,8 @@ import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.headers.Header; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @@ -34,12 +36,17 @@ import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import java.io.IOException; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Optional; import org.apache.commons.lang3.StringUtils; +import org.signal.libsignal.zkgroup.InvalidInputException; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; +import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader; @@ -49,6 +56,7 @@ import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedE import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException; import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager; import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; import org.whispersystems.textsecuregcm.entities.AccountCreationResponse; import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse; import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest; @@ -63,6 +71,10 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.DeviceCapability; import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo; import org.whispersystems.textsecuregcm.storage.DeviceSpec; +import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; +import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.util.HeaderUtils; import org.whispersystems.textsecuregcm.util.Util; @@ -85,6 +97,10 @@ public class RegistrationController { private final RegistrationLockVerificationManager registrationLockVerificationManager; private final RateLimiters rateLimiters; private final RegistrationFraudChecker registrationFraudChecker; + private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory; + private final ServerZkReceiptOperations serverZkReceiptOperations; + private final Clock clock; + private final DynamicConfigurationManager dynamicConfigurationManager; private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class); @@ -92,13 +108,21 @@ public class RegistrationController { final PhoneVerificationTokenManager phoneVerificationTokenManager, final RegistrationLockVerificationManager registrationLockVerificationManager, final RateLimiters rateLimiters, - final RegistrationFraudChecker registrationFraudChecker) { + final RegistrationFraudChecker registrationFraudChecker, + final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory, + final ServerZkReceiptOperations serverZkReceiptOperations, + final Clock clock, + final DynamicConfigurationManager dynamicConfigurationManager) { this.accounts = accounts; this.phoneVerificationTokenManager = phoneVerificationTokenManager; this.registrationLockVerificationManager = registrationLockVerificationManager; this.rateLimiters = rateLimiters; this.registrationFraudChecker = registrationFraudChecker; + this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory; + this.serverZkReceiptOperations = serverZkReceiptOperations; + this.clock = clock; + this.dynamicConfigurationManager = dynamicConfigurationManager; } @POST @@ -113,6 +137,7 @@ public class RegistrationController { 3. success \n """) @ApiResponse(responseCode = "200", description = "Account creation succeeded", useReturnTypeSchema = true) + @ApiResponse(responseCode = "400", description = "Invalid session ID or receipt credential presentation") @ApiResponse(responseCode = "401", description = "The session identified in the request is not verified") @ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password") @ApiResponse(responseCode = "409", description = "The caller has not explicitly elected to skip transferring data from another device, but a device transfer is technically possible") @@ -123,6 +148,18 @@ public class RegistrationController { description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed")) @ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet") public AccountCreationResponse register( + @Parameter( + in = ParameterIn.HEADER, + name = HttpHeaders.AUTHORIZATION, + description = """ + The basic auth header. For accounts with a phone number, the username must be the e164-formatted number that is being registered. + For accounts without a phone number, the username is ignored on a fresh registration (it must be present, however, so an arbitrary + string is acceptable). For account recovery (re-registration) by ACI, it must be set to the ACI of the account being recovered. + In all cases, the password is the password to be used for primary device authentication. + """, + required = true, + schema = @Schema(type = "string") + ) @HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader, @HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent, @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent, @@ -133,10 +170,6 @@ public class RegistrationController { final String number = authorizationHeader.getUsername(); final String password = authorizationHeader.getPassword(); - if (registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().isEmpty()) { - throw new WebApplicationException("PNI registration ID must be provided", 422); - } - if (!registrationRequest.isEverySignedKeyValid(userAgent)) { throw new WebApplicationException("Invalid signature", 422); } @@ -148,6 +181,29 @@ public class RegistrationController { throw new WebApplicationException("Missing required device capability", 499); } + final AccountCreationResponse response; + if (registrationRequest.pniIdentityKey() != null) { + response = registerAccountWithNumber(number, password, registrationRequest, requestContext, userAgent, signalAgent); + } else { + response = registerAccountWithoutNumber(password, registrationRequest, userAgent, signalAgent); + } + + return response; + } + + private AccountCreationResponse registerAccountWithNumber( + final String number, + final String password, + final RegistrationRequest registrationRequest, + final ContainerRequestContext requestContext, + final String userAgent, + final String signalAgent) + throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException { + + if (registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().isEmpty()) { + throw new WebApplicationException("PNI registration ID must be provided", 422); + } + rateLimiters.getRegistrationLimiter().validate(number); final PhoneVerificationRequest.VerificationType verificationType; @@ -245,4 +301,71 @@ public class RegistrationController { return new AccountCreationResponse(identityResponse, existingAccount.isPresent()); } + private AccountCreationResponse registerAccountWithoutNumber( + final String password, + final RegistrationRequest registrationRequest, + final String userAgent, + final String signalAgent) { + + if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) { + throw new BadRequestException("login purchases are not enabled"); + } + + if (registrationRequest.accountAttributes().recoveryPassword().isEmpty()) { + throw new WebApplicationException("Account recovery password is required", 422); + } + + final ReceiptCredentialPresentation receiptCredentialPresentation; + try { + receiptCredentialPresentation = receiptCredentialPresentationFactory + .build(registrationRequest.receiptCredentialPresentation()); + } catch (InvalidInputException _) { + throw new BadRequestException("Invalid receipt credential presentation"); + } + try { + serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation); + } catch (VerificationFailedException _) { + throw new BadRequestException("Receipt credential presentation verification failed"); + } + + final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime()); + if (clock.instant().isAfter(receiptExpiration)) { + throw new BadRequestException("Receipt is already expired"); + } + + final long receiptLevel = receiptCredentialPresentation.getReceiptLevel(); + if (receiptLevel != ReceiptLevel.LOGIN.getValue()) { + throw new BadRequestException("Invalid receipt level"); + } + + try { + final Account account = accounts.create( + registrationRequest.accountAttributes(), + Collections.emptyList(), + registrationRequest.aciIdentityKey(), + receiptCredentialPresentation, + new DeviceSpec( + registrationRequest.accountAttributes().getName(), + password, + signalAgent, + registrationRequest.accountAttributes().getCapabilities(), + new DeviceIdentityInfo(registrationRequest.accountAttributes().getRegistrationId(), registrationRequest.deviceActivationRequest() + .aciSignedPreKey(), registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()), + Optional.empty(), + registrationRequest.accountAttributes().getFetchesMessages(), + registrationRequest.deviceActivationRequest().apnToken(), + registrationRequest.deviceActivationRequest().gcmToken()), + userAgent); + + Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), + Tag.of(VERIFICATION_TYPE_TAG_NAME, registrationRequest.verificationType().name()))) + .increment(); + + final AccountIdentityResponse accountIdentityResponse = new AccountIdentityResponseBuilder(account).build(); + return new AccountCreationResponse(accountIdentityResponse, false); + } catch (ReceiptAlreadyRedeemedException _) { + throw new BadRequestException("Receipt already redeemed"); + } + } + } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountAttributes.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountAttributes.java index 90152e942..27aa63d94 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountAttributes.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountAttributes.java @@ -56,11 +56,13 @@ public class AccountAttributes { final byte[] name, final String registrationLock, final boolean discoverableByPhoneNumber, - final Set capabilities) { + final Set capabilities, + @Nullable final byte[] recoveryPassword) { this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities); this.registrationLock = registrationLock; this.discoverableByPhoneNumber = discoverableByPhoneNumber; + this.recoveryPassword = recoveryPassword; } public boolean getFetchesMessages() { @@ -128,6 +130,11 @@ public class AccountAttributes { return this; } + public AccountAttributes setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) { + this.discoverableByPhoneNumber = discoverableByPhoneNumber; + return this; + } + @AssertTrue @Schema(hidden = true) public boolean isUnrestrictedUakValid() { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountIdentityResponse.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountIdentityResponse.java index 08a1cbb7e..386a41934 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountIdentityResponse.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountIdentityResponse.java @@ -35,5 +35,8 @@ public record AccountIdentityResponse( boolean storageCapable, @Schema(description = "entitlements for this account and their current expirations") - Entitlements entitlements) { + Entitlements entitlements, + + @Schema(description = "salt to generate PNI auth credentials for accounts without a phone number; null if this account does not have a phone number") + @Nullable byte[] authCredentialSalt) { } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/PhoneVerificationRequest.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/PhoneVerificationRequest.java index b005059b0..ef4939fe5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/PhoneVerificationRequest.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/PhoneVerificationRequest.java @@ -10,31 +10,52 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.AssertTrue; import jakarta.ws.rs.ClientErrorException; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; +import org.apache.commons.lang3.ArrayUtils; import org.apache.http.HttpStatus; public interface PhoneVerificationRequest { enum VerificationType { SESSION, - RECOVERY_PASSWORD + RECOVERY_PASSWORD, + RECEIPT_CREDENTIAL } String sessionId(); byte[] recoveryPassword(); + default byte[] receiptCredentialPresentation() { + return null; + } + // for the @AssertTrue to work with bean validation, method name must follow 'isSmth()'/'getSmth()' naming convention @AssertTrue @Schema(hidden = true) default boolean isValid() { - // checking that exactly one of sessionId/recoveryPassword is non-empty - return isNotBlank(sessionId()) ^ (recoveryPassword() != null && recoveryPassword().length > 0); + // exactly one of sessionId/recoveryPassword/receiptCredentialPresentation should be present + return presentVerificationTypes().size() == 1; } default PhoneVerificationRequest.VerificationType verificationType() { - return isNotBlank(sessionId()) ? PhoneVerificationRequest.VerificationType.SESSION - : PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD; + return presentVerificationTypes().get(0); + } + + default List presentVerificationTypes() { + final List types = new ArrayList<>(1); + if (isNotBlank(sessionId())) { + types.add(VerificationType.SESSION); + } + if (ArrayUtils.isNotEmpty(recoveryPassword())) { + types.add(VerificationType.RECOVERY_PASSWORD); + } + if (ArrayUtils.isNotEmpty(receiptCredentialPresentation())) { + types.add(VerificationType.RECEIPT_CREDENTIAL); + } + return types; } default byte[] decodeSessionId() { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java index fa46e46d9..49a834962 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java @@ -22,18 +22,31 @@ import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter; public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ The ID of an existing verification session as it appears in a verification session - metadata object. Must be provided if `recoveryPassword` is not provided; must not be - provided if `recoveryPassword` is provided. + metadata object. Must be provided if `recoveryPassword` and `receiptCredentialPresentation` + are not provided; must not be provided if `recoveryPassword` or `receiptCredentialPresentation` + is provided. """) + @Nullable String sessionId, @JsonDeserialize(using = ByteArrayAdapter.Deserializing.class) @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ - A base64-encoded registration recovery password. Must be provided if `sessionId` is - not provided; must not be provided if `sessionId` is provided + A base64-encoded registration recovery password. Must be provided if `sessionId` and + `receiptCredentialPresentation` are not provided; must not be provided if `sessionId` + or `receiptCredentialPresentation` is provided. """) + @Nullable byte[] recoveryPassword, + @JsonDeserialize(using = ByteArrayAdapter.Deserializing.class) + @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ + A base64-encoded receipt credential presentation that allows for redeeming a Signal Login. + Must be provided if `sessionId` and `recoveryPassword` are not provided; + must not be provided if `sessionId` or `recoveryPassword` is provided. + """) + @Nullable + byte[] receiptCredentialPresentation, + @NotNull @Valid @Schema(requiredMode = Schema.RequiredMode.REQUIRED) @@ -58,13 +71,14 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT @JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class) IdentityKey aciIdentityKey, - @NotNull @Valid - @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """ + @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ The PNI-associated identity key for the account, encoded as a base64 string. + Must be provided for an account with a phone number. """) @JsonSerialize(using = IdentityKeyAdapter.Serializer.class) @JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class) + @Nullable IdentityKey pniIdentityKey, @NotNull @@ -75,14 +89,18 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT public boolean isEverySignedKeyValid(@Nullable final String userAgent) { if (deviceActivationRequest().aciSignedPreKey() == null || - deviceActivationRequest().pniSignedPreKey().isEmpty() || - deviceActivationRequest().aciPqLastResortPreKey() == null || - deviceActivationRequest().pniPqLastResortPreKey().isEmpty()) { + deviceActivationRequest().aciPqLastResortPreKey() == null) { + return false; + } + + final boolean allPniPresentOrAllAbsent = ((pniIdentityKey == null) == deviceActivationRequest().pniSignedPreKey().isEmpty()) + && ((pniIdentityKey == null) == deviceActivationRequest().pniPqLastResortPreKey().isEmpty()); + if (!allPniPresentOrAllAbsent) { return false; } return PreKeySignatureValidator.validatePreKeySignatures(aciIdentityKey(), List.of(deviceActivationRequest().aciSignedPreKey(), deviceActivationRequest().aciPqLastResortPreKey()), userAgent, "register") - && PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey().get(), deviceActivationRequest().pniPqLastResortPreKey().get()), userAgent, "register"); + && (pniIdentityKey == null || PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey().get(), deviceActivationRequest().pniPqLastResortPreKey().get()), userAgent, "register")); } @VisibleForTesting diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java index 601d33f93..5a5ad6797 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java @@ -36,6 +36,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.signal.libsignal.zkgroup.backups.BackupCredentialType; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.util.AsyncTimerUtil; @@ -167,6 +168,7 @@ public class Accounts { private final DynamoDbClient dynamoDbClient; private final DynamoDbAsyncClient dynamoDbAsyncClient; + private final RedeemedReceiptsManager redeemedReceiptsManager; private final String phoneNumberConstraintTableName; private final String phoneNumberIdentifierConstraintTableName; @@ -179,6 +181,7 @@ public class Accounts { final Clock clock, final DynamoDbClient dynamoDbClient, final DynamoDbAsyncClient dynamoDbAsyncClient, + final RedeemedReceiptsManager redeemedReceiptsManager, final String accountsTableName, final String phoneNumberConstraintTableName, final String phoneNumberIdentifierConstraintTableName, @@ -189,6 +192,7 @@ public class Accounts { this.clock = clock; this.dynamoDbClient = dynamoDbClient; this.dynamoDbAsyncClient = dynamoDbAsyncClient; + this.redeemedReceiptsManager = redeemedReceiptsManager; this.phoneNumberConstraintTableName = phoneNumberConstraintTableName; this.phoneNumberIdentifierConstraintTableName = phoneNumberIdentifierConstraintTableName; this.accountsTableName = accountsTableName; @@ -293,6 +297,72 @@ public class Accounts { return true; } + boolean create(final Account account, final ReceiptCredentialPresentation receiptCredentialPresentation, final + byte[] accountRecoveryPasswordInRequest, final List additionalWriteItems) + throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException { + + final Timer.Sample sample = Timer.start(); + + try { + final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier()); + + final TransactWriteItem signalLoginReceiptConstraintPut = + redeemedReceiptsManager.buildTransactWriteItemForReceipt( + receiptCredentialPresentation.getReceiptSerial(), + Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime()), + receiptCredentialPresentation.getReceiptLevel(), + account.getAccountIdentifier()); + final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, Optional.empty(), Optional.empty()); + + final Collection writeItems = new ArrayList<>( + List.of(signalLoginReceiptConstraintPut, accountPut)); + + writeItems.addAll(additionalWriteItems); + + final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder() + .transactItems(writeItems) + .build(); + + try { + dynamoDbClient.transactWriteItems(request); + } catch (final TransactionCanceledException e) { + + final CancellationReason receiptSerialConstraintCancellationReason = e.cancellationReasons().get(0); + + if (conditionalCheckFailed(receiptSerialConstraintCancellationReason)) { + final UUID existingAccountUuid = UUIDUtil.fromByteBuffer(receiptSerialConstraintCancellationReason.item() + .get(RedeemedReceiptsManager.KEY_ACCOUNT_UUID).b().asByteBuffer()); + final Account existingAccount = getByAccountIdentifier(existingAccountUuid) + // The account was already deleted, and we don't allow re-registering with the same receipt + .orElseThrow(ReceiptAlreadyRedeemedException::new); + + // If the account recovery password in the request matches the existing account, this is likely a client retry, + // and we continue to allow for idempotency, otherwise this is an attempt to double-redeem a receipt + final boolean isRetry = existingAccount.getAccountRecoveryPassword().map(arp -> + PhoneNumberRecoveryPasswordsManager.verify(arp, accountRecoveryPasswordInRequest)).orElse(false); + if (!isRetry) { + throw new ReceiptAlreadyRedeemedException(); + } + + throw new AccountAlreadyExistsException(existingAccount); + } + + final CancellationReason accountCancellationReason = e.cancellationReasons().get(1); + if (TRANSACTION_CONFLICT.equals(accountCancellationReason.code())) { + // this should only happen if two clients manage to make concurrent create() calls + throw new ContestedOptimisticLockException(); + } + + // this shouldn't happen + throw new RuntimeException("could not create account: " + extractCancellationReasonCodes(e)); + } + } finally { + sample.stop(CREATE_TIMER); + } + + return true; + } + /** * Copies over any account attributes that should be preserved when a new account reclaims an account identifier. * @@ -304,6 +374,7 @@ public class Accounts { final Collection additionalWriteItems) { if (!existingAccount.getAccountIdentifier().equals(accountToCreate.getAccountIdentifier()) || + existingAccount.getNumberOptional().isPresent() != accountToCreate.getNumberOptional().isPresent() || !existingAccount.getPhoneNumberIdentifierOptional().equals(accountToCreate.getPhoneNumberIdentifierOptional())) { log.error("Reclaimed accounts must match. Old account {}:{}:{}, New account {}:{}:{}", @@ -998,12 +1069,14 @@ public class Accounts { final Optional maybeExpectedExistingE164) { final UpdateAccountSpec base = forAccount(accountTableName, account); + final Map attrNames = new HashMap<>(base.attrNames()); final Map attrValues = new HashMap<>(base.attrValues()); final UpdateExpression updateExpression = base.updateExpression(); final List setClauses = new ArrayList<>(updateExpression.setClauses()); final String conditionExpression = account.getNumberOptional() .map(number -> { + attrNames.put("#number", ATTR_ACCOUNT_E164); attrValues.put(":number", AttributeValues.fromString(number)); setClauses.add("#number = :number"); @@ -1020,7 +1093,7 @@ public class Accounts { return new UpdateAccountSpec( base.tableName(), base.key(), - base.attrNames(), + attrNames, attrValues, new UpdateExpression(setClauses, updateExpression.addClauses(), updateExpression.removeClauses()), conditionExpression @@ -1031,7 +1104,6 @@ public class Accounts { final String accountTableName, final Account account) { final Map attrNames = new HashMap<>(Map.of( - "#number", ATTR_ACCOUNT_E164, "#data", ATTR_ACCOUNT_DATA, "#cds", ATTR_CANONICALLY_DISCOVERABLE, "#version", ATTR_VERSION)); @@ -1094,7 +1166,7 @@ public class Accounts { attrNames, attrValues, new UpdateExpression(setClauses, addClauses, removeClauses), - "attribute_exists(#number) AND #version = :version"); + "#version = :version"); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java index 2e0f4bd95..0c469e202 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -28,6 +28,7 @@ import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -62,6 +63,7 @@ import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.lang3.StringUtils; import org.signal.libsignal.protocol.IdentityKey; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager; @@ -184,6 +186,10 @@ public class AccountsManager extends RedisPubSubAdapter implemen private static final int MAX_UPDATE_ATTEMPTS = 10; + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + private static final int AUTH_CREDENTIAL_SALT_SIZE = 16; + @VisibleForTesting static final Duration LINK_DEVICE_TOKEN_EXPIRATION_DURATION = Duration.ofMinutes(10); @@ -293,6 +299,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen /// @param accountAttributes the account-level attributes to set on the account /// @param accountBadges the badges to set on the account /// @param aciIdentityKey the ACI identity key to associate with the account + /// @param receiptCredentialPresentation the receipt credential presentation of proof of payment for a Signal Login /// @param primaryDeviceSpec the attributes to set on the account's primary device /// @param userAgent the user agent of the client requesting to create an account /// @@ -300,16 +307,27 @@ public class AccountsManager extends RedisPubSubAdapter implemen public Account create(final AccountAttributes accountAttributes, final List accountBadges, final IdentityKey aciIdentityKey, + final ReceiptCredentialPresentation receiptCredentialPresentation, final DeviceSpec primaryDeviceSpec, - @Nullable final String userAgent) { - return Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "false").record(() -> { - try { - return create(Optional.empty(), Optional.empty(), accountAttributes, accountBadges, aciIdentityKey, Optional.empty(), primaryDeviceSpec, userAgent); - } catch (final RuntimeException e) { - logger.error("Unexpected exception while creating account", e); - throw e; - } - }); + @Nullable final String userAgent) throws ReceiptAlreadyRedeemedException { + + // 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); + + // 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(); + + try { + return create(Optional.empty(), Optional.empty(), Optional.of(receiptCredentialPresentation), Optional.of(authCredentialSalt), accountAttributes, accountBadges, aciIdentityKey, Optional.empty(), primaryDeviceSpec, userAgent); + } 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, "false")); + } } /// Create an account with a phone number. @@ -336,7 +354,9 @@ public class AccountsManager extends RedisPubSubAdapter implemen 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), accountAttributes, accountBadges, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent), accountLockExecutor); + () -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, accountBadges, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent), accountLockExecutor); + } 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; @@ -347,12 +367,15 @@ public class AccountsManager extends RedisPubSubAdapter implemen @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private Account create(final Optional maybeNumber, final Optional maybePni, + final Optional maybeReceiptCredentialPresentation, + final Optional maybeAuthCredentialSalt, final AccountAttributes accountAttributes, final List accountBadges, final IdentityKey aciIdentityKey, final Optional maybePniIdentityKey, final DeviceSpec primaryDeviceSpec, - @Nullable final String userAgent) { + @Nullable final String userAgent) throws ReceiptAlreadyRedeemedException { + assert maybeNumber.isPresent() ^ maybeReceiptCredentialPresentation.isPresent(); final Account account = new Account(); final Optional maybeRecentlyDeletedAccountIdentifier = maybePni.flatMap(accounts::findRecentlyDeletedAccountIdentifier); @@ -363,6 +386,8 @@ public class AccountsManager extends RedisPubSubAdapter implemen 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)); @@ -390,13 +415,20 @@ public class AccountsManager extends RedisPubSubAdapter implemen String previousPushTokenType = null; try { - accounts.create(account, keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), + final List newDeviceWriteItems = keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional(), Device.PRIMARY_ID, primaryDeviceSpec.aciInfo().signedPreKey(), primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), primaryDeviceSpec.aciInfo().pqLastResortPreKey(), - primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey))); + primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey)); + if (maybeNumber.isPresent()) { + accounts.create(account, newDeviceWriteItems); + } else { + assert accountAttributes.recoveryPassword().isPresent(); + accounts.create(account, maybeReceiptCredentialPresentation.get(), accountAttributes.recoveryPassword().get(), + newDeviceWriteItems); + } } catch (final AccountAlreadyExistsException e) { accountCreationType = "re-registration"; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java index e323ec42a..ec70e661f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/PhoneNumberRecoveryPasswordsManager.java @@ -24,7 +24,11 @@ public class PhoneNumberRecoveryPasswordsManager { public boolean verify(final UUID phoneNumberIdentifier, final byte[] password) { return phoneNumberRecoveryPasswords.lookup(phoneNumberIdentifier) - .filter(hash -> hash.verify(bytesToString(password))).isPresent(); + .filter(hash -> verify(hash, password)).isPresent(); + } + + public static boolean verify(final SaltedTokenHash saltedTokenHash, final byte[] password) { + return saltedTokenHash.verify(bytesToString(password)); } public boolean store(final UUID phoneNumberIdentifier, final byte[] password) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ReceiptAlreadyRedeemedException.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ReceiptAlreadyRedeemedException.java new file mode 100644 index 000000000..60c5e3bf5 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ReceiptAlreadyRedeemedException.java @@ -0,0 +1,12 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import org.whispersystems.textsecuregcm.util.NoStackTraceException; + +/// Indicates that a receipt credential has already been redeemed for the entitlement +public class ReceiptAlreadyRedeemedException extends NoStackTraceException { +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedeemedReceiptsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedeemedReceiptsManager.java index af5637782..ce3a86c51 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedeemedReceiptsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedeemedReceiptsManager.java @@ -17,7 +17,10 @@ import org.whispersystems.textsecuregcm.util.AttributeValues; import org.whispersystems.textsecuregcm.util.UUIDUtil; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.Put; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; +import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; @@ -96,4 +99,44 @@ public class RedeemedReceiptsManager { return ddbReceiptExpiration == receiptExpiration && ddbReceiptLevel == receiptLevel && Objects.equals(ddbAccountUuid, accountUuid); } + + /// Creates a [TransactWriteItem] that inserts the receipt into the redeemed receipts table if the receipt serial + /// mapping for the specified accountUuid doesn't already exist. If a receipt serial mapping exists for another + /// account, the enclosing transaction fails. + /// + /// @param receiptSerial The receipt serial + /// @param receiptExpiration The timestamp at which the receipt expires + /// @param receiptLevel The receipt level indicating the type of entitlement + /// @param accountUuid The account identifier + public TransactWriteItem buildTransactWriteItemForReceipt( + final ReceiptSerial receiptSerial, + final Instant receiptExpiration, + final long receiptLevel, + final UUID accountUuid) { + + return TransactWriteItem.builder() + .put(Put.builder() + .tableName(table) + .item(Map.of( + KEY_SERIAL, AttributeValues.b(receiptSerial.serialize()), + // NOTE: this differs from the expiration for other receipt types (see RedeemedReceiptsManager#put) which + // sets the expiration to now + a static expiration time. The TTL handling needs to be unified in the future. + KEY_TTL, AttributeValues.n(receiptExpiration.getEpochSecond()), + KEY_RECEIPT_EXPIRATION, AttributeValues.n(receiptExpiration.getEpochSecond()), + KEY_RECEIPT_LEVEL, AttributeValues.n(receiptLevel), + KEY_ACCOUNT_UUID, AttributeValues.b(accountUuid), + KEY_REDEMPTION_TIME, AttributeValues.n(clock.instant().getEpochSecond()))) + .conditionExpression("attribute_not_exists(#serial) OR (#account_uuid = :account_uuid AND #receipt_level = :receipt_level)") + .expressionAttributeNames(Map.of( + "#serial", KEY_SERIAL, + "#account_uuid", KEY_ACCOUNT_UUID, + "#receipt_level", KEY_RECEIPT_LEVEL)) + .expressionAttributeValues(Map.of( + ":account_uuid", AttributeValues.b(accountUuid), + ":receipt_level", AttributeValues.n(receiptLevel) + )) + .returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD) + .build()) + .build(); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index af9a98fb7..e19ebc4fa 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -75,6 +75,7 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager; import org.whispersystems.textsecuregcm.storage.ProfilesV2; import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords; import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager; +import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore; import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore; import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb; @@ -259,10 +260,16 @@ public record CommandDependencies( dynamoDbClient, clock); + RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock, + configuration.getDynamoDbTables().getRedeemedReceipts().getTableName(), + dynamoDbClient, + configuration.getDynamoDbTables().getRedeemedReceipts().getExpiration()); + Accounts accounts = new Accounts( clock, dynamoDbClient, dynamoDbAsyncClient, + redeemedReceiptsManager, configuration.getDynamoDbTables().getAccounts().getTableName(), configuration.getDynamoDbTables().getAccounts().getPhoneNumberTableName(), configuration.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java index f5f015d52..11f853c8a 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AccountControllerTest.java @@ -804,7 +804,7 @@ class AccountControllerTest { .target("/v1/accounts/attributes/") .request() .header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) - .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null) + .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null, null) .setUnidentifiedAccessKey(unidentifiedAccessKey) .setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess)))) { @@ -828,7 +828,7 @@ class AccountControllerTest { .target("/v1/accounts/attributes/") .request() .header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) - .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null) + .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null, null) .setUnidentifiedAccessKey(new byte[16])))) { assertThat(response.getStatus()).isEqualTo(204); @@ -841,7 +841,7 @@ class AccountControllerTest { .target("/v1/accounts/attributes/") .request() .header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.UNDISCOVERABLE_UUID, AuthHelper.UNDISCOVERABLE_PASSWORD)) - .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null) + .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null, null) .setUnidentifiedAccessKey(new byte[16])))) { assertThat(response.getStatus()).isEqualTo(204); @@ -856,7 +856,7 @@ class AccountControllerTest { .target("/v1/accounts/attributes/") .request() .header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.UNDISCOVERABLE_UUID, AuthHelper.UNDISCOVERABLE_PASSWORD)) - .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null) + .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, true, null, null) .setUnidentifiedAccessKey(new byte[16]) .setRecoveryPassword(recoveryPassword)))) { @@ -872,7 +872,7 @@ class AccountControllerTest { .target("/v1/accounts/attributes/") .request() .header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) - .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null) + .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null, null) .setUnidentifiedAccessKey(new byte[16])))) { assertThat(response.getStatus()).isEqualTo(204); @@ -885,7 +885,7 @@ class AccountControllerTest { .target("/v1/accounts/attributes/") .request() .header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) - .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null) + .put(Entity.json(new AccountAttributes(false, 2222, 3333, null, null, false, null, null) .setUnidentifiedAccessKey(new byte[7])))) { assertThat(response.getStatus()).isEqualTo(422); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java index f9afed52f..2a54adeab 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java @@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.controllers; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; @@ -14,7 +15,9 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import static org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil.receiptPresentation; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.i18n.phonenumbers.PhoneNumberUtil; @@ -28,6 +31,9 @@ import jakarta.ws.rs.core.Response; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.Base64; import java.util.Collections; @@ -57,12 +63,18 @@ import org.junitpioneer.jupiter.cartesian.ArgumentSets; import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.ecc.ECKeyPair; +import org.signal.libsignal.zkgroup.InvalidInputException; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; +import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException; import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager; import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException; import org.whispersystems.textsecuregcm.auth.RegistrationLockError; import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager; import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicLoginPurchaseConfiguration; import org.whispersystems.textsecuregcm.entities.AccountAttributes; import org.whispersystems.textsecuregcm.entities.AccountCreationResponse; import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse; @@ -85,10 +97,14 @@ import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.DeviceCapability; import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo; import org.whispersystems.textsecuregcm.storage.DeviceSpec; +import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; +import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.KeysHelper; import org.whispersystems.textsecuregcm.util.MockUtils; import org.whispersystems.textsecuregcm.util.SystemMapper; +import org.whispersystems.textsecuregcm.util.TestClock; import org.whispersystems.textsecuregcm.util.TestRandomUtil; @ExtendWith(DropwizardExtensionsSupport.class) @@ -109,6 +125,16 @@ class RegistrationControllerTest { private final RateLimiter registrationLimiter = mock(RateLimiter.class); + private static final Clock CLOCK = TestClock.pinned(Instant.now()); + + private static final DynamicLoginPurchaseConfiguration ENABLED = new DynamicLoginPurchaseConfiguration(true); + private static final DynamicLoginPurchaseConfiguration DISABLED = new DynamicLoginPurchaseConfiguration(false); + + @SuppressWarnings("unchecked") + private static final DynamicConfigurationManager DYNAMIC_CONFIGURATION_MANAGER = + mock(DynamicConfigurationManager.class); + private static final DynamicConfiguration DYNAMIC_CONFIGURATION = mock(DynamicConfiguration.class); + private final ResourceExtension resources = ResourceExtension.builder() .addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE) .addProvider(new RateLimitExceededExceptionMapper()) @@ -117,7 +143,8 @@ class RegistrationControllerTest { .setMapper(SystemMapper.jsonMapper()) .setTestContainerFactory(new GrizzlyWebTestContainerFactory()) .addResource(new RegistrationController(accountsManager, phoneVerificationTokenManager, - registrationLockVerificationManager, rateLimiters, registrationFraudChecker)) + registrationLockVerificationManager, rateLimiters, registrationFraudChecker, ReceiptCredentialPresentation::new, mock( + ServerZkReceiptOperations.class), CLOCK, DYNAMIC_CONFIGURATION_MANAGER)) .build(); @BeforeEach @@ -133,6 +160,12 @@ class RegistrationControllerTest { return invocation.getArgument(0); }); + + reset(DYNAMIC_CONFIGURATION_MANAGER, DYNAMIC_CONFIGURATION); + + when(DYNAMIC_CONFIGURATION_MANAGER.getConfiguration()).thenReturn(DYNAMIC_CONFIGURATION); + when(DYNAMIC_CONFIGURATION.getLoginPurchaseConfiguration()).thenReturn(ENABLED); + reset(registrationFraudChecker); reset(phoneVerificationTokenManager); @@ -436,16 +469,17 @@ class RegistrationControllerTest { final AccountAttributes fetchesMessagesAccountAttributes = new AccountAttributes(true, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true, - DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES); + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null); final AccountAttributes pushAccountAttributes = new AccountAttributes(false, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true, - DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES); + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null); return List.of( Arguments.argumentSet("\"Fetches messages\" is true, but an APNs token is provided", new RegistrationRequest("session-id", new byte[0], + null, fetchesMessagesAccountAttributes, true, aciIdentityKey, @@ -460,6 +494,7 @@ class RegistrationControllerTest { Arguments.argumentSet("\"Fetches messages\" is true, but an FCM (GCM) token is provided", new RegistrationRequest("session-id", new byte[0], + null, fetchesMessagesAccountAttributes, true, aciIdentityKey, @@ -474,6 +509,7 @@ class RegistrationControllerTest { Arguments.argumentSet("\"Fetches messages\" is false, but multiple types of push tokens are provided", new RegistrationRequest("session-id", new byte[0], + null, pushAccountAttributes, true, aciIdentityKey, @@ -521,12 +557,13 @@ class RegistrationControllerTest { final AccountAttributes accountAttributes = new AccountAttributes(true, 1, 1, "test".getBytes(StandardCharsets.UTF_8), null, true, - DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES); + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null); return List.of( Arguments.argumentSet("Signed PNI EC pre-key is missing", new RegistrationRequest("session-id", new byte[0], + null, accountAttributes, true, aciIdentityKey, @@ -541,6 +578,7 @@ class RegistrationControllerTest { Arguments.argumentSet("Signed ACI EC pre-key is missing", new RegistrationRequest("session-id", new byte[0], + null, accountAttributes, true, aciIdentityKey, @@ -555,6 +593,7 @@ class RegistrationControllerTest { Arguments.argumentSet("Signed PNI KEM pre-key is missing", new RegistrationRequest("session-id", new byte[0], + null, accountAttributes, true, aciIdentityKey, @@ -569,6 +608,7 @@ class RegistrationControllerTest { Arguments.argumentSet("Signed ACI KEM pre-key is missing", new RegistrationRequest("session-id", new byte[0], + null, accountAttributes, true, aciIdentityKey, @@ -583,6 +623,7 @@ class RegistrationControllerTest { Arguments.argumentSet("All signed pre-keys are present, but ACI identity key is missing", new RegistrationRequest("session-id", new byte[0], + null, accountAttributes, true, null, @@ -597,6 +638,7 @@ class RegistrationControllerTest { Arguments.argumentSet("All signed pre-keys are present, but PNI identity key is missing", new RegistrationRequest("session-id", new byte[0], + null, accountAttributes, true, aciIdentityKey, @@ -695,6 +737,435 @@ class RegistrationControllerTest { } } + @Test + void registerAccountWithoutNumber() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + + final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8); + final int registrationId = 1; + final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; + + final AccountAttributes accountAttributes = + new AccountAttributes(true, registrationId, null, deviceName, null, false, deviceCapabilities, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + final ReceiptCredentialPresentation receiptCredentialPresentation = + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()); + + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + new byte[0], + receiptCredentialPresentation.serialize(), + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final UUID accountIdentifier = UUID.randomUUID(); + + final Account account = MockUtils.buildMock(Account.class, + a -> when(a.getAccountIdentifier()).thenReturn(accountIdentifier)); + + when(accountsManager.create(any(), any(), any(), any(), any(), any())).thenReturn(account); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(200, response.getStatus()); + + final AccountCreationResponse creationResponse = response.readEntity(AccountCreationResponse.class); + assertEquals(accountIdentifier, creationResponse.identityResponse().uuid()); + assertEquals(Optional.empty(), creationResponse.identityResponse().number()); + assertEquals(Optional.empty(), creationResponse.identityResponse().pni()); + assertFalse(creationResponse.reregistration()); + } + + verify(accountsManager).create( + argThat(attributes -> accountAttributesEqual(attributes, accountAttributes)), + eq(Collections.emptyList()), + eq(aciIdentityKey), + argThat(presentation -> + Arrays.equals(presentation.serialize(), receiptCredentialPresentation.serialize())), + eq(new DeviceSpec( + deviceName, + PASSWORD, + null, + deviceCapabilities, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.empty(), + true, + Optional.empty(), + Optional.empty())), + any()); + + verifyNoInteractions(phoneVerificationTokenManager); + } + + @Test + void registerAccountWithoutNumberLoginPurchasesDisabled() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + + final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8); + final int registrationId = 1; + final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; + + final AccountAttributes accountAttributes = + new AccountAttributes(true, registrationId, null, deviceName, null, false, deviceCapabilities, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + final ReceiptCredentialPresentation receiptCredentialPresentation = + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()); + + when(DYNAMIC_CONFIGURATION.getLoginPurchaseConfiguration()).thenReturn(DISABLED); + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + new byte[0], + receiptCredentialPresentation.serialize(), + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(400, response.getStatus()); + } + + verifyNoInteractions(accountsManager); + } + + @ParameterizedTest + @MethodSource + void registerAccountBadReceipt(final byte[] receiptCredentialPresentation) throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + + final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8); + final int registrationId = 1; + final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; + + final AccountAttributes accountAttributes = + new AccountAttributes(true, registrationId, null, deviceName, null, false, deviceCapabilities, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + new byte[0], + receiptCredentialPresentation, + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final UUID accountIdentifier = UUID.randomUUID(); + + final Account account = MockUtils.buildMock(Account.class, + a -> when(a.getAccountIdentifier()).thenReturn(accountIdentifier)); + + when(accountsManager.create(any(), any(), any(), any(), any(), any())).thenReturn(account); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(400, response.getStatus()); + } + + verifyNoInteractions(phoneVerificationTokenManager); + verifyNoInteractions(accountsManager); + } + + static Stream registerAccountBadReceipt() throws InvalidInputException, VerificationFailedException { + return Stream.of( + Arguments.argumentSet("malformed receipt", new byte[]{0, 0}), + Arguments.argumentSet("expired receipt", receiptPresentation(CLOCK.instant().minusSeconds(5), ReceiptLevel.LOGIN.getValue()).serialize()), + Arguments.argumentSet("wrong receipt level", receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.BACKUP_PAID.getValue()).serialize()) + ); + } + + @Test + void registerAccountSessionIdAndReceiptNotAllowed() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + + final AccountAttributes accountAttributes = + new AccountAttributes(true, 1, null, "test".getBytes(StandardCharsets.UTF_8), null, false, + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + // A session ID and a receipt credential presentation are mutually exclusive + final RegistrationRequest registrationRequest = new RegistrationRequest( + Base64.getEncoder().encodeToString("session-id".getBytes(StandardCharsets.UTF_8)), + new byte[0], + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(), + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(422, response.getStatus()); + } + + verifyNoInteractions(phoneVerificationTokenManager); + } + + @Test + void registerAccountReceiptAndRecoveryPasswordNotAllowed() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + + final byte[] recoveryPassword = TestRandomUtil.nextBytes(16); + + final AccountAttributes accountAttributes = + new AccountAttributes(true, 1, null, "test".getBytes(StandardCharsets.UTF_8), null, false, + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + // A receipt credential presentation and recovery password are mutually exclusive + final RegistrationRequest registrationRequest = new RegistrationRequest( + null, + recoveryPassword, + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(), + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(422, response.getStatus()); + } + + } + + @Test + void registerAccountMissingRecoveryPassword() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + + final AccountAttributes accountAttributes = + new AccountAttributes(true, 1, null, "test".getBytes(StandardCharsets.UTF_8), null, false, + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)); + + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + new byte[0], + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(), + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(KeysHelper.signedECPreKey(1, aciIdentityKeyPair), + Optional.empty(), + KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair), + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(422, response.getStatus()); + } + + verifyNoInteractions(accountsManager); + } + + @Test + void registerAccountWithoutNumberRejectsPniKeys() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + + final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate(); + final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(1, pniIdentityKeyPair); + + final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8); + final int registrationId = 1; + final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; + + final AccountAttributes accountAttributes = + new AccountAttributes(true, registrationId, null, deviceName, null, false, deviceCapabilities, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + final ReceiptCredentialPresentation receiptCredentialPresentation = + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()); + + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + new byte[0], + receiptCredentialPresentation.serialize(), + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(aciSignedPreKey, + Optional.of(pniSignedPreKey), + aciPqLastResortPreKey, + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(422, response.getStatus()); + } + } + + @Test + void registerAccountReceiptAlreadyRedeemed() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + + final AccountAttributes accountAttributes = + new AccountAttributes(true, 1, null, "test".getBytes(StandardCharsets.UTF_8), null, false, + DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + final RegistrationRequest registrationRequest = new RegistrationRequest(null, + new byte[0], + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(), + accountAttributes, + true, + aciIdentityKey, + null, + new DeviceActivationRequest(KeysHelper.signedECPreKey(1, aciIdentityKeyPair), + Optional.empty(), + KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair), + Optional.empty(), + Optional.empty(), + Optional.empty())); + + when(accountsManager.create(any(), any(), any(), any(), any(), any())) + .thenThrow(new ReceiptAlreadyRedeemedException()); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(400, response.getStatus()); + } + } + + @Test + void registerAccountWithNumberMissingPniKeys() throws Exception { + final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey()); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair); + + final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate(); + final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(1, pniIdentityKeyPair); + final IdentityKey pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey()); + + final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8); + final int registrationId = 1; + final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; + + final AccountAttributes accountAttributes = + new AccountAttributes(true, registrationId, null, deviceName, null, false, deviceCapabilities, null) + .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)) + .setRecoveryPassword(TestRandomUtil.nextBytes(32)); + + final RegistrationRequest registrationRequest = new RegistrationRequest( + Base64.getEncoder().encodeToString("session-id".getBytes(StandardCharsets.UTF_8)), + new byte[0], + null, + accountAttributes, + true, + aciIdentityKey, + pniIdentityKey, + new DeviceActivationRequest(aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty(), + Optional.empty(), + Optional.empty())); + + final Invocation.Builder request = resources.getJerseyTest() + .target("/v1/registration") + .request() + .header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD)); + + try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) { + assertEquals(422, response.getStatus()); + } + } + private static boolean accountAttributesEqual(final AccountAttributes a, final AccountAttributes b) { return a.getFetchesMessages() == b.getFetchesMessages() && a.getRegistrationId() == b.getRegistrationId() @@ -705,7 +1176,7 @@ class RegistrationControllerTest { && Objects.equals(a.getRegistrationLock(), b.getRegistrationLock()) && Arrays.equals(a.getUnidentifiedAccessKey(), b.getUnidentifiedAccessKey()) && Objects.equals(a.getCapabilities(), b.getCapabilities()) - && Objects.equals(a.recoveryPassword(), b.recoveryPassword()); + && Arrays.equals(a.recoveryPassword().orElse(null), b.recoveryPassword().orElse(null)); } private static List atomicAccountCreationSuccess() { @@ -734,11 +1205,13 @@ class RegistrationControllerTest { final Set deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES; final AccountAttributes fetchesMessagesAccountAttributes = - new AccountAttributes(true, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities) + new AccountAttributes(true, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities, + null) .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)); final AccountAttributes pushAccountAttributes = - new AccountAttributes(false, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities) + new AccountAttributes(false, registrationId, pniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, deviceCapabilities, + null) .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)); final String apnsToken = "apns-token"; @@ -748,6 +1221,7 @@ class RegistrationControllerTest { Arguments.argumentSet("Fetches messages; no push tokens", new RegistrationRequest("session-id", new byte[0], + null, fetchesMessagesAccountAttributes, true, aciIdentityKey, @@ -775,6 +1249,7 @@ class RegistrationControllerTest { Arguments.argumentSet("Has APNs tokens", new RegistrationRequest("session-id", new byte[0], + null, pushAccountAttributes, true, aciIdentityKey, @@ -801,6 +1276,7 @@ class RegistrationControllerTest { Arguments.argumentSet("Has GCM token", new RegistrationRequest("session-id", new byte[0], + null, pushAccountAttributes, true, aciIdentityKey, @@ -841,12 +1317,13 @@ class RegistrationControllerTest { final AccountAttributes accountAttributes = new AccountAttributes(true, registrationId, pniRegistrationId, "name".getBytes(StandardCharsets.UTF_8), REGLOCK, - true, deviceCapabilities) + true, deviceCapabilities, null) .setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16)); return new RegistrationRequest( Base64.getEncoder().encodeToString(sessionId.getBytes(StandardCharsets.UTF_8)), recoveryPassword, + null, accountAttributes, skipDeviceTransfer, aciIdentityKey, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java index 809c687bc..9d954a931 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -12,6 +13,7 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil.receiptPresentation; import com.google.i18n.phonenumbers.PhoneNumberUtil; import java.nio.charset.StandardCharsets; @@ -33,7 +35,6 @@ import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; @@ -42,6 +43,10 @@ import org.junitpioneer.jupiter.cartesian.ArgumentSets; import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.ecc.ECKeyPair; +import org.signal.libsignal.zkgroup.InvalidInputException; +import org.signal.libsignal.zkgroup.ServerSecretParams; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager; import org.whispersystems.textsecuregcm.entities.AccountAttributes; import org.whispersystems.textsecuregcm.entities.ApnRegistrationId; @@ -72,7 +77,8 @@ public class AccountCreationDeletionIntegrationTest { DynamoDbExtensionSchema.Tables.PAGED_PQ_KEYS, DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS, DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS, - DynamoDbExtensionSchema.Tables.REGISTRATION_RECOVERY_PASSWORDS); + DynamoDbExtensionSchema.Tables.REGISTRATION_RECOVERY_PASSWORDS, + DynamoDbExtensionSchema.Tables.REDEEMED_RECEIPTS); @RegisterExtension static final RedisClusterExtension CACHE_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); @@ -82,6 +88,8 @@ public class AccountCreationDeletionIntegrationTest { private static final Clock CLOCK = Clock.fixed(Instant.now(), ZoneId.systemDefault()); + private static final ServerSecretParams RECEIPT_PARAMS = ServerSecretParams.generate(); + private ScheduledExecutorService executor; private AccountsManager accountsManager; @@ -109,6 +117,8 @@ public class AccountCreationDeletionIntegrationTest { CLOCK, DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + new RedeemedReceiptsManager(CLOCK, DynamoDbExtensionSchema.Tables.REDEEMED_RECEIPTS.tableName(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), Duration.ofDays(30)), DynamoDbExtensionSchema.Tables.ACCOUNTS.tableName(), DynamoDbExtensionSchema.Tables.NUMBERS.tableName(), DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS.tableName(), @@ -201,7 +211,7 @@ public class AccountCreationDeletionIntegrationTest { deviceName, registrationLockSecret, discoverableByPhoneNumber, - deviceCapabilities); + deviceCapabilities, null); final List badges = new ArrayList<>(List.of(new AccountBadge( RandomStringUtils.secure().nextAlphabetic(8), @@ -269,8 +279,8 @@ public class AccountCreationDeletionIntegrationTest { @ParameterizedTest @MethodSource("deliveryChannels") - @Disabled("creating numberless accounts is not supported yet") - void createAccountWithoutNumber(final DeliveryChannels deliveryChannels) { + void createAccountWithoutNumber(final DeliveryChannels deliveryChannels) + throws InvalidInputException, VerificationFailedException, ReceiptAlreadyRedeemedException { final String password = RandomStringUtils.secure().nextAlphanumeric(16); final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3); final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID); @@ -284,7 +294,8 @@ public class AccountCreationDeletionIntegrationTest { deviceName, null, false, - deviceCapabilities); + deviceCapabilities, + TestRandomUtil.nextBytes(16)); final List badges = new ArrayList<>(List.of(new AccountBadge( RandomStringUtils.secure().nextAlphabetic(8), @@ -308,6 +319,7 @@ public class AccountCreationDeletionIntegrationTest { final Account account = accountsManager.create(accountAttributes, badges, new IdentityKey(aciKeyPair.getPublicKey()), + receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1), new DeviceSpec( deviceName, password, @@ -382,7 +394,8 @@ public class AccountCreationDeletionIntegrationTest { final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); final Account existingAccount = accountsManager.create(number, - new AccountAttributes(true, 1, 1, "name".getBytes(StandardCharsets.UTF_8), "registration-lock", false, Set.of()), + new AccountAttributes(true, 1, 1, "name".getBytes(StandardCharsets.UTF_8), "registration-lock", false, Set.of(), + null), Collections.emptyList(), new IdentityKey(aciKeyPair.getPublicKey()), new IdentityKey(pniKeyPair.getPublicKey()), @@ -415,7 +428,7 @@ public class AccountCreationDeletionIntegrationTest { deviceName, registrationLockSecret, discoverableByPhoneNumber, - deviceCapabilities); + deviceCapabilities, null); final List badges = new ArrayList<>(List.of(new AccountBadge( RandomStringUtils.secure().nextAlphabetic(8), @@ -501,7 +514,7 @@ public class AccountCreationDeletionIntegrationTest { deviceName, registrationLockSecret, true, - deviceCapabilities); + deviceCapabilities, null); accountAttributes.setRecoveryPassword(TestRandomUtil.nextBytes(16)); @@ -555,6 +568,160 @@ public class AccountCreationDeletionIntegrationTest { disconnectedAccount.getIdentifier(IdentityType.ACI).equals(account.getIdentifier(IdentityType.ACI)))); } + @Test + void retryRegistrationAccountWithoutNumber() + throws InvalidInputException, VerificationFailedException, ReceiptAlreadyRedeemedException { + + final ReceiptSerial receiptSerial = new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)); + final String password = RandomStringUtils.secure().nextAlphanumeric(16); + final byte[] recoveryPassword = TestRandomUtil.nextBytes(32); + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciKeyPair.getPublicKey()); + final DeliveryChannels deliveryChannels = new DeliveryChannels(false, "apns-token", null); + + final UUID existingAccountUuid; + { + final Account existingAccount = accountsManager.create( + new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), null) + .setRecoveryPassword(recoveryPassword), + Collections.emptyList(), + aciIdentityKey, + receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1), + new DeviceSpec(null, + password, + "OWI", + Set.of(), + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.empty(), + true, + Optional.empty(), + Optional.empty()), + null); + + existingAccountUuid = existingAccount.getAccountIdentifier(); + } + + final String signalAgent = RandomStringUtils.secure().nextAlphabetic(3); + final int registrationId = ThreadLocalRandom.current().nextInt(Device.MAX_REGISTRATION_ID); + final byte[] deviceName = RandomStringUtils.secure().nextAlphabetic(16).getBytes(StandardCharsets.UTF_8); + + final Set deviceCapabilities = Set.of(); + + final AccountAttributes accountAttributes = new AccountAttributes(deliveryChannels.fetchesMessages(), + registrationId, + null, + deviceName, + null, + false, + deviceCapabilities, null).setRecoveryPassword(recoveryPassword); + + final List badges = new ArrayList<>(List.of(new AccountBadge( + RandomStringUtils.secure().nextAlphabetic(8), + CLOCK.instant().plus(Duration.ofDays(7)), + true))); + + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(5, aciKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(7, aciKeyPair); + + final Optional maybeApnRegistrationId = + deliveryChannels.apnsToken() != null + ? Optional.of(new ApnRegistrationId(deliveryChannels.apnsToken())) + : Optional.empty(); + + final Optional maybeGcmRegistrationId = deliveryChannels.fcmToken() != null + ? Optional.of(new GcmRegistrationId(deliveryChannels.fcmToken())) + : Optional.empty(); + + final Account retriedAccount = accountsManager.create(accountAttributes, + badges, + aciIdentityKey, + receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1), + new DeviceSpec(deviceName, + password, + signalAgent, + deviceCapabilities, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.empty(), + accountAttributes.getFetchesMessages(), + maybeApnRegistrationId, + maybeGcmRegistrationId), + null); + + assertExpectedStoredAccount(retriedAccount, + Optional.empty(), + password, + signalAgent, + deliveryChannels, + registrationId, + Optional.empty(), + deviceName, + false, + deviceCapabilities, + badges, + maybeApnRegistrationId, + maybeGcmRegistrationId, + Optional.empty(), + aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty()); + + assertEquals(existingAccountUuid, retriedAccount.getAccountIdentifier()); + + assertTrue(retriedAccount.getNumberOptional().isEmpty()); + assertTrue(retriedAccount.getPhoneNumberIdentifierOptional().isEmpty()); + assertTrue(retriedAccount.getPhoneNumberIdentityKey().isEmpty()); + + verify(disconnectionRequestManager).requestDisconnection(argThat(account -> + account.getAccountIdentifier().equals(existingAccountUuid) && account != retriedAccount)); + } + + @Test + void retryRegistrationAccountWithNoNumberDifferentRecoveryPassword() + throws InvalidInputException, VerificationFailedException, ReceiptAlreadyRedeemedException { + + final ReceiptSerial receiptSerial = new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)); + final String password = RandomStringUtils.secure().nextAlphanumeric(16); + final byte[] recoveryPassword = TestRandomUtil.nextBytes(32); + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final IdentityKey aciIdentityKey = new IdentityKey(aciKeyPair.getPublicKey()); + + final Account existingAccount = accountsManager.create( + new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), recoveryPassword), + Collections.emptyList(), + aciIdentityKey, + receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1), + new DeviceSpec(null, + password, + "OWI", + Set.of(), + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.empty(), + true, + Optional.empty(), + Optional.empty()), + null); + + assertNotNull(existingAccount); + + assertThrows(ReceiptAlreadyRedeemedException.class, () -> accountsManager.create( + // 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)), + Collections.emptyList(), + aciIdentityKey, + receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1), + new DeviceSpec(null, + password, + "OWI", + Set.of(), + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.empty(), + true, + Optional.empty(), + Optional.empty()), + null)); + } + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private void assertExpectedStoredAccount(final Account account, final Optional number, @@ -605,5 +772,6 @@ public class AccountCreationDeletionIntegrationTest { assertEquals(pniSignedPreKey, keysManager.getEcSignedPreKey(pni, Device.PRIMARY_ID).join()); assertEquals(pniPqLastResortPreKey, keysManager.getLastResort(pni, Device.PRIMARY_ID).join()); }); + assertEquals(number.isEmpty(), account.getAuthCredentialSalt().isPresent()); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java index d69a09532..17b8ba15c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java @@ -96,6 +96,8 @@ class AccountsManagerChangeNumberIntegrationTest { Clock.systemUTC(), DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + new RedeemedReceiptsManager(Clock.systemUTC(), Tables.REDEEMED_RECEIPTS.tableName(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -227,7 +229,8 @@ class AccountsManagerChangeNumberIntegrationTest { final ECKeyPair rotatedPniIdentityKeyPair = ECKeyPair.generate(); final ECSignedPreKey rotatedSignedPreKey = KeysHelper.signedECPreKey(1L, rotatedPniIdentityKeyPair); final KEMSignedPreKey rotatedKemSignedPreKey = KeysHelper.signedKEMPreKey(2L, rotatedPniIdentityKeyPair); - final AccountAttributes accountAttributes = new AccountAttributes(true, rotatedPniRegistrationId + 1, rotatedPniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, Set.of()); + final AccountAttributes accountAttributes = new AccountAttributes(true, rotatedPniRegistrationId + 1, rotatedPniRegistrationId, "test".getBytes(StandardCharsets.UTF_8), null, true, Set.of(), + null); final Account account = AccountsHelper.createAccount(accountsManager, originalNumber, accountAttributes); keysManager.storeEcSignedPreKeys(account.getIdentifier(IdentityType.ACI), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java index 47b9bee7f..bbd131683 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java @@ -23,6 +23,7 @@ import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Optional; @@ -88,6 +89,8 @@ class AccountsManagerConcurrentModificationIntegrationTest { Clock.systemUTC(), DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + new RedeemedReceiptsManager(Clock.systemUTC(), Tables.REDEEMED_RECEIPTS.tableName(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java index f864a0840..8067169a3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java @@ -81,6 +81,8 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest { Clock.systemUTC(), DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + new RedeemedReceiptsManager(Clock.systemUTC(), DynamoDbExtensionSchema.Tables.REDEEMED_RECEIPTS.tableName(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), Duration.ofDays(30)), DynamoDbExtensionSchema.Tables.ACCOUNTS.tableName(), DynamoDbExtensionSchema.Tables.NUMBERS.tableName(), DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS.tableName(), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java index 0a1e593b8..cf896ff62 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java @@ -49,6 +49,7 @@ import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; @@ -75,7 +76,9 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.stubbing.Answer; import org.signal.libsignal.protocol.IdentityKey; import org.signal.libsignal.protocol.ecc.ECKeyPair; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager; +import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.controllers.MismatchedDevices; import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException; @@ -705,19 +708,21 @@ class AccountsManagerTest { @ParameterizedTest @ValueSource(booleans = {false, true}) - void testCreateFreshAccount(final boolean hasE164) throws AccountAlreadyExistsException { + void testCreateFreshAccount(final boolean hasE164) + throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException { when(accounts.create(any(), any())).thenReturn(true); final Optional maybeE164 = hasE164 ? Optional.of("+18005550123") : Optional.empty(); final Integer pniRegistrationId = hasE164 ? 2 : null; - final AccountAttributes attributes = new AccountAttributes(false, 1, pniRegistrationId, null, null, hasE164, null); + final AccountAttributes attributes = new AccountAttributes(false, 1, pniRegistrationId, null, null, hasE164, null, + TestRandomUtil.nextBytes(16)); - final Account createdAccount = maybeE164 - .map(e164 -> createAccount(e164, attributes)) - .orElseGet(() -> createAccount(attributes)); + final Account createdAccount = maybeE164.isPresent() + ? createAccount(maybeE164.get(), attributes) + : createAccount(attributes); // Check existence (or lack thereof) of phone number, phone number identifier, phone number identity key, - // and phone number identity registration ID + // phone number identity registration ID, and auth credential salt. final Device primaryDevice = createdAccount.getDevices().stream().findFirst().orElseThrow(); assertEquals(maybeE164, createdAccount.getNumberOptional()); maybeE164.ifPresentOrElse( @@ -725,14 +730,20 @@ class AccountsManagerTest { assertTrue(phoneNumberIdentifiersByE164.containsKey(number)); assertTrue(createdAccount.getPhoneNumberIdentityKey().isPresent()); assertEquals(pniRegistrationId, primaryDevice.getPhoneNumberIdentityRegistrationId().orElseThrow()); + assertTrue(createdAccount.getAuthCredentialSalt().isEmpty()); }, () -> { assertTrue(phoneNumberIdentifiersByE164.isEmpty()); assertTrue(createdAccount.getPhoneNumberIdentityKey().isEmpty()); assertTrue(primaryDevice.getPhoneNumberIdentityRegistrationId().isEmpty()); + assertTrue(createdAccount.getAuthCredentialSalt().isPresent()); }); - verify(accounts).create(argThat(account -> maybeE164.equals(account.getNumberOptional())), any()); + if (maybeE164.isPresent()) { + verify(accounts).create(argThat(account -> maybeE164.equals(account.getNumberOptional())), any()); + } else { + verify(accounts).create(argThat(account -> account.getNumberOptional().isEmpty()), any(), any(), any()); + } verify(keysManager).buildWriteItemsForNewDevice( eq(createdAccount.getAccountIdentifier()), eq(createdAccount.getPhoneNumberIdentifierOptional()), @@ -753,29 +764,42 @@ class AccountsManagerTest { void testReregisterAccount( final Optional maybeE164, final Optional maybeExistingAccountE164) - throws AccountAlreadyExistsException { + throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException { 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); + final AccountAttributes attributes = new AccountAttributes(false, 1, pniRegistrationId, null, null, maybeE164.isPresent(), null, + null); + final byte[] recoveryPassword = TestRandomUtil.nextBytes(32); + attributes.setRecoveryPassword(recoveryPassword); - when(accounts.create(any(), any())) - .thenAnswer(invocation -> { - final Account requestedAccount = invocation.getArgument(0); + final Answer existingAccountAnswer = invocation -> { + final Account requestedAccount = invocation.getArgument(0); - final Account existingAccount = mock(Account.class); - when(existingAccount.getAccountIdentifier()).thenReturn(existingUuid); - when(existingAccount.getNumberOptional()).thenReturn(maybeExistingAccountE164); - when(existingAccount.getPhoneNumberIdentifierOptional()).thenReturn(requestedAccount.getPhoneNumberIdentifierOptional()); - when(existingAccount.getPrimaryDevice()).thenReturn(mock(Device.class)); + final Device existingPrimaryDevice = mock(Device.class); - throw new AccountAlreadyExistsException(existingAccount); - }); + final Account existingAccount = mock(Account.class); + when(existingAccount.getAccountIdentifier()).thenReturn(existingUuid); + when(existingAccount.getNumberOptional()).thenReturn(maybeExistingAccountE164); + when(existingAccount.getPhoneNumberIdentifierOptional()).thenReturn(requestedAccount.getPhoneNumberIdentifierOptional()); + when(existingAccount.getPrimaryDevice()).thenReturn(existingPrimaryDevice); + when(existingAccount.getAccountIdentityKey()).thenReturn(requestedAccount.getAccountIdentityKey()); + when(existingAccount.getAccountRecoveryPassword()).thenReturn( + Optional.of(SaltedTokenHash.generateFor(HexFormat.of().formatHex(recoveryPassword)))); + + throw new AccountAlreadyExistsException(existingAccount); + }; + + if (maybeE164.isPresent()) { + when(accounts.create(any(), any())).thenAnswer(existingAccountAnswer); + } else { + when(accounts.create(any(), any(), any(), any())).thenAnswer(existingAccountAnswer); + } when(accounts.reclaimAccount(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null)); - final Account reregisteredAccount = maybeE164 - .map(number -> createAccount(number, attributes)) - .orElseGet(() -> createAccount(attributes)); + final Account reregisteredAccount = maybeE164.isPresent() + ? createAccount(maybeE164.get(), attributes) + : createAccount(attributes); // Check existence (or lack thereof) of phone number, phone number identifier, phone number identity key, // and phone number identity registration ID @@ -794,8 +818,13 @@ class AccountsManagerTest { assertTrue(primaryDevice.getPhoneNumberIdentityRegistrationId().isEmpty()); }); - verify(accounts) - .create(argThat(account -> existingUuid.equals(account.getAccountIdentifier())), any()); + if (maybeE164.isPresent()) { + verify(accounts) + .create(argThat(account -> existingUuid.equals(account.getAccountIdentifier())), any()); + } else { + verify(accounts) + .create(argThat(account -> existingUuid.equals(account.getAccountIdentifier())), any(), any(), any()); + } verify(keysManager).buildWriteItemsForNewDevice( eq(reregisteredAccount.getAccountIdentifier()), @@ -832,7 +861,7 @@ class AccountsManagerTest { when(accounts.create(any(), any())).thenReturn(true); final String e164 = "+18005550123"; - final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null); + final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null, null); final Account account = createAccount(e164, attributes); @@ -856,7 +885,7 @@ class AccountsManagerTest { @ParameterizedTest @ValueSource(booleans = {true, false}) void testCreateWithDiscoverability(final boolean discoverable) throws InterruptedException { - final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, discoverable, null); + final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, discoverable, null, null); final Account account = createAccount("+18005550123", attributes); assertEquals(discoverable, account.isDiscoverableByPhoneNumber()); @@ -866,7 +895,7 @@ class AccountsManagerTest { @ValueSource(booleans = {true, false}) void testCreateWithStorageCapability(final boolean hasStorage) throws InterruptedException { final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, - true, hasStorage ? Set.of(DeviceCapability.STORAGE) : Set.of()); + true, hasStorage ? Set.of(DeviceCapability.STORAGE) : Set.of(), null); final Account account = createAccount("+18005550123", attributes); @@ -1365,12 +1394,13 @@ class AccountsManagerTest { return device; } - private Account createAccount(final AccountAttributes accountAttributes) { + private Account createAccount(final AccountAttributes accountAttributes) throws ReceiptAlreadyRedeemedException { final ECKeyPair aciKeyPair = ECKeyPair.generate(); return accountsManager.create(accountAttributes, new ArrayList<>(), new IdentityKey(aciKeyPair.getPublicKey()), + mock(ReceiptCredentialPresentation.class), new DeviceSpec( accountAttributes.getName(), "password", diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java index 4f45c58f7..91004594b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java @@ -109,6 +109,8 @@ class AccountsManagerUsernameIntegrationTest { Clock.systemUTC(), DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + new RedeemedReceiptsManager(Clock.systemUTC(), Tables.REDEEMED_RECEIPTS.tableName(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java index 594c4ad3c..ed93ec27f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil.receiptPresentation; import static org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil.assertFailsWithCause; import com.fasterxml.jackson.core.JsonProcessingException; @@ -50,18 +51,21 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; +import jakarta.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; +import org.junitpioneer.jupiter.cartesian.ArgumentSets; +import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.signal.libsignal.zkgroup.ZkCredentialKeyPair; import org.signal.libsignal.zkgroup.backups.BackupCredentialType; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; import org.whispersystems.textsecuregcm.identity.IdentityType; @@ -116,6 +120,7 @@ class AccountsTest { Tables.USERNAMES, Tables.DELETED_ACCOUNTS, Tables.USED_LINK_DEVICE_TOKENS, + Tables.REDEEMED_RECEIPTS, // This is an unrelated table used to test "tag-along" transactional updates Tables.CLIENT_RELEASES); @@ -139,6 +144,8 @@ class AccountsTest { clock, DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + new RedeemedReceiptsManager(clock, Tables.REDEEMED_RECEIPTS.tableName(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -147,11 +154,20 @@ class AccountsTest { Tables.USED_LINK_DEVICE_TOKENS.tableName()); } - @Test - public void testStoreAndLookupUsernameLink() { - final Account account = nextRandomAccount(); + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + public void testStoreAndLookupUsernameLink(@Nullable final String number) throws Exception { + Device device = generateDevice(DEVICE_ID_1); + Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), List.of(device)); account.setUsernameHash(TestRandomUtil.nextBytes(16)); - createAccount(account); + + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); + } final BiConsumer, byte[]> validator = (maybeAccount, expectedEncryptedUsername) -> { assertTrue(maybeAccount.isPresent()); @@ -182,32 +198,39 @@ class AccountsTest { assertTrue(accounts.getByUsernameLinkHandle(linkHandle2).join().isEmpty()); } - @Test - void testStore() { + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testStore(@Nullable final String number) throws Exception { Device device = generateDevice(DEVICE_ID_1); - Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device)); + Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), List.of(device)); - boolean freshUser = createAccount(account); + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + boolean freshUser = number != null ? createAccount(account) : createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); assertThat(freshUser).isTrue(); - verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); - assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); + if (number != null) { + assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + } else { + assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); + } + + freshUser = number != null ? createAccount(account) : createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); - freshUser = createAccount(account); assertThat(freshUser).isTrue(); - verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); - assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); - } - - @Test - void testStoreNumberlessAccount() { - // Numberless account creation is not supported yet in the Accounts layer - final Account account = generateNumberlessAccount(UUID.randomUUID()); - assertThrows(IllegalArgumentException.class, () -> createAccount(account)); + if (number != null) { + assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + } else { + assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); + } } @Test @@ -238,17 +261,29 @@ class AccountsTest { assertThat(accounts.findRecentlyDeletedAccountIdentifier(account.getPhoneNumberIdentifier())).isEmpty(); } - @Test - void testStoreMulti() { + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testStoreMulti(@Nullable final String number) throws Exception { final List devices = List.of(generateDevice(DEVICE_ID_1), generateDevice(DEVICE_ID_2)); - final Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), devices); + final Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), devices); - createAccount(account); + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); + } - verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); - assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); + if (number != null) { + assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + } else { + assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); + } } @Test @@ -335,6 +370,31 @@ class AccountsTest { verifyStoredState("+14152221111", uuidSecond, pniSecond, null, retrievedSecond.get(), accountSecond); } + @Test + void testRetrieveNumberlessAccount() throws Exception { + final List devicesFirst = List.of(generateDevice(DEVICE_ID_1), generateDevice(DEVICE_ID_2)); + + final UUID uuidFirst = UUID.randomUUID(); + final Account accountFirst = generateAccount(null, uuidFirst, null, devicesFirst); + + final List devicesSecond = List.of(generateDevice(DEVICE_ID_1), generateDevice(DEVICE_ID_2)); + + final UUID uuidSecond = UUID.randomUUID(); + final Account accountSecond = generateAccount(null, uuidSecond, null, devicesSecond); + + createNumberlessAccount(accountFirst, receiptPresentation(), TestRandomUtil.nextBytes(16)); + createNumberlessAccount(accountSecond, receiptPresentation(), TestRandomUtil.nextBytes(16)); + + final Optional retrievedFirst = accounts.getByAccountIdentifier(uuidFirst); + final Optional retrievedSecond = accounts.getByAccountIdentifier(uuidSecond); + + assertThat(retrievedFirst.isPresent()).isTrue(); + assertThat(retrievedSecond.isPresent()).isTrue(); + + verifyStoredState(null, uuidFirst, null, null, retrievedFirst.get(), accountFirst); + verifyStoredState(null, uuidSecond, null, null, retrievedSecond.get(), accountSecond); + } + // State before the account is re-registered enum UsernameStatus { NONE, @@ -343,14 +403,21 @@ class AccountsTest { CONFIRMED } - @ParameterizedTest - @EnumSource(UsernameStatus.class) - void reclaimAccountWithNoUsername(UsernameStatus usernameStatus) throws UsernameHashNotAvailableException { + @CartesianTest + @CartesianTest.MethodFactory("reclaimAccountWithNoUsername") + void reclaimAccountWithNoUsername(final UsernameStatus usernameStatus, @Nullable final String number) + throws Exception { Device device = generateDevice(DEVICE_ID_1); UUID firstUuid = UUID.randomUUID(); - UUID firstPni = UUID.randomUUID(); - Account account = generateAccount("+14151112222", firstUuid, firstPni, List.of(device)); - createAccount(account); + final byte[] accoutRecoveryPassword = TestRandomUtil.nextBytes(16); + Account account = generateAccount(number, firstUuid, number == null ? null : UUID.randomUUID(), List.of(device), accoutRecoveryPassword); + + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptCredentialPresentation, accoutRecoveryPassword); + } final byte[] usernameHash = TestRandomUtil.nextBytes(32); final byte[] encryptedUsername = TestRandomUtil.nextBytes(32); @@ -367,8 +434,13 @@ class AccountsTest { // simulate a partially-completed re-reg: we give the account a reclaimable username, but we'll try // re-registering again later in the test case - account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); - reclaimAccount(account); + account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), + List.of(generateDevice(DEVICE_ID_1)), accoutRecoveryPassword); + if (number != null) { + reclaimAccount(account); + } else { + reclaimNumberlessAccount(account, receiptCredentialPresentation, accoutRecoveryPassword); + } break; case CONFIRMED: accounts.reserveUsernameHash(account, usernameHash, Duration.ofMinutes(1)); @@ -379,8 +451,13 @@ class AccountsTest { Optional preservedLink = Optional.ofNullable(account.getUsernameLinkHandle()); // re-register the account - account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); - reclaimAccount(account); + account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), + List.of(generateDevice(DEVICE_ID_1))); + if (number != null) { + reclaimAccount(account); + } else { + reclaimNumberlessAccount(account, receiptCredentialPresentation, accoutRecoveryPassword); + } // If we had a username link, or we had previously saved a username link from another re-registration, make sure // we preserve it @@ -402,6 +479,13 @@ class AccountsTest { assertThat(account.getReservedUsernameHash()).isEmpty(); } + @SuppressWarnings("unused") + static ArgumentSets reclaimAccountWithNoUsername() { + return ArgumentSets.argumentsForFirstParameter(UsernameStatus.values()) + // number + .argumentsForNextParameter("+14151112222", null); + } + private void reclaimAccount(final Account reregisteredAccount) { final AccountAlreadyExistsException accountAlreadyExistsException = assertThrows(AccountAlreadyExistsException.class, @@ -420,21 +504,48 @@ class AccountsTest { Collections.emptyList()).toCompletableFuture().join()); } - @Test - void testReclaimAccountPreservesFields() throws Exception { - final String e164 = "+14151112222"; + private void reclaimNumberlessAccount(final Account reregisteredAccount, final ReceiptCredentialPresentation receiptCredentialPresentation, final byte[] accountRecoveryPassword) { + final AccountAlreadyExistsException accountAlreadyExistsException = + assertThrows(AccountAlreadyExistsException.class, + () -> accounts.create(reregisteredAccount, receiptCredentialPresentation, accountRecoveryPassword, Collections.emptyList())); + + reregisteredAccount.setAccountIdentifier(accountAlreadyExistsException.getExistingAccount().getAccountIdentifier()); + + assertDoesNotThrow(() -> accounts.reclaimAccount(accountAlreadyExistsException.getExistingAccount(), + reregisteredAccount, + Collections.emptyList()).toCompletableFuture().join()); + } + + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testReclaimAccountPreservesBackupCredentialFields(@Nullable final String number) throws Exception { final UUID existingUuid = UUID.randomUUID(); + final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16); final Account existingAccount = - generateAccount(e164, existingUuid, UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); + generateAccount(number, existingUuid, number == null ? null : UUID.randomUUID(), + List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword); // the backup credential request and share-set are always preserved across account reclaims existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32)); existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey()); - createAccount(existingAccount); - final Account secondAccount = - generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); - reclaimAccount(secondAccount); + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(existingAccount); + } else { + createNumberlessAccount(existingAccount, receiptCredentialPresentation, accountRecoveryPassword); + } + + final Account secondAccount = + generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), + List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword); + + if (number != null) { + reclaimAccount(secondAccount); + } else { + reclaimNumberlessAccount(secondAccount, receiptCredentialPresentation, accountRecoveryPassword); + } final Account reclaimed = accounts.getByAccountIdentifier(existingUuid).orElseThrow(); assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElseThrow()) @@ -444,13 +555,15 @@ class AccountsTest { assertThat(reclaimed.getZkCredentialKey()).hasValue(existingAccount.getZkCredentialKey().orElseThrow()); } - @Test - void testReclaimAccount() throws Exception { - final String e164 = "+14151112222"; + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testReclaimAccount(@Nullable final String number) throws Exception { final Device device = generateDevice(DEVICE_ID_1); final UUID existingUuid = UUID.randomUUID(); - final UUID existingPni = UUID.randomUUID(); - final Account existingAccount = generateAccount(e164, existingUuid, existingPni, List.of(device)); + final UUID existingPni = number == null ? null : UUID.randomUUID(); + final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16); + final Account existingAccount = generateAccount(number, existingUuid, existingPni, List.of(device), accountRecoveryPassword); // Backup vouchers should be carried over across re-registration final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1))); @@ -458,7 +571,12 @@ class AccountsTest { // ZK credential keys should be carried over across re-registration existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey()); - createAccount(existingAccount); + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(existingAccount); + } else { + createNumberlessAccount(existingAccount, receiptCredentialPresentation, accountRecoveryPassword); + } final byte[] usernameHash = TestRandomUtil.nextBytes(32); final byte[] encryptedUsername = TestRandomUtil.nextBytes(16); @@ -467,23 +585,34 @@ class AccountsTest { accounts.confirmUsernameHash(existingAccount, usernameHash, encryptedUsername); final UUID usernameLinkHandle = existingAccount.getUsernameLinkHandle(); - assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); - verifyStoredState(e164, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), usernameHash, existingAccount, true); + verifyStoredState(number, existingAccount.getAccountIdentifier(), + existingAccount.getPhoneNumberIdentifierOptional().orElse(null), usernameHash, existingAccount, + number != null); - assertPhoneNumberConstraintExists(e164, existingUuid); - assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); + if (number != null) { + assertThat(existingAccount.getPhoneNumberIdentifierOptional()).isPresent(); + assertPhoneNumberConstraintExists(number, existingUuid); + assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); + } else { + assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, existingUuid); + } assertDoesNotThrow(() -> accounts.update(existingAccount)); final UUID secondUuid = UUID.randomUUID(); final Device secondDevice = generateDevice(DEVICE_ID_1); - final Account secondAccount = generateAccount(e164, secondUuid, UUID.randomUUID(), List.of(secondDevice)); + final Account secondAccount = + generateAccount(number, secondUuid, number == null ? null : UUID.randomUUID(), List.of(secondDevice)); - reclaimAccount(secondAccount); + if (number != null) { + reclaimAccount(secondAccount); + } else { + reclaimNumberlessAccount(secondAccount, receiptCredentialPresentation, accountRecoveryPassword); + } // usernameHash should be unset - verifyStoredState("+14151112222", existingUuid, existingPni, null, secondAccount, true); + verifyStoredState(number, existingUuid, existingPni, null, secondAccount, number != null); // username should become 'reclaimable' Map item = readAccount(existingUuid); @@ -508,70 +637,17 @@ class AccountsTest { assertArrayEquals(usernameHash, result.getUsernameHash().orElseThrow()); assertThat(result.getReservedUsernameHash()).isEmpty(); - assertPhoneNumberConstraintExists("+14151112222", existingUuid); - assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); + if (number != null) { + assertPhoneNumberConstraintExists(number, existingUuid); + assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); - Account invalidAccount = generateAccount("+14151113333", existingUuid, UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); + final Account invalidAccount = + generateAccount("+14151113333", existingUuid, UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); - assertThatThrownBy(() -> createAccount(invalidAccount)); - } - - @Test - @Disabled("reclaiming numberless accounts is not supported yet") - void testReclaimNumberlessAccount() throws Exception { - final UUID existingUuid = UUID.randomUUID(); - final Account numberlessExistingAccount = generateNumberlessAccount(existingUuid); - - // Backup vouchers should be carried over across re-registration - final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1))); - numberlessExistingAccount.setBackupVoucher(bv); - // ZK credential keys should be carried over across re-registration - numberlessExistingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey()); - - createAccount(numberlessExistingAccount); - - final byte[] usernameHash = TestRandomUtil.nextBytes(32); - final byte[] encryptedUsername = TestRandomUtil.nextBytes(16); - - // Set up the existing account to have a username hash - accounts.confirmUsernameHash(numberlessExistingAccount, usernameHash, encryptedUsername); - final UUID usernameLinkHandle = numberlessExistingAccount.getUsernameLinkHandle(); - - assertTrue(numberlessExistingAccount.getPhoneNumberIdentifierOptional().isEmpty()); - verifyStoredState(null, numberlessExistingAccount.getAccountIdentifier(), null, usernameHash, numberlessExistingAccount, true); - - assertDoesNotThrow(() -> accounts.update(numberlessExistingAccount)); - - final Account secondAccount = generateNumberlessAccount(existingUuid); - - // TODO: may need to update when we add support for reclaiming numberless accounts - reclaimAccount(secondAccount); - - // usernameHash should be unset - verifyStoredState(null, existingUuid, null, null, secondAccount, true); - - // username should become 'reclaimable' - Map item = readAccount(existingUuid); - Account result = Accounts.fromItem(item); - assertThat(AttributeValues.getUUID(item, Accounts.ATTR_USERNAME_LINK_UUID, null)) - .isEqualTo(usernameLinkHandle) - .isEqualTo(result.getUsernameLinkHandle()); - assertThat(result.getUsernameHash()).isEmpty(); - 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); - item = readAccount(existingUuid); - result = Accounts.fromItem(item); - assertThat(AttributeValues.getUUID(item, Accounts.ATTR_USERNAME_LINK_UUID, null)) - .isEqualTo(usernameLinkHandle) - .isEqualTo(result.getUsernameLinkHandle()); - assertArrayEquals(encryptedUsername, result.getEncryptedUsername().orElseThrow()); - assertArrayEquals(usernameHash, result.getUsernameHash().orElseThrow()); - assertThat(result.getReservedUsernameHash()).isEmpty(); + assertThatThrownBy(() -> createAccount(invalidAccount)); + } else { + assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, existingUuid); + } } @ParameterizedTest @@ -716,35 +792,59 @@ class AccountsTest { assertDoesNotThrow(() -> accounts.update(existingAccount)); } - @Test - void testUpdate() { + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testUpdate(@Nullable final String number) throws Exception { Device device = generateDevice(DEVICE_ID_1); - Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device)); + Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), + List.of(device)); - createAccount(account); + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); + } - assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); + if (number != null) { + assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + } else { + assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); + } device.setName("foobar".getBytes(StandardCharsets.UTF_8)); accounts.update(account); - assertPhoneNumberConstraintExists("+14151112222", account.getAccountIdentifier()); - assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier(), account.getAccountIdentifier()); + if (number != null) { + assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + assertPhoneNumberConstraintExists(number, account.getAccountIdentifier()); + assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifierOptional().get(), account.getAccountIdentifier()); + } else { + assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier()); + } - Optional retrieved = accounts.getByE164("+14151112222"); + if (number != null) { + assertThat(account.getPhoneNumberIdentifierOptional()).isPresent(); + final Optional retrievedByE164 = accounts.getByE164(number); + + assertThat(retrievedByE164).isPresent(); + verifyStoredState(number, account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional().get(), null, + retrievedByE164.get(), account); + } + + final Optional retrieved = accounts.getByAccountIdentifier(account.getAccountIdentifier()); assertThat(retrieved.isPresent()).isTrue(); - verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, retrieved.get(), account); - - retrieved = accounts.getByAccountIdentifier(account.getAccountIdentifier()); - - assertThat(retrieved.isPresent()).isTrue(); - verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); + verifyStoredState(number, account.getAccountIdentifier(), + account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); device = generateDevice(DEVICE_ID_1); - Account unknownAccount = generateAccount("+14151113333", UUID.randomUUID(), UUID.randomUUID(), List.of(device)); + Account unknownAccount = generateAccount(number == null ? null : "+14151113333", UUID.randomUUID(), + number == null ? null : UUID.randomUUID(), List.of(device)); assertThatThrownBy(() -> accounts.update(unknownAccount)).isInstanceOfAny(ConditionalCheckFailedException.class); @@ -752,7 +852,8 @@ class AccountsTest { assertThat(account.getVersion()).isEqualTo(2); - verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); + verifyStoredState(number, account.getAccountIdentifier(), + account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); account.setVersion(1); @@ -762,17 +863,22 @@ class AccountsTest { accounts.update(account); - verifyStoredState("+14151112222", account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, true); + verifyStoredState(number, account.getAccountIdentifier(), + account.getPhoneNumberIdentifierOptional().orElse(null), null, account, number != null); } - @Test - void testUpdateWithMockTransactionConflictException() { + @ParameterizedTest + @ValueSource(strings = "+14151112222") + @NullSource + void testUpdateWithMockTransactionConflictException(@Nullable final String number) throws Exception { final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class); accounts = new Accounts( clock, dynamoDbClient, mock(DynamoDbAsyncClient.class), + new RedeemedReceiptsManager(clock, Tables.REDEEMED_RECEIPTS.tableName(), + dynamoDbClient, Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -783,15 +889,23 @@ class AccountsTest { when(dynamoDbClient.updateItem(any(UpdateItemRequest.class))) .thenThrow(TransactionConflictException.builder().build()); - final Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID()); + final Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID()); assertThatThrownBy(() -> accounts.update(account)).isInstanceOfAny(ContestedOptimisticLockException.class); } - @Test - void testUpdateTransactionally() { - final Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID()); - createAccount(account); + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testUpdateTransactionally(@Nullable final String number) throws Exception { + final Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID()); + + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); + } final byte[] deviceName = "device-name".getBytes(StandardCharsets.UTF_8); @@ -832,10 +946,18 @@ class AccountsTest { .hasItem()); } - @Test - void testUpdateTransactionallyContestedLock() { - final Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID()); - createAccount(account); + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testUpdateTransactionallyContestedLock(@Nullable final String number) throws Exception { + final Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID()); + + final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation(); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16)); + } account.setVersion(account.getVersion() - 1); @@ -851,14 +973,18 @@ class AccountsTest { .build()))); } - @Test - void testUpdateTransactionallyWithMockTransactionConflictException() { + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testUpdateTransactionallyWithMockTransactionConflictException(@Nullable final String number) { final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class); accounts = new Accounts( clock, dynamoDbClient, mock(DynamoDbAsyncClient.class), + new RedeemedReceiptsManager(clock, Tables.REDEEMED_RECEIPTS.tableName(), + dynamoDbClient, Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -873,20 +999,30 @@ class AccountsTest { .build()) .build()); - final Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID()); + final Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID()); assertThatThrownBy(() -> accounts.updateTransactionally(account, Collections.emptyList())) .isInstanceOfAny(ContestedOptimisticLockException.class); } @Test - void testGetAll() { + void testGetAll() throws Exception { final List expectedAccounts = new ArrayList<>(); for (int i = 1; i <= 100; i++) { - final Account account = generateAccount("+1" + String.format("%03d", i), UUID.randomUUID(), UUID.randomUUID()); + final boolean numberless = i % 2 == 0; + + final Account account = numberless + ? generateNumberlessAccount(UUID.randomUUID()) + : generateAccount("+1" + String.format("%03d", i), UUID.randomUUID(), UUID.randomUUID()); + expectedAccounts.add(account); - createAccount(account); + + if (numberless) { + createNumberlessAccount(account, receiptPresentation(), TestRandomUtil.nextBytes(16)); + } else { + createAccount(account); + } } final List retrievedAccounts = @@ -898,13 +1034,23 @@ class AccountsTest { } @Test - void testGetAllAccountIdentifiers() { + void testGetAllAccountIdentifiers() throws Exception { final Set expectedAccountIdentifiers = new HashSet<>(); for (int i = 1; i <= 100; i++) { - final Account account = generateAccount("+1" + String.format("%03d", i), UUID.randomUUID(), UUID.randomUUID()); - expectedAccountIdentifiers.add(account.getIdentifier(IdentityType.ACI)); - createAccount(account); + final boolean numberless = i % 2 == 0; + + final Account account = numberless + ? generateNumberlessAccount(UUID.randomUUID()) + : generateAccount("+1" + String.format("%03d", i), UUID.randomUUID(), UUID.randomUUID()); + + expectedAccountIdentifiers.add(account.getAccountIdentifier()); + + if (numberless) { + createNumberlessAccount(account, receiptPresentation(), TestRandomUtil.nextBytes(16)); + } else { + createAccount(account); + } } @SuppressWarnings("DataFlowIssue") final Set retrievedAccountIdentifiers = @@ -962,28 +1108,42 @@ class AccountsTest { } } - @Test - void testMissing() { + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void testMissing(@Nullable final String number) throws Exception { Device device = generateDevice(DEVICE_ID_1); - Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(device)); + Account account = generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), + List.of(device)); - createAccount(account); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptPresentation(), TestRandomUtil.nextBytes(16)); + } Optional retrieved = accounts.getByE164("+11111111"); - assertThat(retrieved.isPresent()).isFalse(); + assertThat(retrieved).isNotPresent(); retrieved = accounts.getByAccountIdentifier(UUID.randomUUID()); - assertThat(retrieved.isPresent()).isFalse(); + assertThat(retrieved).isNotPresent(); } - @Test - void getByAccountIdentifierAsync() { + @ParameterizedTest + @ValueSource(strings = {"+14151112222"}) + @NullSource + void getByAccountIdentifierAsync(@Nullable final String number) throws Exception { assertThat(accounts.getByAccountIdentifierAsync(UUID.randomUUID()).join()).isEmpty(); final Account account = - generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); + generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(), + List.of(generateDevice(DEVICE_ID_1))); - createAccount(account); + if (number != null) { + createAccount(account); + } else { + createNumberlessAccount(account, receiptPresentation(), TestRandomUtil.nextBytes(16)); + } assertThat(accounts.getByAccountIdentifierAsync(account.getAccountIdentifier()).join()).isPresent(); } @@ -1269,6 +1429,8 @@ class AccountsTest { clock, dynamoDbClient, mock(DynamoDbAsyncClient.class), + new RedeemedReceiptsManager(clock, Tables.REDEEMED_RECEIPTS.tableName(), + dynamoDbClient, Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -1315,6 +1477,8 @@ class AccountsTest { clock, dynamoDbClient, mock(DynamoDbAsyncClient.class), + new RedeemedReceiptsManager(clock, Tables.REDEEMED_RECEIPTS.tableName(), + dynamoDbClient, Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -1419,6 +1583,8 @@ class AccountsTest { clock, dynamoDbClient, mock(DynamoDbAsyncClient.class), + new RedeemedReceiptsManager(clock, Tables.REDEEMED_RECEIPTS.tableName(), + dynamoDbClient, Duration.ofDays(30)), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -1889,11 +2055,12 @@ class AccountsTest { assertInstanceOf(DeviceIdDeserializer.DeviceIdDeserializationException.class, cause); } - @Test - void testRegenerateConstraints() { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testRegenerateConstraints(final boolean numberless) { final Instant usernameHoldExpiration = clock.instant().plus(Accounts.USERNAME_HOLD_DURATION).truncatedTo(ChronoUnit.SECONDS); - final Account account = nextRandomAccount(); + final Account account = numberless ? generateNumberlessAccount(UUID.randomUUID()) : nextRandomAccount(); account.setUsernameHash(USERNAME_HASH_1); account.setUsernameLinkDetails(UUID.randomUUID(), ENCRYPTED_USERNAME_1); account.setUsernameHolds(List.of(new Account.UsernameHold(USERNAME_HASH_2, usernameHoldExpiration.getEpochSecond()))); @@ -1902,9 +2069,9 @@ class AccountsTest { accounts.regenerateConstraints(account).join(); // Check that constraints do what they should from a functional perspective - { + if (!numberless) { final Account conflictingNumberAccount = nextRandomAccount(); - conflictingNumberAccount.setNumber(account.getNumber(), account.getIdentifier(IdentityType.PNI)); + conflictingNumberAccount.setNumber(account.getNumberOptional().get(), account.getAccountIdentifier()); assertThrows(AccountAlreadyExistsException.class, () -> accounts.create(conflictingNumberAccount, Collections.emptyList())); @@ -1927,16 +2094,20 @@ class AccountsTest { } // Check that bare constraint records are written as expected - assertEquals(Optional.of(account.getIdentifier(IdentityType.ACI)), - getConstraintValue(Tables.NUMBERS.tableName(), Accounts.ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()))); + if (!numberless) { + assertEquals(Optional.of(account.getAccountIdentifier()), + getConstraintValue(Tables.NUMBERS.tableName(), Accounts.ATTR_ACCOUNT_E164, + AttributeValues.fromString(account.getNumberOptional().get()))); - assertEquals(Optional.of(account.getIdentifier(IdentityType.ACI)), - getConstraintValue(Tables.PNI_ASSIGNMENTS.tableName(), Accounts.ATTR_PNI_UUID, AttributeValues.fromUUID(account.getIdentifier(IdentityType.PNI)))); + assertEquals(Optional.of(account.getAccountIdentifier()), + getConstraintValue(Tables.PNI_ASSIGNMENTS.tableName(), Accounts.ATTR_PNI_UUID, + AttributeValues.fromUUID(account.getPhoneNumberIdentifierOptional().get()))); + } - assertEquals(Optional.of(new UsernameConstraint(account.getIdentifier(IdentityType.ACI), true, Optional.empty())), + assertEquals(Optional.of(new UsernameConstraint(account.getAccountIdentifier(), true, Optional.empty())), getUsernameConstraint(USERNAME_HASH_1)); - assertEquals(Optional.of(new UsernameConstraint(account.getIdentifier(IdentityType.ACI), false, Optional.of(usernameHoldExpiration))), + assertEquals(Optional.of(new UsernameConstraint(account.getAccountIdentifier(), false, Optional.of(usernameHoldExpiration))), getUsernameConstraint(USERNAME_HASH_2)); } @@ -2016,12 +2187,18 @@ class AccountsTest { final Map item = new HashMap<>(Map.of( Accounts.KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier()), - Accounts.ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()), - Accounts.ATTR_PNI_UUID, AttributeValues.fromUUID(account.getPhoneNumberIdentifier()), Accounts.ATTR_ACCOUNT_DATA, accountData, Accounts.ATTR_VERSION, AttributeValues.fromInt(account.getVersion()), Accounts.ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.isDiscoverableByPhoneNumber()))); + account.getNumberOptional() + .map(AttributeValues::fromString) + .ifPresent(number -> item.put(Accounts.ATTR_ACCOUNT_E164, number)); + + account.getPhoneNumberIdentifierOptional() + .map(AttributeValues::fromUUID) + .ifPresent(pni -> item.put(Accounts.ATTR_PNI_UUID, pni)); + account.getUnidentifiedAccessKey() .map(AttributeValues::fromByteArray) .ifPresent(uak -> item.put(Accounts.ATTR_UAK, uak)); @@ -2080,6 +2257,14 @@ 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) { + throw new IllegalStateException(e); + } + } + private static Account nextRandomAccount() { final String nextNumber = "+1800%07d".formatted(ACCOUNT_COUNTER.getAndIncrement()); return generateAccount(nextNumber, UUID.randomUUID(), UUID.randomUUID()); @@ -2089,17 +2274,21 @@ class AccountsTest { return generateAccount(null, uuid, null); } - private static Account generateAccount(String number, UUID uuid, final UUID pni) { + private static Account generateAccount(@Nullable final String number, final UUID uuid, @Nullable final UUID pni) { Device device = generateDevice(DEVICE_ID_1); return generateAccount(number, uuid, pni, List.of(device)); } - private static Account generateAccount(String number, UUID uuid, final UUID pni, List devices) { + private static Account generateAccount(@Nullable final String number, final UUID uuid, @Nullable final UUID pni, final List devices) { + return generateAccount(number, uuid, pni, devices, TestRandomUtil.nextBytes(16)); + } + + private static Account generateAccount(@Nullable final String number, final UUID uuid, @Nullable final UUID pni, final List devices, final byte[] accountRecoveryPassword) { final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]; final Random random = new Random(System.currentTimeMillis()); Arrays.fill(unidentifiedAccessKey, (byte) random.nextInt(255)); - return AccountsHelper.generateTestAccount(number, uuid, pni, devices, unidentifiedAccessKey); + return AccountsHelper.generateTestAccount(number, uuid, pni, devices, unidentifiedAccessKey, accountRecoveryPassword); } private void assertPhoneNumberConstraintExists(final String number, final UUID uuid) { @@ -2144,6 +2333,19 @@ class AccountsTest { assertThat(pniConstraintResponse.hasItem()).isFalse(); } + private void assertRedeemedReceiptConstraintExists(final ReceiptCredentialPresentation receiptCredentialPresentation, final UUID accountId) { + final GetItemResponse receiptConstraintResponse = DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem( + GetItemRequest.builder() + .tableName(Tables.REDEEMED_RECEIPTS.tableName()) + .key(Map.of(RedeemedReceiptsManager.KEY_SERIAL, AttributeValues.b(receiptCredentialPresentation.getReceiptSerial().serialize()))) + .build() + ); + assertThat(receiptConstraintResponse.hasItem()).isTrue(); + assertThat(AttributeValues.getUUID(receiptConstraintResponse.item(), RedeemedReceiptsManager.KEY_ACCOUNT_UUID, null)).isEqualTo(accountId); + assertThat(AttributeValues.getLong(receiptConstraintResponse.item(), RedeemedReceiptsManager.KEY_RECEIPT_LEVEL, -1)).isEqualTo(receiptCredentialPresentation.getReceiptLevel()); + assertThat(AttributeValues.getLong(receiptConstraintResponse.item(), RedeemedReceiptsManager.KEY_RECEIPT_EXPIRATION, -1)).isEqualTo(receiptCredentialPresentation.getReceiptExpirationTime()); + } + private Map readAccount(final UUID uuid) { final DynamoDbClient db = DYNAMO_DB_EXTENSION.getDynamoDbClient(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java index f5e326527..8f2ab921d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java @@ -99,6 +99,8 @@ public class AddRemoveDeviceIntegrationTest { clock, DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + new RedeemedReceiptsManager(clock, DynamoDbExtensionSchema.Tables.REDEEMED_RECEIPTS.tableName(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), Duration.ofDays(30)), DynamoDbExtensionSchema.Tables.ACCOUNTS.tableName(), DynamoDbExtensionSchema.Tables.NUMBERS.tableName(), DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS.tableName(), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ReceiptCredentialTestUtil.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ReceiptCredentialTestUtil.java new file mode 100644 index 000000000..65832c87e --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ReceiptCredentialTestUtil.java @@ -0,0 +1,50 @@ +package org.whispersystems.textsecuregcm.storage; + +import org.signal.libsignal.zkgroup.InvalidInputException; +import org.signal.libsignal.zkgroup.ServerSecretParams; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; +import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; +import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; + +public class ReceiptCredentialTestUtil { + private static final ServerSecretParams RECEIPT_PARAMS = ServerSecretParams.generate(); + + public static ReceiptCredentialPresentation receiptPresentation() + throws InvalidInputException, VerificationFailedException { + + return receiptPresentation(new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)), Instant.now().plus( + Duration.ofDays(30)), 1); + } + + public static ReceiptCredentialPresentation receiptPresentation(final Instant expiresAt, final long receiptLevel) + throws InvalidInputException, VerificationFailedException { + + return receiptPresentation(new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)), expiresAt, receiptLevel); + } + + public static ReceiptCredentialPresentation receiptPresentation(final ReceiptSerial receiptSerial, final Instant expiresAt, final long receiptLevel) + throws VerificationFailedException { + + final ServerZkReceiptOperations serverOperations = new ServerZkReceiptOperations(RECEIPT_PARAMS); + final ClientZkReceiptOperations clientOperations = + new ClientZkReceiptOperations(RECEIPT_PARAMS.getPublicParams()); + + final ReceiptCredentialRequestContext requestContext = + clientOperations.createReceiptCredentialRequestContext(receiptSerial); + + final ReceiptCredentialResponse response = serverOperations.issueReceiptCredential(requestContext.getRequest(), + expiresAt.truncatedTo(ChronoUnit.DAYS).getEpochSecond(), + receiptLevel); + + return clientOperations.createReceiptCredentialPresentation( + clientOperations.receiveReceiptCredential(requestContext, response)); + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java index b1d7beeff..eb02c1fde 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java @@ -22,6 +22,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; +import jakarta.annotation.Nullable; import org.junit.platform.commons.util.StringUtils; import org.mockito.MockingDetails; import org.mockito.stubbing.Stubbing; @@ -38,19 +39,26 @@ import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo; import org.whispersystems.textsecuregcm.storage.DeviceSpec; import org.whispersystems.textsecuregcm.util.SystemMapper; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; public class AccountsHelper { - public static Account generateTestAccount(String number, List devices) { + public static Account generateTestAccount(@Nullable String number, List devices) { return generateTestAccount(number, UUID.randomUUID(), UUID.randomUUID(), devices, null); } - public static Account generateTestAccount(String number, UUID uuid, final UUID phoneNumberIdentifier, List devices, byte[] unidentifiedAccessKey) { + public static Account generateTestAccount(@Nullable String number, UUID uuid, final @Nullable UUID phoneNumberIdentifier, List devices, byte[] unidentifiedAccessKey) { + return generateTestAccount(number, uuid, phoneNumberIdentifier, devices, unidentifiedAccessKey, TestRandomUtil.nextBytes(16)); + + } + + public static Account generateTestAccount(@Nullable String number, UUID uuid, final @Nullable UUID phoneNumberIdentifier, List devices, byte[] unidentifiedAccessKey, final byte[] accountRecoveryPassword) { final Account account = new Account(); account.setNumber(number, phoneNumberIdentifier); account.setAccountIdentifier(uuid); devices.forEach(account::addDevice); account.setUnidentifiedAccessKey(unidentifiedAccessKey); + account.setAccountRecoveryPassword(accountRecoveryPassword); return account; }