gRPC endpoints to verify existing MFA tokens

This commit is contained in:
Jonathan Klabunde Tomer authored and Jonathan Klabunde Tomer committed 2026-09-16 10:37:50 -07:00
1 parent 79757458d6
commit 4f4bd431f5
3 files changed
+261 -1

No files matched your search

@@ -42,6 +42,8 @@ import org.signal.chat.account.DeleteUsernameHashResponse;
import org.signal.chat.account.DeleteUsernameLinkRequest;
import org.signal.chat.account.DeleteUsernameLinkResponse;
import org.signal.chat.account.ExternalServiceCredentials;
import org.signal.chat.account.FinishMfaVerificationRequest;
import org.signal.chat.account.FinishMfaVerificationResponse;
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
@@ -57,6 +59,7 @@ import org.signal.chat.account.GetEntitlementsResponse;
import org.signal.chat.account.ListMfaKeysRequest;
import org.signal.chat.account.ListMfaKeysResponse;
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
import org.signal.chat.account.StartMfaVerificationResponse.WebAuthnAuthenticationParameters;
import org.signal.chat.account.RegistrationLockFailure;
import org.signal.chat.account.RemoveMfaKeyRequest;
import org.signal.chat.account.RemoveMfaKeyResponse;
@@ -76,6 +79,8 @@ import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.SimpleAccountsGrpc;
import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.StartMfaVerificationRequest;
import org.signal.chat.account.StartMfaVerificationResponse;
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
import org.signal.chat.account.StartWebAuthnRegistrationResponse.WebAuthnCreateParameters;
@@ -97,6 +102,7 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
@@ -737,6 +743,36 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return RemoveMfaKeyResponse.getDefaultInstance();
}
@Override
public StartMfaVerificationResponse startMfaVerification(final StartMfaVerificationRequest request) {
final Account account = getAuthenticatedAccount();
final StartMfaVerificationResponse.Builder builder = StartMfaVerificationResponse.newBuilder()
.setHasTotp(account.getMfaKeys().values().stream().anyMatch(AnnotatedTotpKey.class::isInstance));
accountsManager.startWebAuthnAuthentication(account)
.map(AccountsGrpcService::toGrpcWebAuthnAuthenticationParameters)
.ifPresent(builder::setWebauthnAuthenticationParameters);
return builder.build();
}
@Override
public FinishMfaVerificationResponse finishMfaVerification(final FinishMfaVerificationRequest request) throws RateLimitExceededException {
rateLimiters.getCheckMfaLimiter().validate(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
final Account account = getAuthenticatedAccount();
final boolean success = switch (request.getCredentialCase()) {
case TOTP_PASSWORD -> accountsManager.verifyTotp(account, clock.instant(), request.getTotpPassword());
case WEBAUTHN_AUTHENTICATION_RESPONSE_JSON ->
accountsManager.verifyWebAuthnAuthentication(account, request.getWebauthnAuthenticationResponseJson()).isPresent();
case CREDENTIAL_NOT_SET -> false;
};
return FinishMfaVerificationResponse.newBuilder().setSuccess(success).build();
}
private byte validateMfaKeyId(final int keyId) {
if (keyId < 0 || keyId > Account.MAX_MFA_KEY_ID) {
throw GrpcExceptions.invalidArguments("MFA key ID out of range");
@@ -753,6 +789,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
.build();
}
private static WebAuthnAuthenticationParameters toGrpcWebAuthnAuthenticationParameters(final AuthenticationCeremonyParameters parameters) {
return WebAuthnAuthenticationParameters.newBuilder()
.setChallenge(ByteString.copyFrom(parameters.challenge()))
.setTimeoutSeconds((int) parameters.timeout().toSeconds())
.addAllAllowedCredentialIds(parameters.allowedCredentialIds().stream().map(ByteString::copyFrom).toList())
.build();
}
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())));
@@ -110,6 +110,12 @@ service Accounts {
// Removes an MFA key from the authenticated account
rpc RemoveMfaKey(RemoveMfaKeyRequest) returns (RemoveMfaKeyResponse) {}
// Requests the parameters needed to verify with an MFA factor associated with this account.
rpc StartMfaVerification(StartMfaVerificationRequest) returns (StartMfaVerificationResponse) {}
// Attemps to verify an MFA factor associated with this account.
rpc FinishMfaVerification(FinishMfaVerificationRequest) returns (FinishMfaVerificationResponse) {}
}
// Provides methods for looking up Signal accounts. Callers must not provide
@@ -698,3 +704,40 @@ message RemoveMfaKeyRequest {
message RemoveMfaKeyResponse {
}
message StartMfaVerificationRequest {
}
message StartMfaVerificationResponse {
/// If true, a TOTP password will be accepted for verification
bool has_totp = 1;
message WebAuthnAuthenticationParameters {
/// A random challenge that must be included in the authenticator response, to prevent replay attacks
bytes challenge = 1;
/// The estimated amount of time, in seconds, after which an otherwise-valid response will be rejected
uint32 timeout_seconds = 2;
/// A list of credential IDs associated with this account
repeated bytes allowed_credential_ids = 3;
}
/// If present, information required to complete a WebAuthn authentication
optional WebAuthnAuthenticationParameters webauthn_authentication_parameters = 2;
}
message FinishMfaVerificationRequest {
oneof credential {
/// A 6-digit TOTP password to validate
uint32 totp_password = 1;
/// A WebAuthn-compatible JSON-serialized authentication response
string webauthn_authentication_response_json = 2;
}
}
message FinishMfaVerificationResponse {
/// If true, the selected authentication factor was verified correctly.
bool success = 1;
}
@@ -9,6 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -67,6 +68,8 @@ import org.signal.chat.account.DeleteAccountResponse;
import org.signal.chat.account.DeleteUsernameHashRequest;
import org.signal.chat.account.DeleteUsernameLinkRequest;
import org.signal.chat.account.ExternalServiceCredentials;
import org.signal.chat.account.FinishMfaVerificationRequest;
import org.signal.chat.account.FinishMfaVerificationResponse;
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
@@ -97,6 +100,8 @@ import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.StartMfaVerificationRequest;
import org.signal.chat.account.StartMfaVerificationResponse;
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
import org.signal.chat.account.UsernameNotAvailable;
@@ -115,6 +120,7 @@ import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
@@ -190,7 +196,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(rateLimiters.getUsernameReserveLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getUsernameSetLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getUsernameLinkOperationLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getCheckMfaLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getSetZkCredentialKeyLimiter()).thenReturn(rateLimiter);
return new AccountsGrpcService(accountsManager,
@@ -1529,6 +1535,173 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.build()));
}
@Test
void startMfaVerification_totp() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getMfaKeys()).thenReturn(Map.of((byte) 1, mock(AnnotatedTotpKey.class)));
when(accountsManager.startWebAuthnAuthentication(account)).thenReturn(Optional.empty());
final StartMfaVerificationResponse response = authenticatedServiceStub().startMfaVerification(StartMfaVerificationRequest.getDefaultInstance());
assertTrue(response.getHasTotp());
assertFalse(response.hasWebauthnAuthenticationParameters());
}
@Test
void startMfaVerification_webAuthn() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getMfaKeys()).thenReturn(
Map.of((byte) 1, mock(AnnotatedWebAuthnCredential.class),
(byte) 2, mock(AnnotatedWebAuthnCredential.class)));
when(accountsManager.startWebAuthnAuthentication(account)).thenReturn(
Optional.of(
new AuthenticationCeremonyParameters("challenge".getBytes(), Duration.ofSeconds(30), List.of("id1".getBytes(), "id2".getBytes()))));
final StartMfaVerificationResponse response = authenticatedServiceStub().startMfaVerification(StartMfaVerificationRequest.getDefaultInstance());
assertFalse(response.getHasTotp());
assertTrue(response.hasWebauthnAuthenticationParameters());
assertArrayEquals("challenge".getBytes(), response.getWebauthnAuthenticationParameters().getChallenge().toByteArray());
assertEquals(30, response.getWebauthnAuthenticationParameters().getTimeoutSeconds());
assertEquals(2, response.getWebauthnAuthenticationParameters().getAllowedCredentialIdsCount());
assertArrayEquals("id1".getBytes(), response.getWebauthnAuthenticationParameters().getAllowedCredentialIds(0).toByteArray());
assertArrayEquals("id2".getBytes(), response.getWebauthnAuthenticationParameters().getAllowedCredentialIds(1).toByteArray());
}
@Test
void startMfaVerification_totpAndWebAuthn() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getMfaKeys()).thenReturn(
Map.of((byte) 1, mock(AnnotatedTotpKey.class),
(byte) 2, mock(AnnotatedWebAuthnCredential.class),
(byte) 3, mock(AnnotatedWebAuthnCredential.class)));
when(accountsManager.startWebAuthnAuthentication(account)).thenReturn(
Optional.of(
new AuthenticationCeremonyParameters("challenge".getBytes(), Duration.ofSeconds(30), List.of("id1".getBytes(), "id2".getBytes()))));
final StartMfaVerificationResponse response = authenticatedServiceStub().startMfaVerification(StartMfaVerificationRequest.getDefaultInstance());
assertTrue(response.getHasTotp());
assertTrue(response.hasWebauthnAuthenticationParameters());
assertArrayEquals("challenge".getBytes(), response.getWebauthnAuthenticationParameters().getChallenge().toByteArray());
assertEquals(30, response.getWebauthnAuthenticationParameters().getTimeoutSeconds());
assertEquals(2, response.getWebauthnAuthenticationParameters().getAllowedCredentialIdsCount());
assertArrayEquals("id1".getBytes(), response.getWebauthnAuthenticationParameters().getAllowedCredentialIds(0).toByteArray());
assertArrayEquals("id2".getBytes(), response.getWebauthnAuthenticationParameters().getAllowedCredentialIds(1).toByteArray());
}
@Test
void startMfaVerification_noMfa() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(account.getMfaKeys()).thenReturn(Map.of());
when(accountsManager.startWebAuthnAuthentication(account)).thenReturn(Optional.empty());
final StartMfaVerificationResponse response = authenticatedServiceStub().startMfaVerification(StartMfaVerificationRequest.getDefaultInstance());
assertFalse(response.getHasTotp());
assertFalse(response.hasWebauthnAuthenticationParameters());
}
@Test
void finishMfaVerification_totp() {
final int oneTimePassword = 123456;
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(accountsManager.verifyTotp(any(), eq(testClock.instant()), eq(oneTimePassword))).thenReturn(true);
final FinishMfaVerificationResponse response = authenticatedServiceStub().finishMfaVerification(
FinishMfaVerificationRequest.newBuilder()
.setTotpPassword(oneTimePassword)
.build());
assertTrue(response.getSuccess());
}
@Test
void finishMfaVerification_totpFailed() {
final int oneTimePassword = 123456;
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(accountsManager.verifyTotp(any(), eq(testClock.instant()), eq(oneTimePassword))).thenReturn(false);
final FinishMfaVerificationResponse response = authenticatedServiceStub().finishMfaVerification(
FinishMfaVerificationRequest.newBuilder()
.setTotpPassword(oneTimePassword)
.build());
assertFalse(response.getSuccess());
}
@Test
void finishMfaVerification_totpRateLimited() throws RateLimitExceededException {
final int oneTimePassword = 123456;
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
doThrow(new RateLimitExceededException(Duration.ofSeconds(1))).when(rateLimiter).validate(AUTHENTICATED_ACI);
GrpcTestUtils.assertRateLimitExceeded(Duration.ofSeconds(1),
() -> authenticatedServiceStub().finishMfaVerification(
FinishMfaVerificationRequest.newBuilder()
.setTotpPassword(oneTimePassword)
.build()),
accountsManager);
}
@Test
void finishMfaVerification_webAuthn() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(accountsManager.verifyWebAuthnAuthentication(any(), eq("good auth json"))).thenReturn(Optional.of(account));
final FinishMfaVerificationResponse response = authenticatedServiceStub().finishMfaVerification(
FinishMfaVerificationRequest.newBuilder()
.setWebauthnAuthenticationResponseJson("good auth json")
.build());
assertTrue(response.getSuccess());
}
@Test
void finishMfaVerification_webAuthnFailed() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
when(accountsManager.verifyWebAuthnAuthentication(any(), eq("bad auth json"))).thenReturn(Optional.empty());
final FinishMfaVerificationResponse response = authenticatedServiceStub().finishMfaVerification(
FinishMfaVerificationRequest.newBuilder()
.setWebauthnAuthenticationResponseJson("bad auth json")
.build());
assertFalse(response.getSuccess());
}
private static AnnotatedWebAuthnCredential generateRandomAnnotatedWebAuthnCredential() {
return new AnnotatedWebAuthnCredential(
new AttestedCredentialData(AAGUID.ZERO, TestRandomUtil.nextBytes(32), TestDataUtil.createEC2COSEPublicKey()),