mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:56:47 +00:00
make some TOTP-specific RPCs generic to any MFA factor
This commit is contained in:
1 parent
9ee081ef28
commit
5469341fd6
12 files changed
+264
-159
No files matched your search
+65
-48
@@ -51,11 +51,11 @@ import org.signal.chat.account.GetCapabilitiesRequest;
|
||||
import org.signal.chat.account.GetCapabilitiesResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ListTotpKeysRequest;
|
||||
import org.signal.chat.account.ListTotpKeysResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.RemoveTotpKeyRequest;
|
||||
import org.signal.chat.account.RemoveTotpKeyResponse;
|
||||
import org.signal.chat.account.RemoveMfaKeyRequest;
|
||||
import org.signal.chat.account.RemoveMfaKeyResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -64,8 +64,8 @@ import org.signal.chat.account.SetRegistrationLockRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockResponse;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
@@ -104,10 +104,12 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
@@ -131,7 +133,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final Clock clock;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
|
||||
private static class TotpKeyNotFoundException extends NoStackTraceRuntimeException {
|
||||
private static class MfaKeyNotFoundException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
@@ -568,91 +570,106 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
.setTotpParameters(toGrpcTotpParameters(pendingTotpKey.totpParameters()))
|
||||
.build())
|
||||
.build();
|
||||
} catch (final TooManyTotpKeysException e) {
|
||||
} catch (final TooManyTotpKeysException _) {
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setTooManyTotpKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final TooManyMfaKeysException _) {
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
|
||||
final Optional<Byte> maybeConfirmedTotpKeyId =
|
||||
accountsManager.confirmPendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getOneTimePassword(),
|
||||
clock.instant(),
|
||||
request.getMetadataCiphertext().toByteArray());
|
||||
try {
|
||||
final Optional<Byte> maybeConfirmedTotpKeyId =
|
||||
accountsManager.confirmPendingTotpKey(
|
||||
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getOneTimePassword(),
|
||||
clock.instant(),
|
||||
request.getMetadataCiphertext().toByteArray());
|
||||
|
||||
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
|
||||
.setKeyId(keyId)
|
||||
.build())
|
||||
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
|
||||
.build());
|
||||
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
|
||||
.setKeyId(keyId)
|
||||
.build())
|
||||
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
|
||||
.build());
|
||||
} catch (TooManyMfaKeysException _) {
|
||||
return ConfirmTotpKeyResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListTotpKeysResponse listTotpKeys(final ListTotpKeysRequest request) {
|
||||
final ListTotpKeysResponse.Builder responseBuilder = ListTotpKeysResponse.newBuilder();
|
||||
public ListMfaKeysResponse listMfaKeys(final ListMfaKeysRequest request) {
|
||||
final ListMfaKeysResponse.Builder responseBuilder = ListMfaKeysResponse.newBuilder();
|
||||
|
||||
getAuthenticatedAccount().getTotpKeys().forEach((keyId, totpKey) -> {
|
||||
assert totpKey.metadataCiphertext() != null;
|
||||
getAuthenticatedAccount().getMfaKeys().forEach((keyId, mfaKey) -> {
|
||||
assert mfaKey.metadataCiphertext() != null;
|
||||
|
||||
responseBuilder.putKeys(keyId, ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
|
||||
.setMetadataCiphertext(ByteString.copyFrom(totpKey.metadataCiphertext()))
|
||||
.setTotpParameters(toGrpcTotpParameters(totpKey.totpKey().totpParameters()))
|
||||
.build());
|
||||
ListMfaKeysResponse.MfaKeyMetadata.Builder metadataBuilder = ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
|
||||
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()));
|
||||
|
||||
switch (mfaKey) {
|
||||
case AnnotatedTotpKey k -> metadataBuilder.setTotpParameters(toGrpcTotpParameters(k.totpKey().totpParameters()));
|
||||
}
|
||||
|
||||
responseBuilder.putKeys(keyId, metadataBuilder.build());
|
||||
});
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetTotpKeyMetadataResponse setTotpKeyMetadata(final SetTotpKeyMetadataRequest request) {
|
||||
final byte keyId = validateTotpKeyId(request.getKeyId());
|
||||
public SetMfaKeyMetadataResponse setMfaKeyMetadata(final SetMfaKeyMetadataRequest request) {
|
||||
final byte keyId = validateMfaKeyId(request.getKeyId());
|
||||
|
||||
try {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(keyId);
|
||||
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
@Nullable final AnnotatedMfaKey existingKey = mfaKeys.get(keyId);
|
||||
|
||||
if (existingKey == null) {
|
||||
throw new TotpKeyNotFoundException();
|
||||
throw new MfaKeyNotFoundException();
|
||||
}
|
||||
|
||||
totpKeys.put(keyId, new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
|
||||
mfaKeys.put(keyId, existingKey.withMetadataCiphertext(request.getMetadataCiphertext().toByteArray()));
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
account.setMfaKeys(mfaKeys);
|
||||
});
|
||||
|
||||
return SetTotpKeyMetadataResponse.newBuilder()
|
||||
.setMetadataUpdated(SetTotpKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
.setMetadataUpdated(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final TotpKeyNotFoundException _) {
|
||||
return SetTotpKeyMetadataResponse.newBuilder()
|
||||
} catch (final MfaKeyNotFoundException _) {
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
.setKeyNotFound(NotFound.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoveTotpKeyResponse removeTotpKey(final RemoveTotpKeyRequest request) {
|
||||
final byte keyId = validateTotpKeyId(request.getKeyId());
|
||||
public RemoveMfaKeyResponse removeMfaKey(final RemoveMfaKeyRequest request) {
|
||||
final byte keyId = validateMfaKeyId(request.getKeyId());
|
||||
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
totpKeys.remove(keyId);
|
||||
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
mfaKeys.remove(keyId);
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
account.setMfaKeys(mfaKeys);
|
||||
});
|
||||
|
||||
return RemoveTotpKeyResponse.getDefaultInstance();
|
||||
return RemoveMfaKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private byte validateTotpKeyId(final int keyId) {
|
||||
if (keyId < 0 || keyId > Account.MAX_TOTP_KEY_ID) {
|
||||
throw GrpcExceptions.invalidArguments("TOTP key ID out of range");
|
||||
private byte validateMfaKeyId(final int keyId) {
|
||||
if (keyId < 0 || keyId > Account.MAX_MFA_KEY_ID) {
|
||||
throw GrpcExceptions.invalidArguments("MFA key ID out of range");
|
||||
}
|
||||
|
||||
return (byte) keyId;
|
||||
|
||||
@@ -49,7 +49,7 @@ import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
|
||||
@JsonFilter("Account")
|
||||
public class Account {
|
||||
|
||||
public static final int MAX_TOTP_KEY_ID = Byte.MAX_VALUE;
|
||||
public static final int MAX_MFA_KEY_ID = Byte.MAX_VALUE;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Account.class);
|
||||
|
||||
@@ -165,8 +165,8 @@ public class Account {
|
||||
@Nullable
|
||||
private TotpKey pendingTotpKey;
|
||||
|
||||
@JsonProperty("totp")
|
||||
private Map<Byte, AnnotatedTotpKey> totpKeys = Collections.emptyMap();
|
||||
@JsonProperty("mfa")
|
||||
private Map<Byte, AnnotatedMfaKey> mfaKeys = Collections.emptyMap();
|
||||
|
||||
@JsonIgnore
|
||||
private boolean stale;
|
||||
@@ -673,25 +673,25 @@ public class Account {
|
||||
return Optional.ofNullable(pendingTotpKey);
|
||||
}
|
||||
|
||||
public byte getNextTotpKeyId() {
|
||||
public byte getNextMfaKeyId() {
|
||||
requireNotStale();
|
||||
|
||||
final Set<Byte> usedKeys = new HashSet<>(totpKeys.keySet());
|
||||
final Set<Byte> usedKeys = new HashSet<>(mfaKeys.keySet());
|
||||
|
||||
return (byte) IntStream.range(0, MAX_TOTP_KEY_ID + 1)
|
||||
return (byte) IntStream.range(0, MAX_MFA_KEY_ID + 1)
|
||||
.filter(b -> !usedKeys.contains((byte) b))
|
||||
.findFirst()
|
||||
.orElseThrow(IllegalStateException::new);
|
||||
}
|
||||
|
||||
public Map<Byte, AnnotatedTotpKey> getTotpKeys() {
|
||||
public Map<Byte, AnnotatedMfaKey> getMfaKeys() {
|
||||
requireNotStale();
|
||||
return totpKeys;
|
||||
return mfaKeys;
|
||||
}
|
||||
|
||||
public void setTotpKeys(final Map<Byte, AnnotatedTotpKey> totpKeys) {
|
||||
public void setMfaKeys(final Map<Byte, AnnotatedMfaKey> mfaKeys) {
|
||||
requireNotStale();
|
||||
this.totpKeys = totpKeys;
|
||||
this.mfaKeys = mfaKeys;
|
||||
}
|
||||
|
||||
public void markStale() {
|
||||
|
||||
@@ -410,9 +410,9 @@ public class Accounts {
|
||||
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
|
||||
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
|
||||
|
||||
// Carry over any existing TOTP keys to the new account; we don't need to copy the pending TOTP key since that's
|
||||
// Carry over any existing MFA keys to the new account; we don't need to copy the pending TOTP key since that's
|
||||
// just a temporary holding place for essentially ephemeral data
|
||||
accountToCreate.setTotpKeys(new HashMap<>(existingAccount.getTotpKeys()));
|
||||
accountToCreate.setMfaKeys(new HashMap<>(existingAccount.getMfaKeys()));
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
|
||||
+30
-11
@@ -210,6 +210,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
new TotpParameters(TOTP.getAlgorithm(), TOTP.getPasswordLength(), TOTP.getTimeStep());
|
||||
|
||||
public static final int MAX_TOTP_KEYS = 2;
|
||||
public static final int MAX_MFA_KEYS = 10;
|
||||
|
||||
public enum DeletionReason {
|
||||
ADMIN_DELETED("admin"),
|
||||
@@ -282,6 +283,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private static class UncheckedTooManyTotpKeysException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
private static class UncheckedTooManyMfaKeysException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
public AccountsManager(final Accounts accounts,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
@@ -2025,20 +2029,25 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
/// @see [#confirmPendingTotpKey(UUID, int, Instant, byte[])
|
||||
///
|
||||
/// @throws TooManyTotpKeysException if the target account already has at least [#MAX_TOTP_KEYS] TOTP keys
|
||||
public TotpKey generatePendingTotpKey(final UUID accountIdentifier) throws TooManyTotpKeysException {
|
||||
/// @throws TooManyMfaKeysException if the target account already has at least [#MAX_MFA_KEYS] total MFA keys
|
||||
public TotpKey generatePendingTotpKey(final UUID accountIdentifier) throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
final SecretKey secretKey = totpKeyGenerator.generateKey();
|
||||
final TotpKey pendingTotpKey = new TotpKey(TOTP_PARAMETERS, secretKey.getEncoded());
|
||||
|
||||
try {
|
||||
update(accountIdentifier, account -> {
|
||||
if (account.getTotpKeys().size() >= MAX_TOTP_KEYS) {
|
||||
if (account.getMfaKeys().values().stream().filter(AnnotatedTotpKey.class::isInstance).count() >= MAX_TOTP_KEYS) {
|
||||
throw new UncheckedTooManyTotpKeysException();
|
||||
} else if (account.getMfaKeys().size() >= MAX_MFA_KEYS) {
|
||||
throw new UncheckedTooManyMfaKeysException();
|
||||
}
|
||||
|
||||
account.setPendingTotpKey(pendingTotpKey);
|
||||
});
|
||||
} catch (final UncheckedTooManyTotpKeysException _) {
|
||||
throw new TooManyTotpKeysException();
|
||||
} catch (final UncheckedTooManyMfaKeysException _) {
|
||||
throw new TooManyMfaKeysException();
|
||||
}
|
||||
|
||||
return pendingTotpKey;
|
||||
@@ -2055,11 +2064,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
/// TOTP password for the given account or for a one-time password previously verified for the given account or empty
|
||||
/// otherwise
|
||||
///
|
||||
/// @throws TooManyMfaKeysException if the target account already has at least [#MAX_MFA_KEYS] total MFA keys
|
||||
///
|
||||
/// @see [#generatePendingTotpKey(UUID)
|
||||
public Optional<Byte> confirmPendingTotpKey(final UUID accountIdentifier,
|
||||
final int oneTimePassword,
|
||||
final Instant timestamp,
|
||||
final byte[] metadataCiphertext) {
|
||||
final byte[] metadataCiphertext) throws TooManyMfaKeysException {
|
||||
|
||||
final Optional<Account> maybeAccount = accounts.getByAccountIdentifier(accountIdentifier);
|
||||
|
||||
@@ -2077,21 +2088,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final AtomicInteger keyId = new AtomicInteger();
|
||||
|
||||
update(accountIdentifier, account -> {
|
||||
final Map<Byte, AnnotatedTotpKey> updatedTotpKeys = new HashMap<>(account.getTotpKeys());
|
||||
final Map<Byte, AnnotatedMfaKey> updatedMfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
|
||||
keyId.set(account.getNextTotpKeyId());
|
||||
if (updatedMfaKeys.size() >= MAX_MFA_KEYS) {
|
||||
throw new UncheckedTooManyMfaKeysException();
|
||||
}
|
||||
|
||||
updatedTotpKeys.put((byte) keyId.get(),
|
||||
keyId.set(account.getNextMfaKeyId());
|
||||
|
||||
updatedMfaKeys.put((byte) keyId.get(),
|
||||
new AnnotatedTotpKey(new TotpKey(pendingTotpKey.totpParameters(), pendingTotpKey.encodedKey()), metadataCiphertext));
|
||||
|
||||
account.setPendingTotpKey(null);
|
||||
account.setTotpKeys(updatedTotpKeys);
|
||||
account.setMfaKeys(updatedMfaKeys);
|
||||
});
|
||||
|
||||
return Optional.of((byte) keyId.get());
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
ImpossibleEvents.logImpossible(logger, "Invalid pending TOTP key for account {}", accountIdentifier, e);
|
||||
} catch (final UncheckedTooManyMfaKeysException _) {
|
||||
throw new TooManyMfaKeysException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2105,11 +2122,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
// possible that a user will have iterated through so many keys that they've wrapped around into negative integers,
|
||||
// but that's not really a practical concern.
|
||||
return getByAccountIdentifier(accountIdentifier)
|
||||
.flatMap(account -> account.getTotpKeys().entrySet().stream()
|
||||
.flatMap(account -> account.getMfaKeys().entrySet().stream()
|
||||
.filter(entry -> entry.getValue() instanceof AnnotatedTotpKey)
|
||||
.max(Map.Entry.comparingByKey())
|
||||
.filter(entry -> {
|
||||
try {
|
||||
return TOTP.validateOneTimePassword(entry.getValue(), timestamp, oneTimePassword);
|
||||
return TOTP.validateOneTimePassword((AnnotatedTotpKey) entry.getValue(), timestamp, oneTimePassword);
|
||||
} catch (final InvalidKeyException e) {
|
||||
ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", accountIdentifier, e);
|
||||
return false;
|
||||
@@ -2119,7 +2137,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
public boolean verifyTotp(final Account account, final Instant validationTimestamp, @Nullable final Integer oneTimePassword) {
|
||||
if (account.getTotpKeys().isEmpty()) {
|
||||
final List<AnnotatedTotpKey> totpKeys = account.getMfaKeys().values().stream().filter(AnnotatedTotpKey.class::isInstance).map(AnnotatedTotpKey.class::cast).toList();
|
||||
if (totpKeys.isEmpty()) {
|
||||
return oneTimePassword == null;
|
||||
}
|
||||
|
||||
@@ -2129,7 +2148,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
for (final Instant timestamp : new Instant[] { validationTimestamp, validationTimestamp.minus(maxTotpValidationDelay) }) {
|
||||
for (final SecretKey totpKey : account.getTotpKeys().values()) {
|
||||
for (final SecretKey totpKey : totpKeys) {
|
||||
try {
|
||||
if (TOTP.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) {
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
|
||||
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, property = "type")
|
||||
@JsonSubTypes({@JsonSubTypes.Type(value=AnnotatedTotpKey.class, name = "totp")})
|
||||
public sealed interface AnnotatedMfaKey permits AnnotatedTotpKey {
|
||||
byte[] metadataCiphertext();
|
||||
AnnotatedMfaKey withMetadataCiphertext(byte[] newCiphertext);
|
||||
}
|
||||
+6
-1
@@ -15,7 +15,7 @@ public record AnnotatedTotpKey(@JsonUnwrapped
|
||||
TotpKey totpKey,
|
||||
|
||||
@JsonProperty("metadata")
|
||||
byte[] metadataCiphertext) implements SecretKey {
|
||||
byte[] metadataCiphertext) implements SecretKey, AnnotatedMfaKey {
|
||||
|
||||
@Override
|
||||
public String getAlgorithm() {
|
||||
@@ -45,4 +45,9 @@ public record AnnotatedTotpKey(@JsonUnwrapped
|
||||
public int hashCode() {
|
||||
return Objects.hash(totpKey, Arrays.hashCode(metadataCiphertext));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnnotatedMfaKey withMetadataCiphertext(byte[] newCiphertext) {
|
||||
return new AnnotatedTotpKey(totpKey(), newCiphertext);
|
||||
}
|
||||
}
|
||||
+11
@@ -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.util.NoStackTraceException;
|
||||
|
||||
public class TooManyMfaKeysException extends NoStackTraceException {
|
||||
}
|
||||
@@ -87,15 +87,15 @@ service Accounts {
|
||||
// key for the caller's account
|
||||
rpc ConfirmTotpKey(ConfirmTotpKeyRequest) returns (ConfirmTotpKeyResponse) {}
|
||||
|
||||
// Returns a list of confirmed TOTP keys for the authenticated account
|
||||
rpc ListTotpKeys(ListTotpKeysRequest) returns (ListTotpKeysResponse) {}
|
||||
// Returns a list of confirmed MFA keys for the authenticated account
|
||||
rpc ListMfaKeys(ListMfaKeysRequest) returns (ListMfaKeysResponse) {}
|
||||
|
||||
// Updates encrypted, user-supplied metadata (e.g. a human-readable name and
|
||||
// creation timestamp) for an existing, confirmed TOTP key
|
||||
rpc SetTotpKeyMetadata(SetTotpKeyMetadataRequest) returns (SetTotpKeyMetadataResponse) {}
|
||||
// creation timestamp) for an existing, confirmed MFA key
|
||||
rpc SetMfaKeyMetadata(SetMfaKeyMetadataRequest) returns (SetMfaKeyMetadataResponse) {}
|
||||
|
||||
// Removes a TOTP from the authenticated account
|
||||
rpc RemoveTotpKey(RemoveTotpKeyRequest) returns (RemoveTotpKeyResponse) {}
|
||||
// Removes an MFA key from the authenticated account
|
||||
rpc RemoveMfaKey(RemoveMfaKeyRequest) returns (RemoveMfaKeyResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for looking up Signal accounts. Callers must not provide
|
||||
@@ -533,6 +533,10 @@ message GenerateTotpKeyResponse {
|
||||
// The authenticated account already has too many TOTP keys, and the caller
|
||||
// must remove one before adding more
|
||||
errors.FailedPrecondition too_many_totp_keys = 2 [(tag.reason) = "too_many_totp_keys"];
|
||||
|
||||
// The authenticated account already has too many MFA keys of all types, and
|
||||
// the caller must remove one before adding more
|
||||
errors.FailedPrecondition too_many_mfa_keys = 3 [(tag.reason) = "too_many_mfa_keys"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,25 +564,31 @@ message ConfirmTotpKeyResponse {
|
||||
// The provided one-time password was not valid for any reason (including
|
||||
// incorrect passwords, misaligned clocks, or missing account records)
|
||||
errors.FailedPrecondition one_time_password_not_verified = 2 [(tag.reason) = "one_time_password_not_verified"];
|
||||
|
||||
// The authenticated account already has too many MFA keys of all types, and
|
||||
// the caller must remove one before adding more
|
||||
errors.FailedPrecondition too_many_mfa_keys = 3 [(tag.reason) = "too_many_mfa_keys"];
|
||||
}
|
||||
}
|
||||
|
||||
message ListTotpKeysRequest {}
|
||||
message ListMfaKeysRequest {}
|
||||
|
||||
message ListTotpKeysResponse {
|
||||
message TotpKeyMetadata {
|
||||
// The user-provided ciphertext for metadata associated with this TOTP key
|
||||
message ListMfaKeysResponse {
|
||||
message MfaKeyMetadata {
|
||||
// The user-provided ciphertext for metadata associated with this MFA key
|
||||
bytes metadata_ciphertext = 1 [(require.exactlySize) = 160];
|
||||
|
||||
// The TOTP parameters associated with this key
|
||||
TotpParameters totp_parameters = 2;
|
||||
oneof mfa_key {
|
||||
// The TOTP parameters associated with this key, which is a TOTP key
|
||||
TotpParameters totp_parameters = 2;
|
||||
}
|
||||
}
|
||||
|
||||
map<uint32, TotpKeyMetadata> keys = 1;
|
||||
map<uint32, MfaKeyMetadata> keys = 1;
|
||||
}
|
||||
|
||||
message SetTotpKeyMetadataRequest {
|
||||
// The account-specific identifier of the TOTP key to modify
|
||||
message SetMfaKeyMetadataRequest {
|
||||
// The account-specific identifier of the MFA key to modify
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
|
||||
// The ciphertext of the new user-provided metadata to be attached to the
|
||||
@@ -586,7 +596,7 @@ message SetTotpKeyMetadataRequest {
|
||||
bytes metadata_ciphertext = 2 [(require.exactlySize) = 160];
|
||||
}
|
||||
|
||||
message SetTotpKeyMetadataResponse {
|
||||
message SetMfaKeyMetadataResponse {
|
||||
message MetadataUpdated {
|
||||
}
|
||||
|
||||
@@ -599,10 +609,10 @@ message SetTotpKeyMetadataResponse {
|
||||
}
|
||||
}
|
||||
|
||||
message RemoveTotpKeyRequest {
|
||||
// The account-specific identifier of the TOTP key to remove
|
||||
message RemoveMfaKeyRequest {
|
||||
// The account-specific identifier of the MFA key to remove
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
}
|
||||
|
||||
message RemoveTotpKeyResponse {
|
||||
message RemoveMfaKeyResponse {
|
||||
}
|
||||
+74
-45
@@ -73,18 +73,18 @@ import org.signal.chat.account.GetCapabilitiesRequest;
|
||||
import org.signal.chat.account.GetCapabilitiesResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ListTotpKeysRequest;
|
||||
import org.signal.chat.account.ListTotpKeysResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.RemoveTotpKeyRequest;
|
||||
import org.signal.chat.account.RemoveMfaKeyRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockResponse;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
@@ -123,6 +123,7 @@ import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -130,6 +131,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
@@ -167,7 +169,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
AccountsManager.TOTP.getPasswordLength(),
|
||||
AccountsManager.TOTP.getTimeStep());
|
||||
|
||||
private static final int TOTP_KEY_METADATA_SIZE = 160;
|
||||
private static final int MFA_KEY_METADATA_SIZE = 160;
|
||||
|
||||
@Override
|
||||
protected AccountsGrpcService createServiceBeforeEachTest() {
|
||||
@@ -1124,7 +1126,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateTotpKey() throws TooManyTotpKeysException {
|
||||
void generateTotpKey() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
final byte[] encodedKey = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(accountsManager.generatePendingTotpKey(AUTHENTICATED_ACI))
|
||||
@@ -1142,7 +1144,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateTotpKeyTooManyKeys() throws TooManyTotpKeysException {
|
||||
void generateTotpKeyTooManyKeys() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
when(accountsManager.generatePendingTotpKey(AUTHENTICATED_ACI))
|
||||
.thenThrow(TooManyTotpKeysException.class);
|
||||
|
||||
@@ -1153,10 +1155,22 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmTotpKey() {
|
||||
void generateTotpKeyTooManyNonTotpKeys() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
when(accountsManager.generatePendingTotpKey(AUTHENTICATED_ACI))
|
||||
.thenThrow(TooManyMfaKeysException.class);
|
||||
|
||||
final GenerateTotpKeyResponse response =
|
||||
authenticatedServiceStub().generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
|
||||
|
||||
assertEquals(GenerateTotpKeyResponse.ResponseCase.TOO_MANY_MFA_KEYS, response.getResponseCase());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void confirmTotpKey() throws TooManyMfaKeysException {
|
||||
final byte keyId = 17;
|
||||
final int oneTimePassword = 123456;
|
||||
final byte[] metadataCiphertext = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
|
||||
final byte[] metadataCiphertext = TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE);
|
||||
|
||||
when(accountsManager.confirmPendingTotpKey(AUTHENTICATED_ACI, oneTimePassword, testClock.instant(), metadataCiphertext))
|
||||
.thenReturn(Optional.of(keyId));
|
||||
@@ -1175,37 +1189,52 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(123456)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE + 1)))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE + 1)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmTotpKeyPasswordNotVerified() {
|
||||
void confirmTotpKeyPasswordNotVerified() throws TooManyMfaKeysException {
|
||||
when(accountsManager.confirmPendingTotpKey(any(), anyInt(), any(), any()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
final ConfirmTotpKeyResponse response = authenticatedServiceStub().confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(123456)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build());
|
||||
|
||||
assertEquals(ConfirmTotpKeyResponse.ResponseCase.ONE_TIME_PASSWORD_NOT_VERIFIED, response.getResponseCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmTotpKeyTooManyNonTotpKeys() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
when(accountsManager.confirmPendingTotpKey(any(), anyInt(), any(), any()))
|
||||
.thenThrow(TooManyMfaKeysException.class);
|
||||
|
||||
final ConfirmTotpKeyResponse response =
|
||||
authenticatedServiceStub().confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(123456)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build());
|
||||
|
||||
assertEquals(ConfirmTotpKeyResponse.ResponseCase.TOO_MANY_MFA_KEYS, response.getResponseCase());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void listTotpKeys() {
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = Map.of(
|
||||
final Map<Byte, AnnotatedMfaKey> totpKeys = Map.of(
|
||||
(byte) 1, generateRandomAnnotatedTotpKey(),
|
||||
(byte) 2, generateRandomAnnotatedTotpKey());
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(totpKeys);
|
||||
when(account.getMfaKeys()).thenReturn(totpKeys);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final ListTotpKeysResponse response =
|
||||
authenticatedServiceStub().listTotpKeys(ListTotpKeysRequest.getDefaultInstance());
|
||||
final ListMfaKeysResponse response =
|
||||
authenticatedServiceStub().listMfaKeys(ListMfaKeysRequest.getDefaultInstance());
|
||||
|
||||
final TotpParameters expectedTotpParameters = TotpParameters.newBuilder()
|
||||
.setAlgorithm(AccountsManager.TOTP.getAlgorithm())
|
||||
@@ -1213,8 +1242,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
.setTimeStepSeconds(Math.toIntExact(AccountsManager.TOTP.getTimeStep().toSeconds()))
|
||||
.build();
|
||||
|
||||
final Map<Integer, ListTotpKeysResponse.TotpKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
|
||||
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
|
||||
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
|
||||
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
|
||||
.setTotpParameters(expectedTotpParameters)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(entry.getValue().metadataCiphertext()))
|
||||
.build()));
|
||||
@@ -1224,58 +1253,58 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadata() {
|
||||
final byte keyId = (byte) ThreadLocalRandom.current().nextInt(Account.MAX_TOTP_KEY_ID);
|
||||
final byte[] updatedMetadata = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
|
||||
final AnnotatedTotpKey existingTotpKey = generateRandomAnnotatedTotpKey();
|
||||
final byte keyId = (byte) ThreadLocalRandom.current().nextInt(Account.MAX_MFA_KEY_ID);
|
||||
final byte[] updatedMetadata = TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE);
|
||||
final AnnotatedMfaKey existingTotpKey = generateRandomAnnotatedTotpKey();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(Map.of(keyId, existingTotpKey));
|
||||
when(account.getMfaKeys()).thenReturn(Map.of(keyId, existingTotpKey));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final SetTotpKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
final SetMfaKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(keyId)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(updatedMetadata))
|
||||
.build());
|
||||
|
||||
assertEquals(SetTotpKeyMetadataResponse.ResponseCase.METADATA_UPDATED, response.getResponseCase());
|
||||
verify(account).setTotpKeys(Map.of(keyId, new AnnotatedTotpKey(existingTotpKey.totpKey(), updatedMetadata)));
|
||||
assertEquals(SetMfaKeyMetadataResponse.ResponseCase.METADATA_UPDATED, response.getResponseCase());
|
||||
verify(account).setMfaKeys(Map.of(keyId, existingTotpKey.withMetadataCiphertext(updatedMetadata)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadataKeyNotFound() {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(Collections.emptyMap());
|
||||
when(account.getMfaKeys()).thenReturn(Collections.emptyMap());
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final SetTotpKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(ThreadLocalRandom.current().nextInt(Account.MAX_TOTP_KEY_ID))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
|
||||
final SetMfaKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(ThreadLocalRandom.current().nextInt(Account.MAX_MFA_KEY_ID))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build());
|
||||
|
||||
assertEquals(SetTotpKeyMetadataResponse.ResponseCase.KEY_NOT_FOUND, response.getResponseCase());
|
||||
assertEquals(SetMfaKeyMetadataResponse.ResponseCase.KEY_NOT_FOUND, response.getResponseCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadataIncorrectMetadataSize() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
() -> authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE + 1)))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE + 1)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadataKeyIdOutOfRange() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_TOTP_KEY_ID + 1)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
|
||||
() -> authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_MFA_KEY_ID + 1)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@@ -1284,34 +1313,34 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
final byte retainedKeyId = 1;
|
||||
final byte removedKeyId = 2;
|
||||
|
||||
final Map<Byte, AnnotatedTotpKey> initialKeys = Map.of(
|
||||
final Map<Byte, AnnotatedMfaKey> initialKeys = Map.of(
|
||||
retainedKeyId, generateRandomAnnotatedTotpKey(),
|
||||
removedKeyId, generateRandomAnnotatedTotpKey());
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(initialKeys);
|
||||
when(account.getMfaKeys()).thenReturn(initialKeys);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
authenticatedServiceStub().removeTotpKey(RemoveTotpKeyRequest.newBuilder()
|
||||
authenticatedServiceStub().removeMfaKey(RemoveMfaKeyRequest.newBuilder()
|
||||
.setKeyId(removedKeyId)
|
||||
.build());
|
||||
|
||||
verify(account).setTotpKeys(Map.of(retainedKeyId, initialKeys.get(retainedKeyId)));
|
||||
verify(account).setMfaKeys(Map.of(retainedKeyId, initialKeys.get(retainedKeyId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeTotpKeyIdOutOfRange() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().removeTotpKey(RemoveTotpKeyRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_TOTP_KEY_ID + 1)
|
||||
() -> authenticatedServiceStub().removeMfaKey(RemoveMfaKeyRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_MFA_KEY_ID + 1)
|
||||
.build()));
|
||||
}
|
||||
|
||||
private static AnnotatedTotpKey generateRandomAnnotatedTotpKey() {
|
||||
return new AnnotatedTotpKey(new TotpKey(TOTP_PARAMETERS, TestRandomUtil.nextBytes(32)),
|
||||
TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE));
|
||||
TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE));
|
||||
}
|
||||
}
|
||||
@@ -290,7 +290,7 @@ class AccountTest {
|
||||
@MethodSource
|
||||
void getNextTotpKeyId(final List<Byte> existingKeyIds, final byte expectedNextKeyId) {
|
||||
final Account account = new Account();
|
||||
account.setTotpKeys(existingKeyIds.stream()
|
||||
account.setMfaKeys(existingKeyIds.stream()
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
|
||||
@@ -299,13 +299,13 @@ class AccountTest {
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
assertEquals(expectedNextKeyId, account.getNextTotpKeyId());
|
||||
assertEquals(expectedNextKeyId, account.getNextMfaKeyId());
|
||||
}
|
||||
|
||||
private static List<Arguments> getNextTotpKeyId() {
|
||||
final byte unclaimedId = 17;
|
||||
|
||||
final List<Byte> mostIdsTaken = IntStream.range(0, Account.MAX_TOTP_KEY_ID)
|
||||
final List<Byte> mostIdsTaken = IntStream.range(0, Account.MAX_MFA_KEY_ID)
|
||||
.filter(i -> i != unclaimedId)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
@@ -322,7 +322,7 @@ class AccountTest {
|
||||
@Test
|
||||
void getNextTotpKeyNoneAvailable() {
|
||||
final Account account = new Account();
|
||||
account.setTotpKeys(IntStream.range(0, Account.MAX_TOTP_KEY_ID + 1)
|
||||
account.setMfaKeys(IntStream.range(0, Account.MAX_MFA_KEY_ID + 1)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
@@ -332,6 +332,6 @@ class AccountTest {
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
assertThrows(IllegalStateException.class, account::getNextTotpKeyId);
|
||||
assertThrows(IllegalStateException.class, account::getNextMfaKeyId);
|
||||
}
|
||||
}
|
||||
+14
-15
@@ -1299,7 +1299,6 @@ class AccountsManagerTest {
|
||||
verify(accounts, expectUpdate ? times(1) : never()).update(account);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static Stream<Arguments> testUpdateDeviceLastSeen() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, 1, 2),
|
||||
@@ -1937,7 +1936,7 @@ class AccountsManagerTest {
|
||||
class Totp {
|
||||
|
||||
@Test
|
||||
void generatePendingTotpKey() throws TooManyTotpKeysException {
|
||||
void generatePendingTotpKey() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -1958,7 +1957,7 @@ class AccountsManagerTest {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getAccountIdentifier()).thenReturn(accountIdentifier);
|
||||
|
||||
when(account.getTotpKeys()).thenReturn(IntStream.range(0, AccountsManager.MAX_TOTP_KEYS)
|
||||
when(account.getMfaKeys()).thenReturn(IntStream.range(0, AccountsManager.MAX_TOTP_KEYS)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(Integer::byteValue, _ -> new AnnotatedTotpKey(
|
||||
new TotpKey(TOTP_PARAMETERS, TestRandomUtil.nextBytes(16)),
|
||||
@@ -1972,7 +1971,7 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKey() throws InvalidKeyException, TooManyTotpKeysException, NoSuchAlgorithmException {
|
||||
void confirmPendingTotpKey() throws InvalidKeyException, TooManyTotpKeysException, TooManyMfaKeysException, NoSuchAlgorithmException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -1985,7 +1984,7 @@ class AccountsManagerTest {
|
||||
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
|
||||
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
|
||||
when(account.getNextMfaKeyId()).thenReturn(nextTotpKeyId);
|
||||
|
||||
final Instant timestamp = Instant.now();
|
||||
|
||||
@@ -1998,7 +1997,7 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKeyPreviouslyConfirmed() throws InvalidKeyException, NoSuchAlgorithmException {
|
||||
void confirmPendingTotpKeyPreviouslyConfirmed() throws InvalidKeyException, NoSuchAlgorithmException, TooManyMfaKeysException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -2020,7 +2019,7 @@ class AccountsManagerTest {
|
||||
final byte keyId = 17;
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.empty());
|
||||
when(account.getTotpKeys()).thenReturn(Map.of(
|
||||
when(account.getMfaKeys()).thenReturn(Map.of(
|
||||
(byte) (keyId - 1), confirmedTotpKey,
|
||||
keyId, confirmedTotpKey));
|
||||
|
||||
@@ -2033,7 +2032,7 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKeyNoKeys() throws InvalidKeyException, TooManyTotpKeysException, NoSuchAlgorithmException {
|
||||
void confirmPendingTotpKeyNoKeys() throws InvalidKeyException, TooManyTotpKeysException, TooManyMfaKeysException, NoSuchAlgorithmException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -2045,7 +2044,7 @@ class AccountsManagerTest {
|
||||
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.empty());
|
||||
when(account.getTotpKeys()).thenReturn(Collections.emptyMap());
|
||||
when(account.getMfaKeys()).thenReturn(Collections.emptyMap());
|
||||
|
||||
final Instant timestamp = Instant.now();
|
||||
|
||||
@@ -2057,7 +2056,7 @@ class AccountsManagerTest {
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKeyIncorrectPassword()
|
||||
throws InvalidKeyException, TooManyTotpKeysException, NoSuchAlgorithmException {
|
||||
throws InvalidKeyException, TooManyTotpKeysException, TooManyMfaKeysException, NoSuchAlgorithmException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -2070,7 +2069,7 @@ class AccountsManagerTest {
|
||||
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
|
||||
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
|
||||
when(account.getNextMfaKeyId()).thenReturn(nextTotpKeyId);
|
||||
|
||||
final Instant timestamp = Instant.now();
|
||||
final int incorrectPassword = AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp) + 1;
|
||||
@@ -2086,13 +2085,13 @@ class AccountsManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void verifyTotp(final Map<Byte, AnnotatedTotpKey> totpKeys,
|
||||
void verifyTotp(final Map<Byte, AnnotatedMfaKey> mfaKeys,
|
||||
final Instant timestamp,
|
||||
@Nullable final Integer oneTimePassword,
|
||||
final boolean expectVerified) {
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(totpKeys);
|
||||
when(account.getMfaKeys()).thenReturn(mfaKeys);
|
||||
|
||||
assertEquals(expectVerified, accountsManager.verifyTotp(account, timestamp, oneTimePassword));
|
||||
}
|
||||
@@ -2137,7 +2136,7 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
@RepeatedTest(value = 10, failureThreshold = 2)
|
||||
void verifyTotpWithDelay() throws NoSuchAlgorithmException, InvalidKeyException {
|
||||
void verifyTotpWithDelay() throws NoSuchAlgorithmException, InvalidKeyException, TooManyMfaKeysException {
|
||||
final AnnotatedTotpKey totpKey;
|
||||
{
|
||||
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP.getAlgorithm());
|
||||
@@ -2149,7 +2148,7 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(Map.of((byte) 1, totpKey));
|
||||
when(account.getMfaKeys()).thenReturn(Map.of((byte) 1, totpKey));
|
||||
|
||||
final Instant beginningOfTotpWindow =
|
||||
Instant.ofEpochMilli((Instant.now().toEpochMilli() / AccountsManager.TOTP.getTimeStep().toMillis()) *
|
||||
|
||||
@@ -481,7 +481,6 @@ class AccountsTest {
|
||||
assertThat(account.getReservedUsernameHash()).isEmpty();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
static ArgumentSets reclaimAccountWithNoUsername() {
|
||||
return ArgumentSets.argumentsForFirstParameter(UsernameStatus.values())
|
||||
// number
|
||||
@@ -567,7 +566,7 @@ class AccountsTest {
|
||||
generateAccount(number, existingUuid, number == null ? null : UUID.randomUUID(),
|
||||
List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
|
||||
existingAccount.setTotpKeys(Map.of((byte) 1, new AnnotatedTotpKey(new TotpKey(
|
||||
existingAccount.setMfaKeys(Map.of((byte) 1, new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA1,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
@@ -594,7 +593,7 @@ class AccountsTest {
|
||||
|
||||
final Account reclaimed = accounts.getByAccountIdentifier(existingUuid).orElseThrow();
|
||||
|
||||
assertThat(reclaimed.getTotpKeys()).isEqualTo(existingAccount.getTotpKeys());
|
||||
assertThat(reclaimed.getMfaKeys()).isEqualTo(existingAccount.getMfaKeys());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
Reference in new issue
Block a user