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 5a7b99f5f..f9b366159 100644 --- a/integration-tests/src/main/java/org/signal/integration/Operations.java +++ b/integration-tests/src/main/java/org/signal/integration/Operations.java @@ -101,9 +101,9 @@ public final class Operations { new IdentityKey(aciIdentityKeyPair.getPublicKey()), new IdentityKey(pniIdentityKeyPair.getPublicKey()), new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair), - generateSignedECPreKey(2, pniIdentityKeyPair), + Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)), generateSignedKEMPreKey(3, aciIdentityKeyPair), - generateSignedKEMPreKey(4, pniIdentityKeyPair), + Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)), Optional.empty(), Optional.empty())); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java index 37a5621b4..bd00e5205 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceController.java @@ -42,6 +42,7 @@ import java.util.EnumMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicInteger; @@ -72,6 +73,7 @@ import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountsManager; 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.LinkDeviceTokenAlreadyUsedException; import org.whispersystems.textsecuregcm.storage.PersistentTimer; @@ -240,6 +242,12 @@ public class DeviceController { final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest(); final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes(); + if (deviceAttributes.phoneNumberIdentityRegistrationId() == null || + deviceActivationRequest.pniSignedPreKey().isEmpty() || + deviceActivationRequest.pniPqLastResortPreKey().isEmpty()) { + throw new WebApplicationException("PNI-associated info must all be provided", 422); + } + rateLimiters.getVerifyDeviceLimiter().validate(account.getAccountIdentifier()); final boolean allKeysValid = @@ -248,7 +256,7 @@ public class DeviceController { userAgent, "link-device") && PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.PNI), - List.of(deviceActivationRequest.pniSignedPreKey(), deviceActivationRequest.pniPqLastResortPreKey()), + List.of(deviceActivationRequest.pniSignedPreKey().get(), deviceActivationRequest.pniPqLastResortPreKey().get()), userAgent, "link-device"); @@ -284,15 +292,17 @@ public class DeviceController { authorizationHeader.getPassword(), signalAgent, capabilities, - deviceAttributes.registrationId(), - deviceAttributes.phoneNumberIdentityRegistrationId(), + new DeviceIdentityInfo( + deviceAttributes.registrationId(), + deviceActivationRequest.aciSignedPreKey(), + deviceActivationRequest.aciPqLastResortPreKey()), + Optional.of(new DeviceIdentityInfo( + deviceAttributes.phoneNumberIdentityRegistrationId(), + deviceActivationRequest.pniSignedPreKey().get(), + deviceActivationRequest.pniPqLastResortPreKey().get())), deviceAttributes.fetchesMessages(), deviceActivationRequest.apnToken(), - deviceActivationRequest.gcmToken(), - deviceActivationRequest.aciSignedPreKey(), - deviceActivationRequest.pniSignedPreKey(), - deviceActivationRequest.aciPqLastResortPreKey(), - deviceActivationRequest.pniPqLastResortPreKey()), + deviceActivationRequest.gcmToken()), linkDeviceRequest.verificationCode()); return new LinkDeviceResponse( 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 4fef509be..fa3910382 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java @@ -61,6 +61,7 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker; import org.whispersystems.textsecuregcm.storage.Account; 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.util.HeaderUtils; import org.whispersystems.textsecuregcm.util.Util; @@ -132,6 +133,10 @@ 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); } @@ -202,15 +207,18 @@ public class RegistrationController { password, signalAgent, registrationRequest.accountAttributes().getCapabilities(), - registrationRequest.accountAttributes().getRegistrationId(), - registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId(), + new DeviceIdentityInfo( + registrationRequest.accountAttributes().getRegistrationId(), + registrationRequest.deviceActivationRequest().aciSignedPreKey(), + registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()), + Optional.of(new DeviceIdentityInfo( + registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().get(), + // We've already validated the presence of PNI keys by this point + registrationRequest.deviceActivationRequest().pniSignedPreKey().get(), + registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().get())), registrationRequest.accountAttributes().getFetchesMessages(), registrationRequest.deviceActivationRequest().apnToken(), - registrationRequest.deviceActivationRequest().gcmToken(), - registrationRequest.deviceActivationRequest().aciSignedPreKey(), - registrationRequest.deviceActivationRequest().pniSignedPreKey(), - registrationRequest.deviceActivationRequest().aciPqLastResortPreKey(), - registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()), + registrationRequest.deviceActivationRequest().gcmToken()), userAgent); if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) { 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 8449297dd..90152e942 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountAttributes.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/AccountAttributes.java @@ -52,7 +52,7 @@ public class AccountAttributes { public AccountAttributes( final boolean fetchesMessages, final int registrationId, - final int phoneNumberIdentifierRegistrationId, + final Integer phoneNumberIdentifierRegistrationId, final byte[] name, final String registrationLock, final boolean discoverableByPhoneNumber, @@ -71,8 +71,8 @@ public class AccountAttributes { return deviceAttributes.registrationId(); } - public int getPhoneNumberIdentityRegistrationId() { - return deviceAttributes.phoneNumberIdentityRegistrationId(); + public Optional getPhoneNumberIdentityRegistrationId() { + return Optional.ofNullable(deviceAttributes.phoneNumberIdentityRegistrationId()); } public byte[] getName() { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceActivationRequest.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceActivationRequest.java index e722062ac..a16fcee1f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceActivationRequest.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceActivationRequest.java @@ -15,12 +15,10 @@ public record DeviceActivationRequest( """) ECSignedPreKey aciSignedPreKey, - @NotNull - @Valid - @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """ - A signed EC pre-key to be associated with this account's PNI. + @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ + If the account has a phone number, a signed EC pre-key to be associated with this account's PNI. """) - ECSignedPreKey pniSignedPreKey, + Optional<@Valid ECSignedPreKey> pniSignedPreKey, @NotNull @Valid @@ -29,12 +27,10 @@ public record DeviceActivationRequest( """) KEMSignedPreKey aciPqLastResortPreKey, - @NotNull - @Valid - @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """ - A signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI. + @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ + If the account has a phone number, a signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI. """) - KEMSignedPreKey pniPqLastResortPreKey, + Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey, @Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """ An APNs token set for the account's primary device. If provided, the account's primary diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceAttributes.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceAttributes.java index 15c84b53a..7ecb10031 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceAttributes.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/DeviceAttributes.java @@ -24,7 +24,9 @@ public record DeviceAttributes( int registrationId, - @JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId, + @JsonProperty("pniRegistrationId") + @Nullable + Integer phoneNumberIdentityRegistrationId, @JsonSerialize(using = ByteArrayAdapter.Serializing.class) @@ -41,6 +43,7 @@ public record DeviceAttributes( @AssertTrue @Schema(hidden = true) public boolean isEachRegistrationIdValid() { - return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId); + return validRegistrationId(registrationId) && + (phoneNumberIdentityRegistrationId == null || validRegistrationId(phoneNumberIdentityRegistrationId)); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/entities/LinkDeviceRequest.java b/service/src/main/java/org/whispersystems/textsecuregcm/entities/LinkDeviceRequest.java index 0a5fe4c69..23f6b4e22 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/LinkDeviceRequest.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/LinkDeviceRequest.java @@ -33,9 +33,9 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI public LinkDeviceRequest(@JsonProperty("verificationCode") String verificationCode, @JsonProperty("accountAttributes") DeviceAttributes deviceAttributes, @JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey, - @JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey, + @JsonProperty("pniSignedPreKey") Optional<@Valid ECSignedPreKey> pniSignedPreKey, @JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey, - @JsonProperty("pniPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey pniPqLastResortPreKey, + @JsonProperty("pniPqLastResortPreKey") Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey, @JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken, @JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) { 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 319d56aba..fa46e46d9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/entities/RegistrationRequest.java @@ -75,14 +75,14 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT public boolean isEverySignedKeyValid(@Nullable final String userAgent) { if (deviceActivationRequest().aciSignedPreKey() == null || - deviceActivationRequest().pniSignedPreKey() == null || + deviceActivationRequest().pniSignedPreKey().isEmpty() || deviceActivationRequest().aciPqLastResortPreKey() == null || - deviceActivationRequest().pniPqLastResortPreKey() == null) { + deviceActivationRequest().pniPqLastResortPreKey().isEmpty()) { return false; } return PreKeySignatureValidator.validatePreKeySignatures(aciIdentityKey(), List.of(deviceActivationRequest().aciSignedPreKey(), deviceActivationRequest().aciPqLastResortPreKey()), userAgent, "register") - && PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey(), deviceActivationRequest().pniPqLastResortPreKey()), userAgent, "register"); + && 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 b614cb5d5..601d33f93 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java @@ -26,7 +26,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -213,25 +212,27 @@ public class Accounts { boolean create(final Account account, final List additionalWriteItems) throws AccountAlreadyExistsException { + if (account.getNumberOptional().isEmpty() || account.getPhoneNumberIdentifierOptional().isEmpty()) { + throw new IllegalArgumentException("Phone number and phone number identifier must be set"); + } final Timer.Sample sample = Timer.start(); try { final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier()); - final AttributeValue numberAttr = AttributeValues.fromString(account.getNumber()); - final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifier()); + final AttributeValue numberAttr = AttributeValues.fromString(account.getNumberOptional().get()); + final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifierOptional().get()); final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent( phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr); - final TransactWriteItem phoneNumberIdentifierConstraintPut = buildConstraintTablePutIfAbsent( phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniUuidAttr); - final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, numberAttr, pniUuidAttr); + final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, Optional.of(numberAttr), Optional.of(pniUuidAttr)); // Clear any "recently deleted account" record for this number since, if it existed, we've used its old ACI for // the newly-created account. - final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier()); + final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifierOptional().get()); final Collection writeItems = new ArrayList<>( List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete)); @@ -303,11 +304,11 @@ public class Accounts { final Collection additionalWriteItems) { if (!existingAccount.getAccountIdentifier().equals(accountToCreate.getAccountIdentifier()) || - !existingAccount.getPhoneNumberIdentifier().equals(accountToCreate.getPhoneNumberIdentifier())) { + !existingAccount.getPhoneNumberIdentifierOptional().equals(accountToCreate.getPhoneNumberIdentifierOptional())) { log.error("Reclaimed accounts must match. Old account {}:{}:{}, New account {}:{}:{}", - existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(), - accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier()); + existingAccount.getAccountIdentifier(), existingAccount.getNumberOptional().map(Accounts::redactPhoneNumber), existingAccount.getPhoneNumberIdentifierOptional(), + accountToCreate.getAccountIdentifier(), accountToCreate.getNumberOptional().map(Accounts::redactPhoneNumber), accountToCreate.getPhoneNumberIdentifierOptional()); throw new IllegalArgumentException("reclaimed accounts must match"); } @@ -378,24 +379,28 @@ public class Accounts { // Phone number canonicalization means that a user can use a different phone number in the same equivalence class // to reclaim the account. - if (!existingAccount.getNumber().equals(accountToCreate.getNumber())) { - if (getAlternateForms(existingAccount.getNumber()).contains(accountToCreate.getNumber())) { + if (!existingAccount.getNumberOptional().equals(accountToCreate.getNumberOptional()) + && existingAccount.getNumberOptional().isPresent() + && accountToCreate.getNumberOptional().isPresent()) { + final String existingAccountNumber = existingAccount.getNumberOptional().get(); + final String accountToCreateNumber = accountToCreate.getNumberOptional().get(); + if (getAlternateForms(existingAccountNumber).contains(accountToCreateNumber)) { final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getAccountIdentifier()); - final AttributeValue numberAttr = AttributeValues.fromString(accountToCreate.getNumber()); + final AttributeValue numberAttr = AttributeValues.fromString(accountToCreateNumber); final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent( phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr); - writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccount.getNumber())); + writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccountNumber)); writeItems.add(phoneNumberConstraintPut); } else { throw new IllegalStateException(String.format("Reclaiming account with a non-equivalent phone number. Old account %s:%s:%s, new account %s:%s:%s", - existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(), - accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier())); + existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccountNumber), existingAccount.getPhoneNumberIdentifierOptional(), + accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreateNumber), accountToCreate.getPhoneNumberIdentifierOptional())); } } final int updateAccountItemIndex = writeItems.size(); - writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumber()).transactItem()); + writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumberOptional()).transactItem()); writeItems.addAll(additionalWriteItems); return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build()) @@ -408,10 +413,10 @@ public class Accounts { if (unwrapped instanceof TransactionCanceledException te) { if (Accounts.conditionalCheckFailed(te.cancellationReasons().get(updateAccountItemIndex))) { final Map item = te.cancellationReasons().get(updateAccountItemIndex).item(); - final String existingNumber = AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null); - if (!existingAccount.getNumber().equals(existingNumber)) { + final Optional existingNumber = Optional.ofNullable(AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null)); + if (!existingAccount.getNumberOptional().equals(existingNumber)) { log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}", - existingAccount.getAccountIdentifier(), existingAccount.getNumber(), existingNumber); + existingAccount.getAccountIdentifier(), existingAccount.getNumberOptional(), existingNumber); throw new UnexpectedExistingPhoneNumberException(); } } @@ -990,21 +995,27 @@ public class Accounts { static UpdateAccountSpec forReclaimedAccount( final String accountTableName, final Account account, - final String expectedExistingE164) { + final Optional maybeExpectedExistingE164) { final UpdateAccountSpec base = forAccount(accountTableName, account); final Map attrValues = new HashMap<>(base.attrValues()); - attrValues.put(":number", AttributeValues.fromString(account.getNumber())); - final UpdateExpression updateExpression = base.updateExpression(); final List setClauses = new ArrayList<>(updateExpression.setClauses()); - setClauses.add("#number = :number"); - final MembershipExpression membershipExpression = MembershipExpression.build(getAlternateForms(expectedExistingE164)); - attrValues.putAll(membershipExpression.values()); + final String conditionExpression = account.getNumberOptional() + .map(number -> { + attrValues.put(":number", AttributeValues.fromString(number)); + setClauses.add("#number = :number"); - // Defensive check: we should only update the e164 to another e164 in the same equivalence class - final String conditionExpression = base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression()); + final MembershipExpression membershipExpression = maybeExpectedExistingE164 + .map(e164 -> MembershipExpression.build(getAlternateForms(e164))) + .orElseThrow(() -> new IllegalArgumentException("E164 must be present on existing account")); + + attrValues.putAll(membershipExpression.values()); + // Defensive check: if an e164 exists on the account, we should only update it to another e164 in the same equivalence class + return base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression()); + }) + .orElse(base.conditionExpression()); return new UpdateAccountSpec( base.tableName(), @@ -1484,13 +1495,14 @@ public class Accounts { private TransactWriteItem buildAccountPut( final Account account, final AttributeValue uuidAttr, - final AttributeValue numberAttr, - final AttributeValue pniUuidAttr) { + final Optional maybeNumberAttr, + final Optional maybePniUuidAttr) { + if (maybeNumberAttr.isPresent() != maybePniUuidAttr.isPresent()) { + throw new IllegalArgumentException("Number and PNI attribute values must both be provided together or not at all"); + } final Map item = new HashMap<>(Map.of( KEY_ACCOUNT_UUID, uuidAttr, - ATTR_ACCOUNT_E164, numberAttr, - ATTR_PNI_UUID, pniUuidAttr, ATTR_ACCOUNT_DATA, accountDataAttributeValue(account), ATTR_VERSION, AttributeValues.fromInt(account.getVersion()), ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.isDiscoverableByPhoneNumber()))); @@ -1500,14 +1512,24 @@ public class Accounts { .map(AttributeValues::fromByteArray) .ifPresent(uak -> item.put(ATTR_UAK, uak)); - return TransactWriteItem.builder() - .put(Put.builder() - .conditionExpression("attribute_not_exists(#pni) OR #pni = :pni") - .expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID)) - .expressionAttributeValues(Map.of(":pni", pniUuidAttr)) + final Put put = maybeNumberAttr.map(numberAttr -> { + item.put(ATTR_ACCOUNT_E164, numberAttr); + item.put(ATTR_PNI_UUID, maybePniUuidAttr.get()); + return Put.builder() + .tableName(accountsTableName) + .item(item) + .conditionExpression("attribute_not_exists(#pni) OR #pni = :pni") + .expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID)) + .expressionAttributeValues(Map.of(":pni", maybePniUuidAttr.get())) + .build(); + }) + .orElseGet(() -> Put.builder() .tableName(accountsTableName) .item(item) - .build()) + .build()); + + return TransactWriteItem.builder() + .put(put) .build(); } @@ -1656,7 +1678,6 @@ public class Accounts { @Nonnull static Account fromItem(final Map item) { if (!item.containsKey(ATTR_ACCOUNT_DATA) - || !item.containsKey(ATTR_ACCOUNT_E164) || !item.containsKey(KEY_ACCOUNT_UUID) || !item.containsKey(ATTR_CANONICALLY_DISCOVERABLE)) { throw new RuntimeException("item missing values"); @@ -1667,17 +1688,15 @@ public class Accounts { final UUID accountIdentifier = UUIDUtil.fromByteBuffer(item.get(KEY_ACCOUNT_UUID).b().asByteBuffer()); final UUID phoneNumberIdentifierFromAttribute = AttributeValues.getUUID(item, ATTR_PNI_UUID, null); - if (account.getPhoneNumberIdentifier() == null || phoneNumberIdentifierFromAttribute == null || - !Objects.equals(account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute)) { - - log.warn("Missing or mismatched PNIs for account {}. From JSON: {}; from attribute: {}", - accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute); + if (!account.getPhoneNumberIdentifierOptional().equals(Optional.ofNullable(phoneNumberIdentifierFromAttribute))) { + log.warn("Mismatched PNIs for account {}. From JSON: {}; from attribute: {}", + accountIdentifier, account.getPhoneNumberIdentifierOptional(), phoneNumberIdentifierFromAttribute); } - final String attributeNumber = item.get(ATTR_ACCOUNT_E164).s(); - if (account.getNumber() == null || !account.getNumber().equals(attributeNumber)) { - log.error("Missing or mismatched phone numbers for account {}. From JSON: {}; from attribute: {}", - accountIdentifier, account.getNumber(), attributeNumber); + final String attributeNumber = AttributeValues.getString(item, ATTR_ACCOUNT_E164, null); + if (!account.getNumberOptional().equals(Optional.ofNullable(attributeNumber))) { + log.error("Mismatched phone numbers for account {}. From JSON: {}; from attribute: {}", + accountIdentifier, account.getNumberOptional(), attributeNumber); } account.setNumber(attributeNumber, phoneNumberIdentifierFromAttribute); 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 99977a2b9..2e0f4bd95 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -96,7 +96,6 @@ import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledExcepti public class AccountsManager extends RedisPubSubAdapter implements Managed { - private static final Timer createTimer = Metrics.timer(name(AccountsManager.class, "create")); private static final Timer updateTimer = Metrics.timer(name(AccountsManager.class, "update")); private static final Timer getByNumberTimer = Metrics.timer(name(AccountsManager.class, "getByNumber")); private static final Timer getByUsernameHashTimer = Metrics.timer(name(AccountsManager.class, "getByUsernameHash")); @@ -115,6 +114,8 @@ public class AccountsManager extends RedisPubSubAdapter implemen private static final String DELETION_REASON_TAG_NAME = "reason"; private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class, "registrationIdRedisKeyCounter"); + private static final String CREATE_TIMER_NAME = name(AccountsManager.class, "create"); + private static final String HAS_NUMBER_TAG_NAME = "hasNumber"; private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class); @@ -287,20 +288,23 @@ public class AccountsManager extends RedisPubSubAdapter implemen }); } - public Account create(final String number, - final AccountAttributes accountAttributes, + /// Create an account without a phone number. + /// + /// @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 primaryDeviceSpec the attributes to set on the account's primary device + /// @param userAgent the user agent of the client requesting to create an account + /// + /// @return the created account + public Account create(final AccountAttributes accountAttributes, final List accountBadges, final IdentityKey aciIdentityKey, - final IdentityKey pniIdentityKey, final DeviceSpec primaryDeviceSpec, - @Nullable final String userAgent) throws InterruptedException { - - final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(); - - return createTimer.record(() -> { + @Nullable final String userAgent) { + return Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "false").record(() -> { try { - return accountLockManager.withLock(Set.of(pni), - () -> create(number, pni, accountAttributes, accountBadges, aciIdentityKey, pniIdentityKey, primaryDeviceSpec, userAgent), accountLockExecutor); + 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; @@ -308,8 +312,18 @@ public class AccountsManager extends RedisPubSubAdapter implemen }); } - private Account create(final String number, - final UUID pni, + /// Create an account with a phone number. + /// + /// @param number the e164-formatted phone number to set on the account + /// @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 pniIdentityKey the PNI identity key to associate with the account + /// @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 + /// + /// @return the created account + public Account create(final String number, final AccountAttributes accountAttributes, final List accountBadges, final IdentityKey aciIdentityKey, @@ -317,18 +331,43 @@ public class AccountsManager extends RedisPubSubAdapter implemen final DeviceSpec primaryDeviceSpec, @Nullable final String userAgent) { + final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(); + + 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); + } catch (final RuntimeException e) { + logger.error("Unexpected exception while creating account", e); + throw e; + } + }); + } + + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + private Account create(final Optional maybeNumber, + final Optional maybePni, + final AccountAttributes accountAttributes, + final List accountBadges, + final IdentityKey aciIdentityKey, + final Optional maybePniIdentityKey, + final DeviceSpec primaryDeviceSpec, + @Nullable final String userAgent) { final Account account = new Account(); final Optional maybeRecentlyDeletedAccountIdentifier = - accounts.findRecentlyDeletedAccountIdentifier(pni); + maybePni.flatMap(accounts::findRecentlyDeletedAccountIdentifier); + + maybeNumber.ifPresent(number -> { + account.setNumber(number, maybePni.orElseThrow(() -> new IllegalArgumentException("PNI must be provided if the account has a number"))); + account.setPhoneNumberIdentityKey(maybePniIdentityKey.orElseThrow(() -> new IllegalArgumentException("PNI identity key must be provided if the account has a number"))); + account.setRegistrationLockFromAttributes(accountAttributes); + }); // Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is // re-registering. account.setAccountIdentifier(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID)); - account.setNumber(number, pni); account.setIdentityKey(aciIdentityKey); - account.setPhoneNumberIdentityKey(pniIdentityKey); account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock, aciIdentityKey)); - account.setRegistrationLockFromAttributes(accountAttributes); account.setUnidentifiedAccessKey(accountAttributes.getUnidentifiedAccessKey()); account.setUnrestrictedUnidentifiedAccess(accountAttributes.isUnrestrictedUnidentifiedAccess()); account.setDiscoverableByPhoneNumber(accountAttributes.isDiscoverableByPhoneNumber()); @@ -351,13 +390,13 @@ public class AccountsManager extends RedisPubSubAdapter implemen String previousPushTokenType = null; try { - accounts.create(account, keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI), - account.getIdentifier(IdentityType.PNI), + accounts.create(account, keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), + account.getPhoneNumberIdentifierOptional(), Device.PRIMARY_ID, - primaryDeviceSpec.aciSignedPreKey(), - primaryDeviceSpec.pniSignedPreKey(), - primaryDeviceSpec.aciPqLastResortPreKey(), - primaryDeviceSpec.pniPqLastResortPreKey())); + primaryDeviceSpec.aciInfo().signedPreKey(), + primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), + primaryDeviceSpec.aciInfo().pqLastResortPreKey(), + primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey))); } catch (final AccountAlreadyExistsException e) { accountCreationType = "re-registration"; @@ -369,17 +408,17 @@ public class AccountsManager extends RedisPubSubAdapter implemen previousPushTokenType = "none"; } - final UUID aci = e.getExistingAccount().getIdentifier(IdentityType.ACI); + final UUID aci = e.getExistingAccount().getAccountIdentifier(); account.setAccountIdentifier(aci); final List additionalWriteItems = Stream.concat( - keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI), - account.getIdentifier(IdentityType.PNI), + keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(), + account.getPhoneNumberIdentifierOptional(), Device.PRIMARY_ID, - primaryDeviceSpec.aciSignedPreKey(), - primaryDeviceSpec.pniSignedPreKey(), - primaryDeviceSpec.aciPqLastResortPreKey(), - primaryDeviceSpec.pniPqLastResortPreKey()).stream(), + primaryDeviceSpec.aciInfo().signedPreKey(), + primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), + primaryDeviceSpec.aciInfo().pqLastResortPreKey(), + primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey)).stream(), e.getExistingAccount().getDevices() .stream() .map(Device::getId) @@ -387,12 +426,12 @@ public class AccountsManager extends RedisPubSubAdapter implemen // transaction anyhow .filter(existingDeviceId -> existingDeviceId != Device.PRIMARY_ID) .flatMap(existingDeviceId -> - keysManager.buildWriteItemsForRemovedDevice(aci, pni, existingDeviceId).stream())) + keysManager.buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifierOptional(), existingDeviceId).stream())) .toList(); CompletableFuture.allOf( keysManager.deleteSingleUsePreKeys(aci), - keysManager.deleteSingleUsePreKeys(pni), + account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(aci), profilesManager.deleteAll(aci, false)) .thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(e.getExistingAccount())) @@ -406,7 +445,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen // We exclude the primary device's repeated-use keys from deletion because new keys were provided as // part of the account creation process, and we don't want to delete the keys that just got added. return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci), - keysManager.deleteSingleUsePreKeys(pni), + account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)), messagesManager.clear(aci), profilesManager.deleteAll(aci, false)); }) @@ -415,9 +454,9 @@ public class AccountsManager extends RedisPubSubAdapter implemen redisSet(account); - final boolean rrpCreated = accountAttributes.recoveryPassword().map(registrationRecoveryPassword -> - phoneNumberRecoveryPasswordsManager - .store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)) + final boolean phoneNumberRecoveryPasswordCreated = accountAttributes.recoveryPassword().map(phoneNumberRecoveryPassword -> + account.getPhoneNumberIdentifierOptional().map(pni -> phoneNumberRecoveryPasswordsManager.store(pni, phoneNumberRecoveryPassword)) + .orElse(false)) .orElse(false); changeNumberWaitingPeriodManager.handleAccountCreated(account.getAccountIdentifier(), clock.instant()); @@ -433,8 +472,8 @@ public class AccountsManager extends RedisPubSubAdapter implemen if (StringUtils.isNotBlank(previousPushTokenType)) { tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType)); } - if (accountAttributes.recoveryPassword().isPresent()) { - tags = tags.and(Tag.of("recoveryPasswordOutcome", rrpCreated ? "created" : "updated")); + if (accountAttributes.recoveryPassword().isPresent() && account.getPhoneNumberIdentifierOptional().isPresent()) { + tags = tags.and(Tag.of("recoveryPasswordOutcome", phoneNumberRecoveryPasswordCreated ? "created" : "updated")); } Metrics.counter(CREATE_COUNTER_NAME, tags).increment(); return account; @@ -469,12 +508,12 @@ public class AccountsManager extends RedisPubSubAdapter implemen final List additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice( account.getIdentifier(IdentityType.ACI), - account.getIdentifier(IdentityType.PNI), + account.getPhoneNumberIdentifierOptional(), nextDeviceId, - deviceSpec.aciSignedPreKey(), - deviceSpec.pniSignedPreKey(), - deviceSpec.aciPqLastResortPreKey(), - deviceSpec.pniPqLastResortPreKey())); + deviceSpec.aciInfo().signedPreKey(), + deviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey), + deviceSpec.aciInfo().pqLastResortPreKey(), + deviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey))); additionalWriteItems.add(accounts.buildTransactWriteItemForLinkDevice(linkDeviceToken, LINK_DEVICE_TOKEN_EXPIRATION_DURATION)); @@ -662,7 +701,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen final List additionalWriteItems = new ArrayList<>( keysManager.buildWriteItemsForRemovedDevice( account.getIdentifier(IdentityType.ACI), - account.getIdentifier(IdentityType.PNI), + account.getPhoneNumberIdentifierOptional(), deviceId)); try { @@ -1234,7 +1273,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen account.getDevices().stream() .flatMap(device -> keysManager.buildWriteItemsForRemovedDevice( account.getIdentifier(IdentityType.ACI), - account.getIdentifier(IdentityType.PNI), + account.getPhoneNumberIdentifierOptional(), device.getId()) .stream()) .forEach(additionalWriteItems::add); @@ -1273,8 +1312,8 @@ public class AccountsManager extends RedisPubSubAdapter implemen cacheCluster.useCluster(connection -> { final RedisAdvancedClusterCommands commands = connection.sync(); - commands.setex(getAccountMapKey(account.getPhoneNumberIdentifier().toString()), CACHE_TTL_SECONDS, - account.getAccountIdentifier().toString()); + account.getPhoneNumberIdentifierOptional().ifPresent(pni -> + commands.setex(getAccountMapKey(pni.toString()), CACHE_TTL_SECONDS, account.getAccountIdentifier().toString())); commands.setex(getAccountEntityKey(account.getAccountIdentifier()), CACHE_TTL_SECONDS, accountJson); }); } catch (JsonProcessingException e) { @@ -1293,10 +1332,10 @@ public class AccountsManager extends RedisPubSubAdapter implemen } return cacheCluster.withCluster(connection -> CompletableFuture.allOf( - connection.async().setex( - getAccountMapKey(account.getPhoneNumberIdentifier().toString()), CACHE_TTL_SECONDS, - account.getAccountIdentifier().toString()) - .toCompletableFuture(), + account.getPhoneNumberIdentifierOptional().map(pni -> + connection.async().setex(getAccountMapKey(pni.toString()), CACHE_TTL_SECONDS, account.getAccountIdentifier().toString()) + .toCompletableFuture()) + .orElseGet(() -> CompletableFuture.completedFuture(null)), connection.async().setex(getAccountEntityKey(account.getAccountIdentifier()), CACHE_TTL_SECONDS, accountJson) .toCompletableFuture())); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java index 27b14c47b..8f699d319 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Device.java @@ -9,15 +9,17 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.google.common.annotations.VisibleForTesting; import java.time.Duration; import java.util.Collections; import java.util.EnumSet; import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.Nullable; -import com.google.common.annotations.VisibleForTesting; import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.util.ByteArrayAdapter; @@ -71,7 +73,8 @@ public class Device { private int registrationId; @JsonProperty("pniRegistrationId") - private int phoneNumberIdentityRegistrationId; + @Nullable + private Integer phoneNumberIdentityRegistrationId; @JsonProperty private long lastSeen; @@ -221,13 +224,43 @@ public class Device { return getId() == PRIMARY_ID; } + /// Returns the registration ID for this device associated with the given identity type. + /// + /// @param identityType the type of identity for which to return the registration ID + /// + /// @return the registration ID for the given identity type for the device + /// + /// @throws NoSuchElementException if a PNI identity is requested for a device attached + /// to an account without a phone number identity. + /// + /// @deprecated Please use [#getAccountRegistrationId()] or + /// [#getPhoneNumberIdentityRegistrationId()] instead. + @Deprecated public int getRegistrationId(final IdentityType identityType) { return switch (identityType) { - case ACI -> registrationId; - case PNI -> phoneNumberIdentityRegistrationId; + case ACI -> getAccountRegistrationId(); + case PNI -> getPhoneNumberIdentityRegistrationId().orElseThrow(NoSuchElementException::new); }; } + /// Returns the registration ID for this device associated with its account's account identity. + /// + /// @return the registration ID for this device associated with its account's account identity. + public int getAccountRegistrationId() { + return registrationId; + } + + /// Returns the registration ID for this device associated with its + /// account's phone-number identity, or an empty Optional if the account + /// does not have a phone number. + /// + /// @return the registration ID for this device associated with its + /// account's phone-number identity, or an empty Optional if the account + /// does not have a phone number. + public Optional getPhoneNumberIdentityRegistrationId() { + return Optional.ofNullable(phoneNumberIdentityRegistrationId); + } + public void setRegistrationId(int registrationId) { this.registrationId = registrationId; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceIdentityInfo.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceIdentityInfo.java new file mode 100644 index 000000000..aeddf4fe3 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceIdentityInfo.java @@ -0,0 +1,11 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; +import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; + +public record DeviceIdentityInfo(int registrationId, ECSignedPreKey signedPreKey, KEMSignedPreKey pqLastResortPreKey) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceSpec.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceSpec.java index b8e195d13..97257b868 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceSpec.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DeviceSpec.java @@ -8,9 +8,7 @@ import java.util.Set; import org.signal.libsignal.protocol.IdentityKey; import org.whispersystems.textsecuregcm.auth.SaltedTokenHash; import org.whispersystems.textsecuregcm.entities.ApnRegistrationId; -import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; import org.whispersystems.textsecuregcm.entities.GcmRegistrationId; -import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil; import org.whispersystems.textsecuregcm.util.Util; @@ -19,15 +17,11 @@ public record DeviceSpec( String password, String signalAgent, Set capabilities, - int aciRegistrationId, - int pniRegistrationId, + DeviceIdentityInfo aciInfo, + Optional pniInfo, boolean fetchesMessages, Optional apnRegistrationId, - Optional gcmRegistrationId, - ECSignedPreKey aciSignedPreKey, - ECSignedPreKey pniSignedPreKey, - KEMSignedPreKey aciPqLastResortPreKey, - KEMSignedPreKey pniPqLastResortPreKey) { + Optional gcmRegistrationId) { public Device toDevice(final byte deviceId, final Clock clock, final IdentityKey aciIdentityKey) { final long created = clock.millis(); @@ -36,13 +30,13 @@ public record DeviceSpec( device.setId(deviceId); device.setAuthTokenHash(SaltedTokenHash.generateFor(password())); device.setFetchesMessages(fetchesMessages()); - device.setRegistrationId(aciRegistrationId()); - device.setPhoneNumberIdentityRegistrationId(pniRegistrationId()); + device.setRegistrationId(aciInfo.registrationId()); + pniInfo().ifPresent(pniInfo -> device.setPhoneNumberIdentityRegistrationId(pniInfo.registrationId())); device.setName(deviceNameCiphertext()); device.setCapabilities(capabilities()); device.setCreated(created); device.setCreatedAtCiphertext( - EncryptDeviceCreationTimestampUtil.encrypt(created, aciIdentityKey, deviceId, aciRegistrationId())); + EncryptDeviceCreationTimestampUtil.encrypt(created, aciIdentityKey, deviceId, aciInfo.registrationId())); device.setLastSeen(Util.todayInMillis()); device.setUserAgent(signalAgent()); @@ -64,26 +58,21 @@ public record DeviceSpec( final DeviceSpec that = (DeviceSpec) o; - return aciRegistrationId == that.aciRegistrationId - && pniRegistrationId == that.pniRegistrationId + return Objects.equals(aciInfo, that.aciInfo) + && Objects.equals(pniInfo, that.pniInfo) && fetchesMessages == that.fetchesMessages && Arrays.equals(deviceNameCiphertext, that.deviceNameCiphertext) && Objects.equals(password, that.password) && Objects.equals(signalAgent, that.signalAgent) && Objects.equals(capabilities, that.capabilities) && Objects.equals(apnRegistrationId, that.apnRegistrationId) - && Objects.equals(gcmRegistrationId, that.gcmRegistrationId) - && Objects.equals(aciSignedPreKey, that.aciSignedPreKey) - && Objects.equals(pniSignedPreKey, that.pniSignedPreKey) - && Objects.equals(aciPqLastResortPreKey, that.aciPqLastResortPreKey) - && Objects.equals(pniPqLastResortPreKey, that.pniPqLastResortPreKey); + && Objects.equals(gcmRegistrationId, that.gcmRegistrationId); } @Override public int hashCode() { - int result = Objects.hash(password, signalAgent, capabilities, aciRegistrationId, pniRegistrationId, - fetchesMessages, apnRegistrationId, gcmRegistrationId, aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, - pniPqLastResortPreKey); + int result = Objects.hash(password, signalAgent, capabilities, aciInfo, pniInfo, + fetchesMessages, apnRegistrationId, gcmRegistrationId); result = 31 * result + Arrays.hashCode(deviceNameCiphertext); return result; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/KeysManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/KeysManager.java index 99fa307f9..5f89bfd48 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/KeysManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/KeysManager.java @@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -61,32 +62,49 @@ public class KeysManager { return pqLastResortKeys.buildTransactWriteItemForInsertion(identifier, deviceId, lastResortSignedPreKey); } + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public List buildWriteItemsForNewDevice(final UUID accountIdentifier, - final UUID phoneNumberIdentifier, + final Optional maybePhoneNumberIdentifier, final byte deviceId, final ECSignedPreKey aciSignedPreKey, - final ECSignedPreKey pniSignedPreKey, + final Optional maybePniSignedPreKey, final KEMSignedPreKey aciPqLastResortPreKey, - final KEMSignedPreKey pniLastResortPreKey) { + final Optional maybePniPqLastResortPreKey) { + final List writeItems = new ArrayList<>(buildWriteItemsForNewDevice(accountIdentifier, deviceId, aciSignedPreKey, aciPqLastResortPreKey)); + maybePhoneNumberIdentifier.ifPresent(pni -> + writeItems.addAll(buildWriteItemsForNewDevice(pni, deviceId, + maybePniSignedPreKey.orElseThrow(() -> new AssertionError("PNI signed pre key must be provided if PNI is present")), + maybePniPqLastResortPreKey.orElseThrow(() -> new AssertionError("PNI PQ last resort pre key must be provided if PNI is present"))) + )); + return writeItems; + } + + private List buildWriteItemsForNewDevice(final UUID identifier, + final byte deviceId, + final ECSignedPreKey signedPreKey, + final KEMSignedPreKey lastResortPreKey) { return List.of( - ecSignedPreKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, aciSignedPreKey), - ecSignedPreKeys.buildTransactWriteItemForInsertion(phoneNumberIdentifier, deviceId, pniSignedPreKey), - pqLastResortKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, aciPqLastResortPreKey), - pqLastResortKeys.buildTransactWriteItemForInsertion(phoneNumberIdentifier, deviceId, pniLastResortPreKey) + ecSignedPreKeys.buildTransactWriteItemForInsertion(identifier, deviceId, signedPreKey), + pqLastResortKeys.buildTransactWriteItemForInsertion(identifier, deviceId, lastResortPreKey) ); } + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public List buildWriteItemsForRemovedDevice(final UUID accountIdentifier, - final UUID phoneNumberIdentifier, + final Optional maybePhoneNumberIdentifier, final byte deviceId) { - - return List.of( + final List writeItems = new ArrayList<>(List.of( ecSignedPreKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId), + pqLastResortKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId) + )); + + maybePhoneNumberIdentifier.ifPresent(phoneNumberIdentifier -> writeItems.addAll(List.of( ecSignedPreKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId), - pqLastResortKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId), - pqLastResortKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId) + pqLastResortKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId))) ); + + return writeItems; } public CompletableFuture storeEcSignedPreKeys(final UUID identifier, final byte deviceId, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java index 6de7decd0..7e3ac9922 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceControllerTest.java @@ -257,7 +257,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", deviceAttributes, - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId)); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), apnRegistrationId, gcmRegistrationId)); final LinkDeviceResponse response = resources.getJerseyTest() .target("/v1/devices/link") @@ -336,7 +336,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(false, 1234, 5678, null, requestCapabilities), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); final int expectedStatus = capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE @@ -389,7 +389,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(false, 1234, 5678, null, requestCapabilities), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -427,7 +427,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(false, 1234, 5678, null, null), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -473,7 +473,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", deviceAttributes, - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty())); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty())); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -514,7 +514,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(false, 1234, 5678, null, null), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -563,7 +563,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.token(), new DeviceAttributes(fetchesMessages, 1234, 5678, null, null), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnRegistrationId, gcmRegistrationId)); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), apnRegistrationId, gcmRegistrationId)); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -594,24 +594,18 @@ class DeviceControllerTest { final KEMSignedPreKey pniPqLastResortPreKey) { when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account)); - when(accountsManager.generateLinkDeviceToken(any())).thenReturn("test"); + when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID)); final Device existingDevice = mock(Device.class); when(existingDevice.getId()).thenReturn(Device.PRIMARY_ID); when(account.getDevices()).thenReturn(List.of(existingDevice)); - final LinkDeviceToken deviceCode = resources.getJerseyTest() - .target("/v1/devices/provisioning/code") - .request() - .header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) - .get(LinkDeviceToken.class); - when(account.getIdentityKey(IdentityType.ACI)).thenReturn(aciIdentityKey); when(account.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey); - final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.token(), + final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(true, 1234, 5678, null, null), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty())); + new DeviceActivationRequest(aciSignedPreKey, Optional.ofNullable(pniSignedPreKey), aciPqLastResortPreKey, Optional.ofNullable(pniPqLastResortPreKey), Optional.empty(), Optional.empty())); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -671,7 +665,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(true, 1234, 5678, null, null), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty())); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty())); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -704,7 +698,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(true, 1234, 5678, null, null), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.empty())); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty())); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -763,7 +757,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(false, 1234, 5678, TestRandomUtil.nextBytes(512), null), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -808,7 +802,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", new DeviceAttributes(false, registrationId, pniRegistrationId, null, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES), - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.of(new ApnRegistrationId("apn")), Optional.empty())); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.of(new ApnRegistrationId("apn")), Optional.empty())); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -859,7 +853,7 @@ class DeviceControllerTest { final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token", null, - new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); + new DeviceActivationRequest(aciSignedPreKey, Optional.of(pniSignedPreKey), aciPqLastResortPreKey, Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id")))); try (final Response response = resources.getJerseyTest() .target("/v1/devices/link") @@ -1470,9 +1464,9 @@ class DeviceControllerTest { deviceAttributes, new DeviceActivationRequest( KeysHelper.signedECPreKey(1, aciIdentityKeyPair), - KeysHelper.signedECPreKey(2, pniIdentityKeyPair), + Optional.of(KeysHelper.signedECPreKey(2, pniIdentityKeyPair)), KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair), - KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair), + Optional.of(KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair)), Optional.empty(), Optional.empty())); 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 b8b26a902..f9afed52f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java @@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountsManager; 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.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.KeysHelper; @@ -168,7 +169,7 @@ class RegistrationControllerTest { @ParameterizedTest @MethodSource - void invalidRegistrationId(Optional registrationId, Optional pniRegistrationId, int statusCode) throws InterruptedException, JsonProcessingException { + void invalidRegistrationId(Optional registrationId, Optional pniRegistrationId, int statusCode) { final Invocation.Builder request = resources.getJerseyTest() .target("/v1/registration") .request() @@ -180,7 +181,7 @@ class RegistrationControllerTest { when(accountsManager.create(any(), any(), any(), any(), any(), any(), any())) .thenReturn(account); - final String json = requestJson("sessionId", new byte[0], true, registrationId.orElse(0), pniRegistrationId.orElse(0)); + final String json = requestJson("sessionId", new byte[0], true, registrationId.orElse(0), pniRegistrationId.orElse(null)); try (Response response = request.post(Entity.json(json))) { assertEquals(statusCode, response.getStatus()); @@ -450,9 +451,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.of(new ApnRegistrationId("apns-token")), Optional.empty()))), @@ -464,9 +465,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId("gcm-token"))))), @@ -478,9 +479,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.of(new ApnRegistrationId("apns-token")), Optional.of(new GcmRegistrationId("gcm-token"))))) ); @@ -533,7 +534,7 @@ class RegistrationControllerTest { new DeviceActivationRequest(aciSignedPreKey, null, aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty()))), @@ -545,9 +546,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(null, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty()))), @@ -559,7 +560,7 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, null, Optional.empty(), @@ -573,9 +574,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), null, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty()))), @@ -587,9 +588,9 @@ class RegistrationControllerTest { null, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty()))), @@ -601,9 +602,9 @@ class RegistrationControllerTest { aciIdentityKey, null, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty()))) ); @@ -752,9 +753,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.empty())), aciIdentityKey, @@ -764,15 +765,12 @@ class RegistrationControllerTest { PASSWORD, null, deviceCapabilities, - registrationId, - pniRegistrationId, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), true, Optional.empty(), - Optional.empty(), - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey)), + Optional.empty() + )), Arguments.argumentSet("Has APNs tokens", new RegistrationRequest("session-id", @@ -782,9 +780,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.of(new ApnRegistrationId(apnsToken)), Optional.empty())), aciIdentityKey, @@ -794,15 +792,11 @@ class RegistrationControllerTest { PASSWORD, null, deviceCapabilities, - registrationId, - pniRegistrationId, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), false, Optional.of(new ApnRegistrationId(apnsToken)), - Optional.empty(), - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey)), + Optional.empty())), Arguments.argumentSet("Has GCM token", new RegistrationRequest("session-id", @@ -812,9 +806,9 @@ class RegistrationControllerTest { aciIdentityKey, pniIdentityKey, new DeviceActivationRequest(aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey, + Optional.of(pniPqLastResortPreKey), Optional.empty(), Optional.of(new GcmRegistrationId(gcmToken)))), aciIdentityKey, @@ -824,15 +818,11 @@ class RegistrationControllerTest { PASSWORD, null, deviceCapabilities, - registrationId, - pniRegistrationId, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), false, Optional.empty(), - Optional.of(new GcmRegistrationId(gcmToken)), - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey)) + Optional.of(new GcmRegistrationId(gcmToken)))) ); } @@ -841,7 +831,7 @@ class RegistrationControllerTest { final byte[] recoveryPassword, final boolean skipDeviceTransfer, final int registrationId, - int pniRegistrationId, + final Integer pniRegistrationId, Set deviceCapabilities) { final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate(); final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate(); @@ -863,9 +853,9 @@ class RegistrationControllerTest { pniIdentityKey, new DeviceActivationRequest( KeysHelper.signedECPreKey(1, aciIdentityKeyPair), - KeysHelper.signedECPreKey(2, pniIdentityKeyPair), + Optional.of(KeysHelper.signedECPreKey(2, pniIdentityKeyPair)), KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair), - KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair), + Optional.of(KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair)), Optional.empty(), Optional.empty())); } @@ -885,7 +875,7 @@ class RegistrationControllerTest { final byte[] recoveryPassword, final boolean skipDeviceTransfer, final int registrationId, - final int pniRegistrationId) { + final Integer pniRegistrationId) { return requestToJson(request(sessionId, recoveryPassword, skipDeviceTransfer, registrationId, pniRegistrationId, DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)); } 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 a7575b6cf..809c687bc 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java @@ -33,8 +33,11 @@ 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; +import org.junit.jupiter.params.provider.MethodSource; import org.junitpioneer.jupiter.cartesian.ArgumentSets; import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.signal.libsignal.protocol.IdentityKey; @@ -232,52 +235,129 @@ public class AccountCreationDeletionIntegrationTest { password, signalAgent, deviceCapabilities, - registrationId, - pniRegistrationId, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), deliveryChannels.fetchesMessages(), maybeApnRegistrationId, - maybeGcmRegistrationId, - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey), + maybeGcmRegistrationId), null); assertExpectedStoredAccount(account, - number, + Optional.of(number), password, signalAgent, deliveryChannels, registrationId, - pniRegistrationId, + Optional.of(pniRegistrationId), deviceName, discoverableByPhoneNumber, deviceCapabilities, badges, maybeApnRegistrationId, maybeGcmRegistrationId, - registrationLockSecret, + Optional.of(registrationLockSecret), aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey); + Optional.of(pniPqLastResortPreKey)); assertEquals(Optional.of(aciSignedPreKey), keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); - assertEquals(Optional.of(pniSignedPreKey), keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join()); + assertEquals(Optional.of(pniSignedPreKey), keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join()); assertEquals(Optional.of(aciPqLastResortPreKey), keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); - assertEquals(Optional.of(pniPqLastResortPreKey), keysManager.getLastResort(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join()); + assertEquals(Optional.of(pniPqLastResortPreKey), keysManager.getLastResort(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join()); + } + + @ParameterizedTest + @MethodSource("deliveryChannels") + @Disabled("creating numberless accounts is not supported yet") + void createAccountWithoutNumber(final DeliveryChannels deliveryChannels) { + final String password = RandomStringUtils.secure().nextAlphanumeric(16); + 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); + + final List badges = new ArrayList<>(List.of(new AccountBadge( + RandomStringUtils.secure().nextAlphabetic(8), + CLOCK.instant().plus(Duration.ofDays(7)), + true))); + + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, 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 account = accountsManager.create(accountAttributes, + badges, + new IdentityKey(aciKeyPair.getPublicKey()), + new DeviceSpec( + deviceName, + password, + signalAgent, + deviceCapabilities, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.empty(), + deliveryChannels.fetchesMessages(), + maybeApnRegistrationId, + maybeGcmRegistrationId), + null); + + assertExpectedStoredAccount(account, + Optional.empty(), + password, + signalAgent, + deliveryChannels, + registrationId, + Optional.empty(), + deviceName, + false, + deviceCapabilities, + badges, + maybeApnRegistrationId, + maybeGcmRegistrationId, + Optional.empty(), + aciSignedPreKey, + Optional.empty(), + aciPqLastResortPreKey, + Optional.empty()); + + assertEquals(Optional.of(aciSignedPreKey), keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); + assertEquals(Optional.of(aciPqLastResortPreKey), keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); + + assertTrue(account.getNumberOptional().isEmpty()); + assertTrue(account.getPhoneNumberIdentifierOptional().isEmpty()); + assertTrue(account.getPhoneNumberIdentityKey().isEmpty()); + } + + private static List deliveryChannels() { + return List.of( + new DeliveryChannels(true, null, null), + new DeliveryChannels(false, "apns-token", null), + new DeliveryChannels(false, "apns-token", null), + new DeliveryChannels(false, null, "fcm-token")); } @SuppressWarnings("unused") static ArgumentSets createAccount() { - return ArgumentSets - // deliveryChannels - .argumentsForFirstParameter( - new DeliveryChannels(true, null, null), - new DeliveryChannels(false, "apns-token", null), - new DeliveryChannels(false, "apns-token", null), - new DeliveryChannels(false, null, "fcm-token")) - + return ArgumentSets.argumentsForFirstParameter(deliveryChannels()) // discoverableByPhoneNumber .argumentsForNextParameter(true, false); } @@ -310,15 +390,11 @@ public class AccountCreationDeletionIntegrationTest { "password?", "OWI", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(2, pniSignedPreKey, pniPqLastResortPreKey)), true, Optional.empty(), - Optional.empty(), - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey), + Optional.empty()), null); existingAccountUuid = existingAccount.getAccountIdentifier(); @@ -372,44 +448,40 @@ public class AccountCreationDeletionIntegrationTest { password, signalAgent, deviceCapabilities, - registrationId, - pniRegistrationId, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), accountAttributes.getFetchesMessages(), maybeApnRegistrationId, - maybeGcmRegistrationId, - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey), + maybeGcmRegistrationId), null); assertExpectedStoredAccount(reregisteredAccount, - number, + Optional.of(number), password, signalAgent, deliveryChannels, registrationId, - pniRegistrationId, + Optional.of(pniRegistrationId), deviceName, discoverableByPhoneNumber, deviceCapabilities, badges, maybeApnRegistrationId, maybeGcmRegistrationId, - registrationLockSecret, + Optional.of(registrationLockSecret), aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey); + Optional.of(pniPqLastResortPreKey)); assertEquals(existingAccountUuid, reregisteredAccount.getAccountIdentifier()); verify(disconnectionRequestManager).requestDisconnection(argThat(account -> - account.getIdentifier(IdentityType.ACI).equals(existingAccountUuid) && account != reregisteredAccount)); + account.getAccountIdentifier().equals(existingAccountUuid) && account != reregisteredAccount)); } @Test - void deleteAccount() throws InterruptedException { + void deleteAccountWithNumber() throws InterruptedException { final String number = PhoneNumberUtil.getInstance().format( PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164); @@ -456,15 +528,11 @@ public class AccountCreationDeletionIntegrationTest { password, signalAgent, deviceCapabilities, - registrationId, - pniRegistrationId, + new DeviceIdentityInfo(registrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), true, Optional.empty(), - Optional.empty(), - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey), + Optional.empty()), null); final UUID aci = account.getIdentifier(IdentityType.ACI); @@ -477,9 +545,9 @@ public class AccountCreationDeletionIntegrationTest { assertFalse(accountsManager.getByAccountIdentifier(aci).isPresent()); assertFalse(keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); - assertFalse(keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent()); + assertFalse(keysManager.getEcSignedPreKey(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); assertFalse(keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join().isPresent()); - assertFalse(keysManager.getLastResort(account.getPhoneNumberIdentifier(), Device.PRIMARY_ID).join().isPresent()); + assertFalse(keysManager.getLastResort(account.getPhoneNumberIdentifierOptional().orElseThrow(), Device.PRIMARY_ID).join().isPresent()); assertFalse(phoneNumberRecoveryPasswordsManager.verify(account.getPhoneNumberIdentifierOptional().orElseThrow(), accountAttributes.recoveryPassword().orElseThrow())); @@ -489,31 +557,31 @@ public class AccountCreationDeletionIntegrationTest { @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private void assertExpectedStoredAccount(final Account account, - final String number, + final Optional number, final String password, final String signalAgent, final DeliveryChannels deliveryChannels, final int registrationId, - final int pniRegistrationId, + final Optional pniRegistrationId, final byte[] deviceName, final boolean discoverableByPhoneNumber, final Set deviceCapabilities, final List badges, final Optional maybeApnRegistrationId, final Optional maybeGcmRegistrationId, - final String registrationLockSecret, + final Optional registrationLockSecret, final ECSignedPreKey aciSignedPreKey, - final ECSignedPreKey pniSignedPreKey, + final Optional pniSignedPreKey, final KEMSignedPreKey aciPqLastResortPreKey, - final KEMSignedPreKey pniPqLastResortPreKey) { + final Optional pniPqLastResortPreKey) { final Device primaryDevice = account.getPrimaryDevice(); - assertEquals(number, account.getNumber()); + assertEquals(number, account.getNumberOptional()); assertEquals(signalAgent, primaryDevice.getUserAgent()); assertEquals(deliveryChannels.fetchesMessages(), primaryDevice.getFetchesMessages()); - assertEquals(registrationId, primaryDevice.getRegistrationId(IdentityType.ACI)); - assertEquals(pniRegistrationId, primaryDevice.getRegistrationId(IdentityType.PNI)); + assertEquals(registrationId, primaryDevice.getAccountRegistrationId()); + assertEquals(pniRegistrationId, primaryDevice.getPhoneNumberIdentityRegistrationId()); assertArrayEquals(deviceName, primaryDevice.getName()); assertEquals(discoverableByPhoneNumber, account.isDiscoverableByPhoneNumber()); assertEquals(deviceCapabilities, primaryDevice.getCapabilities()); @@ -527,12 +595,15 @@ public class AccountCreationDeletionIntegrationTest { _ -> assertEquals(deliveryChannels.fcmToken(), primaryDevice.getGcmId()), () -> assertNull(primaryDevice.getGcmId())); - assertTrue(account.getRegistrationLock().verify(registrationLockSecret)); + registrationLockSecret.ifPresent(regLockSecret -> assertTrue(account.getRegistrationLock().verify(regLockSecret))); assertTrue(primaryDevice.getAuthTokenHash().verify(password)); assertNotNull(primaryDevice.getCreatedAtCiphertext()); - assertEquals(Optional.of(aciSignedPreKey), keysManager.getEcSignedPreKey(account.getIdentifier(IdentityType.ACI), Device.PRIMARY_ID).join()); - assertEquals(Optional.of(pniSignedPreKey), keysManager.getEcSignedPreKey(account.getIdentifier(IdentityType.PNI), Device.PRIMARY_ID).join()); - assertEquals(Optional.of(aciPqLastResortPreKey), keysManager.getLastResort(account.getIdentifier(IdentityType.ACI), Device.PRIMARY_ID).join()); - assertEquals(Optional.of(pniPqLastResortPreKey), keysManager.getLastResort(account.getIdentifier(IdentityType.PNI), Device.PRIMARY_ID).join()); + assertEquals(Optional.of(aciSignedPreKey), keysManager.getEcSignedPreKey(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); + assertEquals(Optional.of(aciPqLastResortPreKey), keysManager.getLastResort(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); + account.getPhoneNumberIdentifierOptional().ifPresent( + pni -> { + assertEquals(pniSignedPreKey, keysManager.getEcSignedPreKey(pni, Device.PRIMARY_ID).join()); + assertEquals(pniPqLastResortPreKey, keysManager.getLastResort(pni, Device.PRIMARY_ID).join()); + }); } } 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 2575e313d..47b9bee7f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java @@ -151,16 +151,12 @@ class AccountsManagerConcurrentModificationIntegrationTest { "password", null, Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), - null).getIdentifier(IdentityType.ACI), + Optional.empty()), + null).getAccountIdentifier(), a -> { a.setUnidentifiedAccessKey(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); a.removeDevice(Device.PRIMARY_ID); 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 1bb65604d..0a1e593b8 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java @@ -680,7 +680,7 @@ class AccountsManagerTest { assertFalse(account.getDevice(linkedDevice.getId()).isPresent()); verify(messagesManager, times(2)).clear(account.getAccountIdentifier(), linkedDevice.getId()); verify(keysManager, times(2)).deleteSingleUsePreKeys(account.getAccountIdentifier(), linkedDevice.getId()); - verify(keysManager).buildWriteItemsForRemovedDevice(account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), linkedDevice.getId()); + verify(keysManager).buildWriteItemsForRemovedDevice(account.getAccountIdentifier(), account.getPhoneNumberIdentifierOptional(), linkedDevice.getId()); verify(disconnectionRequestManager).requestDisconnection(account.getAccountIdentifier(), List.of(linkedDevice.getId())); } @@ -703,24 +703,44 @@ class AccountsManagerTest { verify(disconnectionRequestManager, never()).requestDisconnection(any(), any()); } - @Test - void testCreateFreshAccount() throws InterruptedException, AccountAlreadyExistsException { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testCreateFreshAccount(final boolean hasE164) throws AccountAlreadyExistsException { when(accounts.create(any(), any())).thenReturn(true); - final String e164 = "+18005550123"; - final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null); + 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 Account createdAccount = createAccount(e164, attributes); + final Account createdAccount = maybeE164 + .map(e164 -> createAccount(e164, attributes)) + .orElseGet(() -> createAccount(attributes)); - verify(accounts).create(argThat(account -> e164.equals(account.getNumber())), any()); + // Check existence (or lack thereof) of phone number, phone number identifier, phone number identity key, + // and phone number identity registration ID + final Device primaryDevice = createdAccount.getDevices().stream().findFirst().orElseThrow(); + assertEquals(maybeE164, createdAccount.getNumberOptional()); + maybeE164.ifPresentOrElse( + number -> { + assertTrue(phoneNumberIdentifiersByE164.containsKey(number)); + assertTrue(createdAccount.getPhoneNumberIdentityKey().isPresent()); + assertEquals(pniRegistrationId, primaryDevice.getPhoneNumberIdentityRegistrationId().orElseThrow()); + }, + () -> { + assertTrue(phoneNumberIdentifiersByE164.isEmpty()); + assertTrue(createdAccount.getPhoneNumberIdentityKey().isEmpty()); + assertTrue(primaryDevice.getPhoneNumberIdentityRegistrationId().isEmpty()); + }); + + verify(accounts).create(argThat(account -> maybeE164.equals(account.getNumberOptional())), any()); verify(keysManager).buildWriteItemsForNewDevice( eq(createdAccount.getAccountIdentifier()), - eq(createdAccount.getPhoneNumberIdentifier()), + eq(createdAccount.getPhoneNumberIdentifierOptional()), eq(Device.PRIMARY_ID), notNull(), + maybeE164.isPresent() ? notNull() : eq(Optional.empty()), notNull(), - notNull(), - notNull()); + maybeE164.isPresent() ? notNull() : eq(Optional.empty())); verify(changeNumberWaitingPeriodManager).handleAccountCreated(eq(createdAccount.getAccountIdentifier()), any(Instant.class)); @@ -729,17 +749,14 @@ class AccountsManagerTest { } @ParameterizedTest - @CsvSource({ - "+18005550123, +18005550123", - // the canonical form of numbers may change over time, so an existing account might have not-identical e164 that - // maps to the same PNI, and the number used by the caller must be present on the re-registered account - "+2290123456789, +22923456789" - }) - void testReregisterAccount(final String e164, final String existingAccountE164) - throws InterruptedException, AccountAlreadyExistsException { + @MethodSource + void testReregisterAccount( + final Optional maybeE164, + final Optional maybeExistingAccountE164) + throws AccountAlreadyExistsException { final UUID existingUuid = UUID.randomUUID(); - - final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null); + final Integer pniRegistrationId = maybeE164.isPresent() ? 2 : null; + final AccountAttributes attributes = new AccountAttributes(false, 1, pniRegistrationId, null, null, maybeE164.isPresent(), null); when(accounts.create(any(), any())) .thenAnswer(invocation -> { @@ -747,10 +764,8 @@ class AccountsManagerTest { final Account existingAccount = mock(Account.class); when(existingAccount.getAccountIdentifier()).thenReturn(existingUuid); - when(existingAccount.getIdentifier(IdentityType.ACI)).thenReturn(existingUuid); - when(existingAccount.getNumber()).thenReturn(existingAccountE164); - when(existingAccount.getPhoneNumberIdentifier()).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI)); - when(existingAccount.getIdentifier(IdentityType.PNI)).thenReturn(requestedAccount.getIdentifier(IdentityType.PNI)); + when(existingAccount.getNumberOptional()).thenReturn(maybeExistingAccountE164); + when(existingAccount.getPhoneNumberIdentifierOptional()).thenReturn(requestedAccount.getPhoneNumberIdentifierOptional()); when(existingAccount.getPrimaryDevice()).thenReturn(mock(Device.class)); throw new AccountAlreadyExistsException(existingAccount); @@ -758,32 +773,57 @@ class AccountsManagerTest { when(accounts.reclaimAccount(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null)); - final Account reregisteredAccount = createAccount(e164, attributes); + final Account reregisteredAccount = maybeE164 + .map(number -> createAccount(number, attributes)) + .orElseGet(() -> createAccount(attributes)); - assertTrue(phoneNumberIdentifiersByE164.containsKey(e164)); - assertEquals(e164, reregisteredAccount.getNumber()); + // Check existence (or lack thereof) of phone number, phone number identifier, phone number identity key, + // and phone number identity registration ID + final Device primaryDevice = reregisteredAccount.getDevices().stream().findFirst().orElseThrow(); + + assertEquals(maybeE164, reregisteredAccount.getNumberOptional()); + maybeE164.ifPresentOrElse( + number -> { + assertTrue(phoneNumberIdentifiersByE164.containsKey(number)); + assertTrue(reregisteredAccount.getPhoneNumberIdentityKey().isPresent()); + assertEquals(pniRegistrationId, primaryDevice.getPhoneNumberIdentityRegistrationId().orElseThrow()); + }, + () -> { + assertTrue(phoneNumberIdentifiersByE164.isEmpty()); + assertTrue(reregisteredAccount.getPhoneNumberIdentityKey().isEmpty()); + assertTrue(primaryDevice.getPhoneNumberIdentityRegistrationId().isEmpty()); + }); verify(accounts) - .create(argThat(account -> e164.equals(account.getNumber()) && existingUuid.equals(account.getAccountIdentifier())), any()); + .create(argThat(account -> existingUuid.equals(account.getAccountIdentifier())), any()); verify(keysManager).buildWriteItemsForNewDevice( eq(reregisteredAccount.getAccountIdentifier()), - eq(reregisteredAccount.getPhoneNumberIdentifier()), + eq(reregisteredAccount.getPhoneNumberIdentifierOptional()), eq(Device.PRIMARY_ID), notNull(), + maybeE164.isPresent() ? notNull() : eq(Optional.empty()), notNull(), - notNull(), - notNull()); + maybeE164.isPresent() ? notNull() : eq(Optional.empty())); verify(keysManager, times(2)).deleteSingleUsePreKeys(existingUuid); - verify(keysManager, times(2)).deleteSingleUsePreKeys(phoneNumberIdentifiersByE164.get(e164)); + maybeE164.ifPresent(number -> verify(keysManager, times(2)).deleteSingleUsePreKeys(phoneNumberIdentifiersByE164.get(number))); verify(messagesManager, times(2)).clear(existingUuid); verify(profilesManager, times(2)).deleteAll(existingUuid, false); verify(disconnectionRequestManager).requestDisconnection(argThat(account -> - account.getIdentifier(IdentityType.ACI).equals(existingUuid) && account != reregisteredAccount)); + account.getAccountIdentifier().equals(existingUuid) && account != reregisteredAccount)); verify(changeNumberWaitingPeriodManager).handleAccountCreated(eq(existingUuid), any(Instant.class)); } + private static List testReregisterAccount() { + return List.of( + Arguments.argumentSet("Re-register with the same phone number", Optional.of("+18005550123"), Optional.of("+18005550123")), + // the canonical form of numbers may change over time, so an existing account might have not-identical e164 that + // maps to the same PNI, and the number used by the caller must be present on the re-registered account + Arguments.argumentSet("Re-register with a phone number in the same equivalence class", Optional.of("+2290123456789"), Optional.of("+22923456789")), + Arguments.argumentSet("Re-register a numberless account", Optional.empty(), Optional.empty())); + } + @Test void testCreateAccountRecentlyDeleted() throws InterruptedException, AccountAlreadyExistsException { final UUID recentlyDeletedUuid = UUID.randomUUID(); @@ -797,11 +837,11 @@ class AccountsManagerTest { final Account account = createAccount(e164, attributes); verify(accounts).create( - argThat(a -> e164.equals(a.getNumber()) && recentlyDeletedUuid.equals(a.getAccountIdentifier())), + argThat(a -> e164.equals(a.getNumberOptional().get()) && recentlyDeletedUuid.equals(a.getAccountIdentifier())), any()); - verify(keysManager).buildWriteItemsForNewDevice(eq(account.getIdentifier(IdentityType.ACI)), - eq(account.getIdentifier(IdentityType.PNI)), + verify(keysManager).buildWriteItemsForNewDevice(eq(account.getAccountIdentifier()), + eq(account.getPhoneNumberIdentifierOptional()), eq(Device.PRIMARY_ID), any(), any(), @@ -871,15 +911,11 @@ class AccountsManagerTest { password, signalAgent, deviceCapabilities, - aciRegistrationId, - pniRegistrationId, + new DeviceIdentityInfo(aciRegistrationId, aciSignedPreKey, aciPqLastResortPreKey), + Optional.of(new DeviceIdentityInfo(pniRegistrationId, pniSignedPreKey, pniPqLastResortPreKey)), true, Optional.empty(), - Optional.empty(), - aciSignedPreKey, - pniSignedPreKey, - aciPqLastResortPreKey, - pniPqLastResortPreKey), + Optional.empty()), accountsManager.generateLinkDeviceToken(aci)); verify(keysManager).deleteSingleUsePreKeys(aci, nextDeviceId); @@ -888,12 +924,12 @@ class AccountsManagerTest { verify(keysManager).buildWriteItemsForNewDevice( aci, - pni, + Optional.of(pni), nextDeviceId, aciSignedPreKey, - pniSignedPreKey, + Optional.of(pniSignedPreKey), aciPqLastResortPreKey, - pniPqLastResortPreKey); + Optional.of(pniPqLastResortPreKey)); final Device device = updatedAccountAndDevice.second(); @@ -1029,7 +1065,7 @@ class AccountsManagerTest { verify(keysManager).deleteSingleUsePreKeys(originalPni); verify(keysManager, atLeastOnce()).deleteSingleUsePreKeys(targetPni); verify(keysManager).deleteSingleUsePreKeys(newPni); - verify(keysManager).buildWriteItemsForRemovedDevice(existingAccountUuid, targetPni, Device.PRIMARY_ID); + verify(keysManager).buildWriteItemsForRemovedDevice(existingAccountUuid, Optional.of(targetPni), Device.PRIMARY_ID); verify(keysManager).buildWriteItemForEcSignedPreKey(newPni, Device.PRIMARY_ID, ecSignedPreKey); verify(keysManager).buildWriteItemForLastResortKey(newPni, Device.PRIMARY_ID, kemLastResoryPreKey); verifyNoMoreInteractions(keysManager); @@ -1329,7 +1365,26 @@ class AccountsManagerTest { return device; } - private Account createAccount(final String e164, final AccountAttributes accountAttributes) throws InterruptedException { + private Account createAccount(final AccountAttributes accountAttributes) { + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + + return accountsManager.create(accountAttributes, + new ArrayList<>(), + new IdentityKey(aciKeyPair.getPublicKey()), + new DeviceSpec( + accountAttributes.getName(), + "password", + null, + accountAttributes.getCapabilities(), + new DeviceIdentityInfo(accountAttributes.getRegistrationId(), KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.empty(), + accountAttributes.getFetchesMessages(), + Optional.empty(), + Optional.empty()), + null); + } + + private Account createAccount(final String e164, final AccountAttributes accountAttributes) { final ECKeyPair aciKeyPair = ECKeyPair.generate(); final ECKeyPair pniKeyPair = ECKeyPair.generate(); @@ -1343,15 +1398,13 @@ class AccountsManagerTest { "password", null, accountAttributes.getCapabilities(), - accountAttributes.getRegistrationId(), - accountAttributes.getPhoneNumberIdentityRegistrationId(), + new DeviceIdentityInfo(accountAttributes.getRegistrationId(), KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(accountAttributes.getPhoneNumberIdentityRegistrationId().orElseThrow(() -> new AssertionError("PNI registration ID must be provided for an account with a phone number")), + KeysHelper.signedECPreKey(2, pniKeyPair), + KeysHelper.signedKEMPreKey(4, pniKeyPair))), accountAttributes.getFetchesMessages(), Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), null); } 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 d435cd1c1..594c4ad3c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java @@ -51,6 +51,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; 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; @@ -202,6 +203,13 @@ class AccountsTest { 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)); + } + @Test void testStoreRecentlyDeleted() { final UUID originalUuid = UUID.randomUUID(); @@ -459,7 +467,8 @@ class AccountsTest { accounts.confirmUsernameHash(existingAccount, usernameHash, encryptedUsername); final UUID usernameLinkHandle = existingAccount.getUsernameLinkHandle(); - verifyStoredState(e164, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifier(), usernameHash, existingAccount, true); + assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); + verifyStoredState(e164, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), usernameHash, existingAccount, true); assertPhoneNumberConstraintExists(e164, existingUuid); assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); @@ -507,6 +516,64 @@ class AccountsTest { 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(); + } + @ParameterizedTest @MethodSource void testReclaimAccountEquivalentPhoneNumbers(final String firstNumber, final String secondNumber) throws IOException { @@ -516,7 +583,8 @@ class AccountsTest { createAccount(existingAccount); - verifyStoredState(firstNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifier(), null, existingAccount, true); + assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); + verifyStoredState(firstNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), null, existingAccount, true); assertPhoneNumberConstraintExists(firstNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(pni, existingUuid); @@ -532,9 +600,10 @@ class AccountsTest { Map item = readAccount(existingUuid); final Account account = SystemMapper.jsonMapper().readValue(item.get(Accounts.ATTR_ACCOUNT_DATA).b().asByteArray(), Account.class); + assertTrue(account.getNumberOptional().isPresent()); assertThat(AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null)) .isEqualTo(secondNumber) - .isEqualTo(account.getNumber()); + .isEqualTo(account.getNumberOptional().get()); assertPhoneNumberConstraintDoesNotExist(firstNumber); assertPhoneNumberConstraintExists(secondNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(pni, existingUuid); @@ -560,7 +629,8 @@ class AccountsTest { createAccount(existingAccount); - verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifier(), null, existingAccount, true); + assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); + verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), null, existingAccount, true); assertPhoneNumberConstraintExists(beninPhoneNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(pni, existingUuid); @@ -595,7 +665,8 @@ class AccountsTest { createAccount(existingAccount); - verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifier(), null, existingAccount, true); + assertTrue(existingAccount.getPhoneNumberIdentifierOptional().isPresent()); + verifyStoredState(beninPhoneNumber, existingAccount.getAccountIdentifier(), existingAccount.getPhoneNumberIdentifierOptional().get(), null, existingAccount, true); assertPhoneNumberConstraintExists(beninPhoneNumber, existingUuid); assertPhoneNumberIdentifierConstraintExists(existingPni, existingUuid); @@ -2014,6 +2085,10 @@ class AccountsTest { return generateAccount(nextNumber, UUID.randomUUID(), UUID.randomUUID()); } + private static Account generateNumberlessAccount(final UUID uuid) { + return generateAccount(null, uuid, null); + } + private static Account generateAccount(String number, UUID uuid, final UUID pni) { Device device = generateDevice(DEVICE_ID_1); return generateAccount(number, uuid, pni, List.of(device)); @@ -2122,8 +2197,8 @@ class AccountsTest { } private void verifyStoredState(String number, UUID uuid, UUID pni, byte[] usernameHash, Account result, Account expecting) { - assertThat(result.getNumber()).isEqualTo(number); - assertThat(result.getPhoneNumberIdentifier()).isEqualTo(pni); + assertThat(result.getNumberOptional()).isEqualTo(Optional.ofNullable(number)); + assertThat(result.getPhoneNumberIdentifierOptional()).isEqualTo(Optional.ofNullable(pni)); assertThat(result.getLastSeen()).isEqualTo(expecting.getLastSeen()); assertThat(result.getAccountIdentifier()).isEqualTo(uuid); assertThat(result.getVersion()).isEqualTo(expecting.getVersion()); @@ -2139,6 +2214,7 @@ class AccountsTest { assertThat(resultDevice.getUserAgent()).isEqualTo(expectingDevice.getUserAgent()); assertThat(resultDevice.getName()).isEqualTo(expectingDevice.getName()); assertThat(resultDevice.getCreated()).isEqualTo(expectingDevice.getCreated()); + assertThat(resultDevice.getPhoneNumberIdentityRegistrationId()).isEqualTo(expectingDevice.getPhoneNumberIdentityRegistrationId()); } } } 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 8acae2bf0..f5e326527 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java @@ -187,15 +187,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI))); assertEquals(2, updatedAccountAndDevice.first().getDevices().size()); @@ -237,15 +233,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), linkDeviceToken); assertEquals(2, @@ -258,15 +250,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), linkDeviceToken)); assertEquals(2, @@ -292,15 +280,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI))); final byte addedDeviceId = updatedAccountAndDevice.second().getId(); @@ -343,15 +327,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), accountsManager.generateLinkDeviceToken(account.getIdentifier(IdentityType.ACI))); final byte addedDeviceId = updatedAccountAndDevice.second().getId(); @@ -413,15 +393,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), linkDeviceToken); final Optional maybeDeviceInfo = activeFuture.join(); @@ -454,15 +430,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), linkDeviceToken); when(messagesManager.getEarliestUndeliveredTimestampForDevice(account.getAccountIdentifier(), account.getPrimaryDevice())) @@ -523,15 +495,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), linkDeviceToken); when(messagesManager.getEarliestUndeliveredTimestampForDevice(account.getAccountIdentifier(), account.getPrimaryDevice())) @@ -566,15 +534,11 @@ public class AddRemoveDeviceIntegrationTest { "password", "OWT", Set.of(), - 1, - 2, + new DeviceIdentityInfo(1, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(2, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), true, Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), linkDeviceToken); when(messagesManager.getEarliestUndeliveredTimestampForDevice(account.getAccountIdentifier(), account.getPrimaryDevice())) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/KeysManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/KeysManagerTest.java index 12958f5a7..af416b1da 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/KeysManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/KeysManagerTest.java @@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.storage; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; @@ -16,7 +17,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; import org.signal.libsignal.protocol.ecc.ECKeyPair; import org.whispersystems.textsecuregcm.entities.ECPreKey; import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; @@ -61,6 +64,38 @@ class KeysManagerTest { new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName())); } + @ParameterizedTest + @MethodSource + void buildWriteItemsForNewDevicePniPresentMissingPniPreKey( + final Optional pniSignedPreKey, + final Optional pniPqLastResortPreKey) { + final ECKeyPair aciKeyPair = ECKeyPair.generate(); + final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciKeyPair); + final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciKeyPair); + + assertThrows(AssertionError.class, () -> keysManager.buildWriteItemsForNewDevice( + UUID.randomUUID(), + Optional.of(UUID.randomUUID()), + Device.PRIMARY_ID, + aciSignedPreKey, + pniSignedPreKey, + aciPqLastResortPreKey, + pniPqLastResortPreKey)); + } + + private static List buildWriteItemsForNewDevicePniPresentMissingPniPreKey() { + final ECKeyPair pniKeyPair = ECKeyPair.generate(); + + final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(2, pniKeyPair); + final KEMSignedPreKey pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair); + + return List.of( + Arguments.argumentSet("Missing PNI signed pre key", Optional.empty(), Optional.of(pniPqLastResortPreKey)), + Arguments.argumentSet("Missing PNI PQ last resort pre key", Optional.of(pniSignedPreKey), Optional.empty()), + Arguments.argumentSet("Missing both PNI pre keys", Optional.empty(), Optional.empty()) + ); + } + @Test void storeEcOneTimePreKeys() { assertEquals(0, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID).join(), 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 0dbe96872..b1d7beeff 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 @@ -35,6 +35,7 @@ import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.Device; +import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo; import org.whispersystems.textsecuregcm.storage.DeviceSpec; import org.whispersystems.textsecuregcm.util.SystemMapper; @@ -297,15 +298,12 @@ public class AccountsHelper { "password", "OWT", accountAttributes.getCapabilities(), - accountAttributes.getRegistrationId(), - accountAttributes.getPhoneNumberIdentityRegistrationId(), + new DeviceIdentityInfo(accountAttributes.getRegistrationId(), KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)), + Optional.of(new DeviceIdentityInfo(accountAttributes.getPhoneNumberIdentityRegistrationId().orElseThrow(() -> new AssertionError("Must provide PNI registration ID for account with number")), + KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))), accountAttributes.getFetchesMessages(), Optional.empty(), - Optional.empty(), - KeysHelper.signedECPreKey(1, aciKeyPair), - KeysHelper.signedECPreKey(2, pniKeyPair), - KeysHelper.signedKEMPreKey(3, aciKeyPair), - KeysHelper.signedKEMPreKey(4, pniKeyPair)), + Optional.empty()), null); } }